Reading — step 1 of 5
Read
Bitcoin Script
Bitcoin transactions don't just transfer coins — they execute a tiny stack-based script. Two scripts run back-to-back:
- scriptSig: provided by the spender (the input)
- scriptPubKey: stored on the previous output (the "lock")
If the combined execution leaves a truthy value on the stack, the spend is valid.
P2PKH (Pay to Public Key Hash) — the most common pattern
scriptPubKey: OP_DUP OP_HASH160 <pubkey_hash> OP_EQUALVERIFY OP_CHECKSIG
scriptSig: <signature> <pubkey>
Execution trace (combined: scriptSig then scriptPubKey):
stack
[]
push <sig> -> [sig]
push <pubkey> -> [sig, pubkey]
OP_DUP -> [sig, pubkey, pubkey]
OP_HASH160 -> [sig, pubkey, h160(pubkey)]
push <pubkey_hash> -> [sig, pubkey, h160(pubkey), pubkey_hash]
OP_EQUALVERIFY -> [sig, pubkey] (assert top two equal, pop both)
OP_CHECKSIG -> [1] (verify signature matches pubkey & tx)
Final stack: [1] → valid.
Other patterns
- P2PK:
<pubkey> OP_CHECKSIG(older, exposes pubkey on chain) - P2SH (BIP-16): hash a redeem script, the spender provides the preimage
- P2WPKH/P2WSH (BIP-141 SegWit): witness data segregated for malleability + fee discount
- P2TR (BIP-341 Taproot): Schnorr signatures, key-path or script-path spends
Script is intentionally not Turing-complete
No loops. Limited stack. This keeps validation bounded and predictable. Ethereum took the opposite design choice (EVM, full Turing) and pays the cost in gas metering complexity.
This exercise implements a mini script evaluator that handles P2PKH-style locks plus a few primitives (OP_DUP, OP_HASH160, OP_EQUAL, OP_EQUALVERIFY, OP_CHECKSIG, OP_ADD, OP_VERIFY).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…