OP_ROLL - Moving Nth Item to Top
17. OP_ROLL — Moving Nth Item to Top
Overview
OP_ROLL is the destructive counterpart of OP_PICK. Like OP_PICK, it reads an integer n from the top of the stack and accesses the item n positions deep. However, instead of copying that item, OP_ROLL removes it from its current position and moves it to the top. The rest of the stack closes the gap.
Opcode Reference
Opcode: OP_ROLL
Hex: 0x7a
Word: ROLL
Input: xn ... x1 x0 n
Output: xn-1 ... x1 x0 xn
Stack Before: [ ..., xn, xn-1, ..., x1, x0, n ]
Stack After: [ ..., xn-1, ..., x1, x0, xn ]
The item at depth n is removed from its position and placed on top.
Execution Traces
OP_ROLL with n=0 (no change — top item moved to top):
Stack: [ A, B, C, 0 ]
OP_ROLL → Stack: [ A, B, C ] ← C removed from position 0, placed at top (same)
OP_ROLL with n=1 (equivalent to OP_SWAP):
Stack: [ A, B, C, 1 ]
OP_ROLL → Stack: [ A, C, B ] ← B extracted from position 1, moved to top
OP_ROLL with n=2 (equivalent to OP_ROT):
Stack: [ A, B, C, 2 ]
OP_ROLL → Stack: [ B, C, A ] ← A extracted from position 2, moved to top
Stack Size After OP_ROLL
Unlike OP_PICK, OP_ROLL does not increase the stack size:
OP_PICK: Stack before = N items → Stack after = N items (n consumed, copy added)
OP_ROLL: Stack before = N items → Stack after = N-1 items (n consumed, item moved, no copy)
Wait — correction:
Stack before OP_ROLL: N+1 items (N items + n on top)
Stack after OP_ROLL: N items (n consumed, item moved to top — no net change in N)
Both OP_PICK and OP_ROLL produce a net stack size of N after removing n, but OP_ROLL achieves this by physically relocating the item rather than copying it.
Practical Use Case: Bringing a Buried Value Forward
Stack: [ sig_A, sig_B, sig_C, pubkey ]
← pubkey buried at depth 3
Push depth: OP_3
OP_ROLL
Stack: [ sig_A, sig_B, sig_C, pubkey ]
Hmm, let's re-index...
Start: [ sig_A, sig_B, sig_C, pubkey, 3 ]
OP_ROLL: [ sig_B, sig_C, pubkey, sig_A ]
↑ sig_A moved from depth 3 to top
Failure Conditions
-
nmust be non-negative. -
nmust be within the current stack depth. -
Out-of-range
ncauses script failure.
Summary
OP_ROLL physically extracts an item from deep within the stack and brings it to the top, reducing the need to rearrange intermediate items manually. It is the destructive version of OP_PICK.
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: