How Script Works

Today we continue chapter 10 about Script, P2SH, and Miniscript.

How Script Works

Script is a stack-based language, so think of it like a stack of plates. You can put plates on it, and you can take the top plate off, but you can’t manipulate plates in the middle.

A stack works differently than regular memory where you can read and write to arbitrary addresses (such as a hard disk or RAM — random-access memory). A stack is easier to implement and reason about.

The most commonly used (before SegWit) Bitcoin Script reads as follows:

The value for pubKeyHash is generated by the recipient wallet by performing a double SHA-256 hash followed by RIPEMD-160, and the result is inserted into the above script. A Bitcoin address only contains the pubKeyHash; the rest is implied. It’s actually the sender’s wallet that generates the full script before publishing it on the blockchain.

On the blockchain this script ends up in the output of a transaction. The output of a transaction, i.e. a coin, consists of this script that it’s locked with (scriptPubKey) and the amount. Now, if you want to spend that, you create a transaction input that instructs the blockchain to add certain things to the stack before the above script is executed.

The Bitcoin interpreter will see what you put on the stack, and it’ll start running the program from the output. In this case, what you put on the stack is your signature and your public key, because the original script didn’t have your public key; it had the hash of your public key.

Continuing with the example from above, we start with a stack that has two plates. The plate at the bottom is your signature, and on top of that is a plate with your public key, and then the script says OP_DUP. It pops the stack, i.e. it takes the top element from the stack — the top plate, which is the public key — and duplicates it. The original and duplicate are then pushed onto the stack. So now you have two plates with a public key at the top of the stack, and your signature’s still at the bottom.

The next instruction is OP_HASH160. This pops one of those two duplicated public keys off the stack and hashes it, and then pushes that hash on the stack.

The signature is still at the bottom, and then there’s a public key, and then there’s the hash of the public key (three plates).

The next operation is pubKeyHash, which pushes the hash of your public key on the stack. So now, the hash of your public key occurs twice at the top of the stack.

The operation OP_EQUAL_VERIFY pops both these hashes of the stack and checks to see if they’re the same.

What’s left on the stack is your signature and your public key, so OP_CHECKSIG checks the signature using your public key, and then the stack is empty.

In a nutshell, that’s how a Script program is run, and you can do arbitrarily complicated things along the way.