TeachMeBitcoin

OP_PICK - Copying Nth Item to Top

From TeachMeBitcoin, the free encyclopedia Reading time: 3 min

16. OP_PICK — Copying Nth Item to Top

Overview

OP_PICK is a generalized copy opcode. It reads an integer n from the top of the stack, then copies the item that is n positions from the top (after removing n itself) to the top of the stack. All other items remain unchanged.

Opcode Reference

Opcode:     OP_PICK
Hex:        0x79
Word:       PICK
Input:      xn ... x2 x1 x0 n
Output:     xn ... x2 x1 x0 xn
Stack Before: [ ..., xn, ..., x1, x0, n ]
Stack After:  [ ..., xn, ..., x1, x0, xn ]

Where n = 0 means the top item (before n is consumed), n = 1 means the second item, and so on.

Execution Traces

OP_PICK with n=0 (equivalent to OP_DUP):

Stack: [ A, B, C, 0 ]

OP_PICK → Stack: [ A, B, C, C ]   ← copied item 0 positions deep (C)

OP_PICK with n=1 (equivalent to OP_OVER):

Stack: [ A, B, C, 1 ]

OP_PICK → Stack: [ A, B, C, B ]   ← copied item 1 position deep (B)

OP_PICK with n=2:

Stack: [ A, B, C, 2 ]

OP_PICK → Stack: [ A, B, C, A ]   ← copied item 2 positions deep (A)

Dynamic Addressing

The key power of OP_PICK is that n is not hardcoded into the opcode — it is taken from the stack. This means the depth to pick from can be computed dynamically by the script:

Script: OP_1 OP_2 OP_3 OP_4 OP_5   ← push 5 values
        OP_3                         ← push pick depth = 3
        OP_PICK

Execution:

Stack before OP_PICK: [ 1, 2, 3, 4, 5, 3 ]
OP_PICK consumes 3, looks 3 positions deep into [ 1, 2, 3, 4, 5 ]
Position 0 = 5, Position 1 = 4, Position 2 = 3, Position 3 = 2
Stack after: [ 1, 2, 3, 4, 5, 2 ]

Failure Conditions

Security Warning: PICK with Dynamic n

If n is derived from user-supplied data, a malicious user could provide an n that reaches into sensitive stack positions. Script authors should validate n before using OP_PICK:

OP_DUP OP_0 OP_GREATERTHANOREQUAL OP_VERIFY   ← n >= 0
OP_DUP <MAX_DEPTH> OP_LESSTHAN OP_VERIFY      ← n < max
OP_PICK

Summary

OP_PICK is the general-purpose non-destructive copy opcode. Unlike OP_DUP, OP_OVER, and similar opcodes which operate at fixed depths, OP_PICK can copy from any position, making it the most flexible read opcode in Bitcoin Script.

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