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
<remote_htlcpubkey> OP_SWAP OP_SIZE 32 OP_EQUAL
# To local node via HTLC-timeout transaction (timelocked).
OP_DROP 2 OP_SWAP <local_htlcpubkey> 2 OP_CHECKMULTISIG
# To remote node with preimage.
OP_HASH160 <RIPEMD160(payment_hash)> OP_EQUALVERIFY