OP_ROT - Rotating Top Three Items
10. OP_ROT — Rotating Top Three Items
Overview
OP_ROT rotates the top three items on the stack. The third item from the top is moved to the top, while the top two items are shifted down by one position each. This is a left rotation of the top three items.
Opcode Reference
Opcode: OP_ROT
Hex: 0x7b
Word: ROT
Input: x1 x2 x3
Output: x2 x3 x1
Stack Before: [ ..., x1, x2, x3 ] ← x3 is top
Stack After: [ ..., x2, x3, x1 ] ← x1 brought to top
Execution Trace
Script: OP_1 OP_2 OP_3 OP_ROT
After pushes: Stack: [ 1, 2, 3 ]
After OP_ROT: Stack: [ 2, 3, 1 ]
Item 1 — which was third from top — is rotated to the top. Items 3 and 2 drop one position.
The Rotation Pattern
It helps to visualize OP_ROT as a cyclic left-shift of three positions:
Before: [ ..., x1, x2, x3 ]
↑ bottom of triplet
After: [ ..., x2, x3, x1 ]
↑ x1 moved to top
Performing OP_ROT three times returns the stack to its original state:
[ 1, 2, 3 ] → OP_ROT → [ 2, 3, 1 ]
OP_ROT → [ 3, 1, 2 ]
OP_ROT → [ 1, 2, 3 ] ← original restored
Use Case: Reordering Three Operands
OP_ROT is used when a value buried two levels deep is needed for the next operation:
<hash_expected> <pubkey> <sig>
OP_ROT
→ Stack: [ <pubkey>, <sig>, <hash_expected> ]
Now <hash_expected> is on top for a hash comparison, while <pubkey> and <sig> are correctly positioned below it for a subsequent OP_CHECKSIG.
Failure Conditions
- Requires at least 3 items on the stack.
Summary
OP_ROT is a powerful reordering opcode that brings the third-from-top item to the top, enabling three-way value manipulation in a single opcode step.
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: