OP_2SWAP - Swapping Top Two Pairs
7. OP_2SWAP — Swapping Top Two Pairs
Overview
OP_2SWAP swaps the top two pairs of stack items. Where OP_SWAP swaps two individual items, OP_2SWAP treats the top four items as two pairs and exchanges the pairs, preserving the internal order of each pair.
Opcode Reference
Opcode: OP_2SWAP
Hex: 0x72
Word: 2SWAP
Input: x1 x2 x3 x4
Output: x3 x4 x1 x2
Stack Before: [ ..., x1, x2, x3, x4 ] ← x4 is top
Stack After: [ ..., x3, x4, x1, x2 ] ← pairs swapped
Execution Trace
Script: OP_1 OP_2 OP_3 OP_4 OP_2SWAP
Step 1-4: Stack: [ 1, 2, 3, 4 ]
Step 5 — OP_2SWAP: Stack: [ 3, 4, 1, 2 ]
The pair (1, 2) and the pair (3, 4) have been swapped in position.
Practical Use Case
OP_2SWAP is useful in scripts that prepare two paired operands for a combined operation:
<sig_A> <pubkey_A> <sig_B> <pubkey_B>
OP_2SWAP
→ Stack: [ <sig_B>, <pubkey_B>, <sig_A>, <pubkey_A> ]
This reorders two signer pairs so they are processed in reverse order.
Difference Between OP_SWAP and OP_2SWAP
OP_SWAP: swaps 2 individual items → requires ≥ 2 stack items
OP_2SWAP: swaps 2 pairs of items → requires ≥ 4 stack items
Failure Conditions
- Requires at least 4 items on the stack.
Summary
OP_2SWAP handles pair-level reordering. It is the natural extension of OP_SWAP for scripts that work with paired data structures such as (signature, pubkey) tuples in multisig scenarios.
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: