TeachMeBitcoin

OP_IFDUP - Conditional Duplication

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

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:

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

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.

☕ Help support TeachMeBitcoin

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:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!