5

In bitcoin, you can create a script like this:

OP_1 OP_IF OP_RETURN OP_ENDIF

But could you place another if statement inside the first?

OP_1 OP_IF OP_1 OP_IF OP_RETURN OP_ENDIF OP_ENDIF

I grant that this is a bit of a silly example (given that the whole thing could be replaced with OP_RETURN) but is that a valid script?

4

Firstly, I'd like to note that you could change your script to OP_1 OP_1 OP_BOOLAND OP_IF OP_RETURN OP_ENDIF and it would be the same.

I'm reading the bitcoin source code, and I can't see a check for nested OP_IF's. These are the IF related checks I've found:

  • No IF/NOTIF without a value on the stack
  • No ELSE/ENDIF without an IF/NOTIF
  • No IF/NOTIF without an ENDIF

So it would let you nest IF's. In fact, it appears that allowing people to nest IF's is intended. Take this variable, which is used to figure out whether a branch of an IF is executing:

vector<bool> vfExec;

If they didn't want nested IF's, they could have made that a single bool variable.

Amusing fact that I figured out while researching this: The script OP_1 OP_IF OP_ELSE OP_ELSE OP_ENDIF is entirely valid.

  • 1
    Indeed, you can have multiple OP_ELSE's. Each one inverts the meaning, so <a IF b ELSE c ELSE d ENDIF e> is equivalent to <a IF b d ELSE c ENDIF e>. – Pieter Wuille Jan 26 '14 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.