OP_SWAP - Swapping Top Two Items
6. OP_SWAP — Swapping Top Two Items
Overview
OP_SWAP exchanges the positions of the top two items on the stack. After execution, what was the top item is now second, and what was second is now on top. The rest of the stack is unchanged. This opcode is used extensively in scripts to reorder operands for subsequent operations.
Opcode Reference
Opcode: OP_SWAP
Hex: 0x7c
Word: SWAP
Input: x1 x2
Output: x2 x1
Stack Before: [ ..., x1, x2 ] ← x2 is top
Stack After: [ ..., x2, x1 ] ← x1 is now top
Execution Trace
Script: OP_3 OP_9 OP_SWAP
Step 1: Stack: [ 3 ]
Step 2: Stack: [ 3, 9 ]
Step 3 — OP_SWAP: Stack: [ 9, 3 ]
Why Operand Order Matters
Many Bitcoin opcodes are order-sensitive. OP_CHECKSIG expects <sig> below <pubkey>. OP_EQUAL doesn't care about order, but OP_SUB does. OP_SWAP enables scripts to reorder stack items to match expected operand conventions without introducing redundant push operations.
Example: ensuring correct operand order for OP_SUB
Script: OP_5 OP_3 OP_SWAP OP_SUB
Stack after OP_5 OP_3: [ 5, 3 ]
After OP_SWAP: [ 3, 5 ]
After OP_SUB: [ 3 - 5 = -2 ] ← top subtracted from below
Without OP_SWAP:
Stack: [ 5, 3 ]
OP_SUB: [ 5 - 3 = 2 ]
OP_SWAP changes subtraction order.
Common Pattern: OP_SWAP with OP_CHECKSIG
Unlocking: <pubkey> <sig>
Locking: OP_SWAP OP_CHECKSIG
After combining:
Stack: [
OP_SWAP → Stack: [ <sig>, <pubkey> ]
OP_CHECKSIG → TRUE
Failure Conditions
- Requires at least 2 items on the stack.
Summary
OP_SWAP is a versatile operand reordering opcode. It enables script authors to write compact, correctly ordered instruction sequences without redundant push operations.
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: