TeachMeBitcoin

The Stack Execution Model

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

The Stack Execution Model

Bitcoin uses a Stack-based virtual machine to validate transactions. To verify an input, the node combines the ScriptSig and the ScriptPubKey in a specific order.

1. The Script Concatenation

In the earliest versions of Bitcoin, the node literally concatenated the two scripts: [ScriptSig] + [ScriptPubKey] Then, it executed the entire string of bytes from left to right.

2. Modern Execution (The Clean Stack)

To improve security, modern nodes execute them separately but on the same stack.

  1. Phase 1: Execute ScriptSig. This pushes data (Signature and PubKey) onto the stack.

  2. Phase 2: Execute ScriptPubKey. This uses the data already on the stack to perform logic (Hashing and Verification).

3. Step-by-Step Execution (P2PKH)

  1. ScriptSig pushes <Sig> onto the stack.

  2. ScriptSig pushes <PubKey> onto the stack.

  3. ScriptPubKey runs OP_DUP (Duplicates the PubKey).

  4. ScriptPubKey runs OP_HASH160 (Hashes the duplicate PubKey).

  5. ScriptPubKey pushes the <ExpectedHash> onto the stack.

  6. ScriptPubKey runs OP_EQUALVERIFY (Compares the calculated hash with the expected one).

  7. ScriptPubKey runs OP_CHECKSIG (Verifies the signature against the original PubKey).

4. The Final Result

For a transaction to be valid, the execution must end with a single value on the stack, and that value must be non-zero (usually the number 1). If the stack is empty or the top value is zero, the transaction is rejected.

Stage Stack State
Start []
After ScriptSig [<Sig>, <PubKey>]
After Hash Logic [<Sig>, <PubKey>, <CalculatedHash>, <ExpectedHash>]
Final Result [1] (Valid)

In the next section, we will discuss the major shift introduced by SegWit.

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