OP_DUP - Duplicating the Top Item
3. OP_DUP — Duplicating the Top Item
Overview
OP_DUP is arguably the most widely used opcode in all of Bitcoin Script. It duplicates the topmost item on the stack, placing a copy of it on top. The original item remains in place. OP_DUP forms the cornerstone of the Pay-to-Public-Key-Hash (P2PKH) script type, which is the most common Bitcoin transaction output format used historically.
Opcode Reference
Opcode: OP_DUP
Hex: 0x76
Word: DUP
Input: x
Output: x x
Stack Before: [ ..., x ]
Stack After: [ ..., x, x ]
How It Works
OP_DUP peeks at the top of the stack, creates a duplicate of the top item, and pushes that duplicate onto the stack. The original item is not consumed. After OP_DUP, there are two identical copies of the top item on the stack.
Execution Trace
Script: OP_5 OP_DUP
Step 1 — OP_5: Stack: [ 5 ]
Step 2 — OP_DUP: Stack: [ 5, 5 ] ← a copy of 5 is pushed
The P2PKH Pattern
The canonical use of OP_DUP is in the P2PKH locking script:
Locking Script (scriptPubKey):
OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
Unlocking Script (scriptSig):
<signature> <pubKey>
Combined script execution:
Step 1: Push
Stack: [
Step 2: Push
Stack: [
Step 3: OP_DUP
Stack: [
Step 4: OP_HASH160
Stack: [
Step 5: Push (from locking script)
Stack: [
Step 6: OP_EQUALVERIFY
Stack: [
Step 7: OP_CHECKSIG
Stack: [ TRUE ] ← signature verified against pubKey
This pattern ensures:
-
The spender provides a public key that hashes to the expected value.
-
The same public key is used to verify the signature.
OP_DUPmakes both checks possible from a single provided public key.
Why OP_DUP is Critical
Without OP_DUP, the P2PKH pattern would require the spender to push the public key twice, increasing transaction size and wasting block space. OP_DUP enables a single-push public key to serve double duty in the script.
Deep Copy vs Shallow Copy
In Bitcoin Script, all stack items are byte arrays. When OP_DUP creates a copy, it creates a byte-for-byte copy of the data. There is no concept of reference types or shared memory in Script — every duplication is a full copy.
Failure Conditions
- If the stack is empty,
OP_DUPcauses the script to fail.
Summary
OP_DUP is the foundation of P2PKH and many other Bitcoin script patterns. Its ability to duplicate the top stack item enables elegant single-pass verification patterns that would otherwise require redundant data in transaction inputs.
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: