TeachMeBitcoin

OP_SWAP - Swapping Top Two Items

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

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

Summary

OP_SWAP is a versatile operand reordering opcode. It enables script authors to write compact, correctly ordered instruction sequences without redundant push operations.

☕ 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!