The Stack Execution Model
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.
-
Phase 1: Execute
ScriptSig. This pushes data (Signature and PubKey) onto the stack. -
Phase 2: Execute
ScriptPubKey. This uses the data already on the stack to perform logic (Hashing and Verification).
3. Step-by-Step Execution (P2PKH)
-
ScriptSig pushes
<Sig>onto the stack. -
ScriptSig pushes
<PubKey>onto the stack. -
ScriptPubKey runs
OP_DUP(Duplicates the PubKey). -
ScriptPubKey runs
OP_HASH160(Hashes the duplicate PubKey). -
ScriptPubKey pushes the
<ExpectedHash>onto the stack. -
ScriptPubKey runs
OP_EQUALVERIFY(Compares the calculated hash with the expected one). -
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.
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: