1

For example can we convert the following code to a script?

if(bool_1)
{
    FOO1();
    if(!bool_2)
    {
        FOO2();
    }
    else
    {
        BAR1();
        if(bool_3)
        {
            BAR2();
        }
        BAR3();
    }
}
else
{
    FOOBAR();
}

<push> <push> <push> OP_IF OP_FOO1 OP_NOTIF OP_FOO2 OP_ELSE OP_BAR1 OP_IF OP_BAR2 OP_ENDIF OP_BAR3 OP_ENDIF OP_FOOBAR OP_ENDIF(correct?)

If yes then:
1. Is there any limit on how deep a nested IFs can go?
2. Is there any examples (raw bytes/hex) I could look at?

1

Do bitcoin scripts support nested ifs (OP_IF OP_NOTIF inside one another)?

Yes, Bitcoin support nested IF/ELSE. In fact we use the nested IFs in Lightning Network all the time when adding HTLCs to forward a payment.

Is there any limit on how deep a nested if can go?

There is no explicit rules dictating how far deep the nested IFs can go but there are some constrains on the script itself:

  • Maximum number of bytes pushable to the stack should be less than 520 bytes
  • Maximum operations per script is limited to 201
  • Maximum size of the script is 10,000 bytes
  • Maximum number of values on script interpreter stack is 1,000 bytes

Is there any examples (raw bytes/hex) I could look at?

As I mentioned earlier, we use nested IFs all the time while adding HTLCs in the Lightning Network implementation. Below is an output script of offered HTLC outputs for a peer.

# To remote node with revocation key
OP_DUP OP_HASH160 <RIPEMD160(SHA256(revocationpubkey))> OP_EQUAL
OP_IF
    OP_CHECKSIG
OP_ELSE
    <remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
    OP_NOTIF
        # To local node via HTLC-timeout transaction (timelocked).
        OP_DROP 2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
    OP_ELSE
        # To remote node with preimage.
        OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY
        OP_CHECKSIG
    OP_ENDIF
OP_ENDIF
  • IF/ELSE loops Is "loop" the correct term to use? – Coding Enthusiast Oct 8 at 6:22
  • @CodingEnthusiast thanks for correcting. I wrote the answer from my phone. – Ugam Kamat Oct 8 at 7:45

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.