OP_IFDUP - Conditional Duplication
12. OP_IFDUP — Conditional Duplication
Overview
OP_IFDUP is a unique conditional opcode that only duplicates the top stack item if it is not zero (i.e., if it is truthy). If the top item is zero or an empty byte array (falsy), OP_IFDUP does nothing — it leaves the stack unchanged.
Opcode Reference
Opcode: OP_IFDUP
Hex: 0x73
Word: IFDUP
Input: x
Output: x (if x == 0 or empty)
x x (if x != 0)
Stack Before: [ ..., x ]
Stack After: [ ..., x ] if x is falsy
[ ..., x, x ] if x is truthy
Execution Traces
Case 1 — Truthy Value:
Script: OP_5 OP_IFDUP
Stack before OP_IFDUP: [ 5 ]
Stack after OP_IFDUP: [ 5, 5 ] ← 5 duplicated (non-zero)
Case 2 — Falsy Value (zero):
Script: OP_0 OP_IFDUP
Stack before OP_IFDUP: [ 0 ]
Stack after OP_IFDUP: [ 0 ] ← no duplication (zero is falsy)
Understanding Truthy and Falsy in Bitcoin Script
In Bitcoin Script, the following values are considered falsy:
-
The empty byte array
[] -
The number
0 -
The byte sequence
0x80(negative zero) -
Any byte sequence of the form
0x00...00or0x00...80
Everything else is truthy.
Practical Use Case
OP_IFDUP was historically used in scripts where conditional branching needed to retain a reference copy of a value if it was valid:
<value>
OP_IFDUP
OP_IF
<process truthy>
OP_ELSE
<process falsy>
OP_ENDIF
When <value> is truthy, OP_IFDUP duplicates it so that OP_IF consumes one copy while leaving the other for further processing. When <value> is falsy, only one copy exists, and OP_IF takes the else branch without leaving a dangling stack item.
Historical P2SH Pattern
OP_IFDUP OP_IF
<pubkey>
OP_CHECKSIG
OP_ELSE
OP_2 <pubkey1> <pubkey2> <pubkey3> OP_3 OP_CHECKMULTISIG
OP_ENDIF
In this pattern, if the top value is nonzero (a direct-pay condition), it is duplicated and used. If zero, a multisig path is taken.
Failure Conditions
- If the stack is empty,
OP_IFDUPfails.
Summary
OP_IFDUP elegantly combines a conditional check with stack duplication. It reduces script size in branching patterns where a value may need to be preserved for one branch but not another.
TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation: