TeachMeBitcoin

OP_NIP - Removing Second Stack Item

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

14. OP_NIP — Removing Second Stack Item

Overview

OP_NIP removes the second-from-top item from the stack, leaving the top item in place. It is effectively a targeted discard — it reaches past the top item and removes the item directly beneath it.

Opcode Reference

Opcode:     OP_NIP
Hex:        0x77
Word:       NIP
Input:      x1 x2
Output:     x2
Stack Before: [ ..., x1, x2 ]   ← x2 is top
Stack After:  [ ..., x2 ]       ← x1 is removed

Execution Trace

Script: OP_5 OP_9 OP_NIP

Step 1: Stack: [ 5 ]

Step 2: Stack: [ 5, 9 ]

Step 3 — OP_NIP: Stack: [ 9 ]   ← 5 is removed, 9 remains on top

OP_NIP as a Compound Operation

OP_NIP is equivalent to:

OP_SWAP OP_DROP

Proof:
Start:        [ ..., x1, x2 ]
OP_SWAP:      [ ..., x2, x1 ]
OP_DROP:      [ ..., x2 ]

Using OP_NIP saves one byte compared to OP_SWAP OP_DROP.

Practical Use Case

OP_NIP is useful when an intermediate computation result is placed second on the stack by a prior operation and is no longer needed:

<input_a> <input_b>
OP_OVER    ← copies input_a to top
OP_ADD     ← adds input_a + input_a (or other computation using the copy)

Stack: [ input_a, input_b, result ]

OP_NIP     ← removes input_b (second from top)

Stack: [ input_a, result ]

Here input_b was needed for the computation but is no longer needed after it.

Failure Conditions

Summary

OP_NIP is a precise stack cleanup opcode. It removes the second item without disturbing the top item, serving as a single-byte equivalent of OP_SWAP OP_DROP.

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