Locking Scripts

Bitcoin

Up until now I’ve been treating a locking script as “whoever has the associated private key can spend these bitcoins”. In the example transaction, that’s precisely what the locking script checks, but that doesn’t always have to be the case. You might recall that locking scripts are actually just tiny programs, and they can ask for a lot more than just one signature.

In this post I’m going to go through how these programs run, and then through the different kinds of locking script that Bitcoin has added over the years. I can’t go through every single one, since there are just too many for one post, but I will cover the important ones and the ones that matter for when we get to the quantum threat.

You might be wondering why I’m going this deep into locking scripts, when this part of the blog is only meant to cover enough of Bitcoin to understand the quantum threat. I can’t fully explain why yet, but the different kinds of locking script expose your public key in different ways, which affects where the quantum threat shows up and how bad it is.

#How Script runs

Locking scripts are written in Script, the small programming language I mentioned when introducing UTXOs. A script is a list of instructions called opcodes, with each opcode being a single byte. People usually write these opcodes with names like OP_ADD so they’re readable to other humans, but in the actual transaction OP_ADD is just the byte 93. Data like a public key goes into a script too, right after an opcode that says how many bytes of data come next.

Script runs its opcodes in order, from first to last, and it has no way to jump back to an earlier opcode and run it again. That’s on purpose, because every node has to run the script of every input it checks. If someone could write a script that loops forever, every node that tried to check it would get stuck. Since Script can’t go backwards, each opcode runs at most once, and a script can never take more steps than it has opcodes.

Script is also stack-based. A stack is a list where you can only add an item to the top (pushing it) or take the top item off (popping it). Every opcode works on the same stack, and each one either pushes data onto the stack or pops items off the top, does something with them, and usually pushes a result back on. Script has no way to store a value under a name, so an opcode never has to be told where to find the items it works on. They’re always whatever is on top of the stack.

Script also limits how much the stack can hold. A single item can be at most 520 bytes, and the stack can never have more than 1,000 items on it [1]. Everything in this post fits easily, since an ECDSA signature is about 72 bytes and a compressed public key is 33.

Script is often described as Forth-like. Forth is an older programming language that also works on a stack, and a lot of Script’s opcodes for shuffling the stack around have the same names as Forth’s, like OP_DUP and OP_SWAP (DUP and SWAP in Forth). As far as I know, Satoshi never said whether that was on purpose.

A node checks an input in two steps, using the same stack for both. First it runs the input’s unlocking script (scriptSig), starting from an empty stack. The scriptSig is a script too, and usually all it does is push whatever the locking script asks for, like a signature. Then the node runs the locking script of the UTXO being spent, which starts with whatever the scriptSig left on the stack. The input is valid if no opcode failed along the way and, at the end, the stack isn’t empty and the item on top isn’t zero [2]. (The example transaction’s scriptSig was empty, since its unlocking data was in the witness. Newer kinds of locking script, like the one in the example, run a bit differently, and I’ll get to them later in this post.)

To understand this a bit better, let’s look at a small example. Say a UTXO has the locking script OP_3 OP_ADD OP_5 OP_EQUAL. The opcodes OP_0 to OP_16 just push the numbers 0 to 16, so OP_3 pushes 3 and OP_5 pushes 5. OP_ADD pops the top two items and pushes their sum, and OP_EQUAL pops the top two items and pushes 1 if they’re the same and 0 if they aren’t. So this locking script basically says “whatever you give me, plus 3, has to equal 5”. To unlock it, you’d make your input’s scriptSig the single opcode OP_2, which pushes 2.

Figure 1: Running the scriptSig (just OP_2) and then the locking script OP_3 OP_ADD OP_5 OP_EQUAL, one opcode at a time from left to right. The labels at the top say which script each opcode is from, and the dashed line separates the two. Under each opcode is the stack after that opcode runs, with the bottom of the stack on the horizontal line and the top item highest. The shaded box in each stack is the item that opcode just pushed. The locking script starts from the 2 that the scriptSig left on the stack.

The top item at the end is 1, which isn’t zero, so the input is valid.

Of course, this is a terrible way to lock up bitcoin, since anyone can work out that the answer is 2. Even if the answer were hard to work out, it would still be sitting in your scriptSig for anyone to read. Once you broadcast your transaction, it’s in mempools all over the network, and someone could copy your scriptSig into their own transaction that spends the same UTXO to themselves. If they give it a higher fee, nodes will replace yours with theirs. A signature doesn’t have this problem, since the message it signs is built from your transaction and covers every output. If someone copies your signature into a transaction that pays themselves, the message changes and the signature no longer verifies. That’s why every locking script in the rest of this post ends up checking at least one signature.

#Pay to public key (P2PK)

The first kind of locking script is the simplest one you could make out of a signature check. It’s

<pubkey> OP_CHECKSIG

where <pubkey> is shorthand for pushing a public key onto the stack. OP_CHECKSIG pops a public key and a signature off the stack, runs ECDSA’s Vrfy\texttt{Vrfy} with them on this input’s mm, and pushes 1 if the signature is valid or 0 if it isn’t. So the only thing the scriptSig needs to push is the signature, which I’ll write as <sig>. This is called pay to public key (P2PK), and it’s what Bitcoin used from its inception [2].

As an example, consider one of the very first transactions ever made. On January 12, 2009, Satoshi Nakamoto sent 10 bitcoin to Hal Finney, a cryptographer who was one of the first people other than Satoshi to run Bitcoin’s software. Hal later wrote that he was “the recipient of the first bitcoin transaction, when Satoshi sent ten coins to me as a test” [3]. The transaction’s txid is

f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16

and you can look it up on mempool.space. It spends one UTXO worth 50 bitcoin (which is an insane amount at today’s prices) and has two outputs: 10 bitcoin to Hal, and 40 bitcoin back to Satoshi as change. Both outputs have P2PK locking scripts. Hal’s has his public key 04ae1a62…7e6cd84c in it, in the uncompressed format, which is all Bitcoin’s software used back then. The change output looks exactly the same, with Satoshi’s public key 0411db93…b412a3 in it instead.

The 50-bitcoin UTXO being spent was also locked to Satoshi’s public key, so the input’s scriptSig is just Satoshi’s signature. When a node checks the input, the scriptSig pushes <sig>, the locking script pushes Satoshi’s public key on top of it, and OP_CHECKSIG pops both and pushes 1, since the signature does verify.

So where’s the public key? This is what I’ll keep track of for every kind of locking script in this post. For P2PK, the public key is right there in the locking script from the moment the UTXO is created, just like Hal’s, so anyone reading the record can see it before the UTXO is ever spent. There’s also no address for P2PK. If you want someone to pay you this way, you have to hand them your whole public key (65 bytes back then) instead of a short address, with no checksum to catch typos.

#Pay to public key hash (P2PKH)

Bitcoin had a second kind of locking script from the start, which deals with both of those problems: the public key sitting in the locking script, and having no address [2]. Instead of a public key, this locking script holds the HASH160⁡\operatorname{HASH160} of one. It’s

OP_DUP OP_HASH160 <20-byte hash> OP_EQUALVERIFY OP_CHECKSIG

and it’s called pay to public key hash (P2PKH). A node can’t check a signature against a hash, so to spend a P2PKH UTXO, the scriptSig has to push the public key as well as the signature, which makes it <sig> <pubkey>. The locking script then checks that the public key matches the hash before it checks the signature.

There are three new opcodes in there. OP_DUP pushes a copy of the top item, and OP_HASH160 pops the top item and pushes its HASH160⁡\operatorname{HASH160}. OP_EQUALVERIFY pops the top two items like OP_EQUAL does, but instead of pushing 1 or 0, it makes the whole script fail right there if they’re different. If they’re the same, the script keeps going without pushing anything.

In the figure I drew the stack from the bottom up, but from here on I’ll write it sideways, with the bottom item on the left and the top item on the right. Here’s the stack after each step when someone spends a P2PKH UTXO.

StepOpcodeStack after
1<sig> (from scriptSig)<sig>
2<pubkey> (from scriptSig)<sig> <pubkey>
3OP_DUP<sig> <pubkey> <pubkey>
4OP_HASH160<sig> <pubkey> <hash of pubkey>
5<20-byte hash><sig> <pubkey> <hash of pubkey> <20-byte hash>
6OP_EQUALVERIFY<sig> <pubkey>
7OP_CHECKSIG1

Step 3 copies the public key, and step 4 hashes the copy. Step 5 pushes the hash from the locking script, and step 6 checks that the two hashes are equal, pops them both, and carries on. If someone had put in a different public key, the hashes wouldn’t match, and the script would fail at step 6 without ever checking the signature. After step 6, the original public key is back on top of the signature, so step 7 is the same signature check as P2PK.

This is the kind of locking script the address I built is for. That address was the HASH160⁡\operatorname{HASH160} of a public key with the version byte 00 in front and a checksum on the end, which is why it started with a 1. When someone pays an address like that, their wallet takes out the 20-byte hash, and the 00 tells it to put the hash into a P2PKH locking script. So to get paid, you only need to hand out your address.

With P2PKH, only the hash of the public key is in the locking script while the UTXO is unspent. The public key itself comes out in the scriptSig when the UTXO is spent, since the node needs it to check the signature.

#Pay to script hash (P2SH)

P2PK and P2PKH both lock a UTXO to a single key, but Script can do more than that. One of the first things people wanted was multisig, where spending needs signatures from some number of keys out of a set. For example, you could keep three keys on three different devices and require any two of them, so losing one device, or having one stolen, doesn’t cost you your coins. A 2-of-3 multisig script looks like

OP_2 <pubkey1> <pubkey2> <pubkey3> OP_3 OP_CHECKMULTISIG

OP_CHECKMULTISIG reads the 3 and the 2 to know how many keys and signatures to expect, then checks that each of the 2 signatures verifies under a different one of the 3 keys, and pushes 1 if they all do. To spend it, the scriptSig pushes two signatures, plus one extra item at the front.

The extra item is there because of a bug in Satoshi’s original code that makes OP_CHECKMULTISIG pop one more item off the stack than it should. Fixing it would change which transactions count as valid, so every node would have to switch at once, the same problem as raising the size limit. Instead, every multisig scriptSig just starts with an OP_0 for OP_CHECKMULTISIG to throw away [2].

You can use that script as a locking script directly. This is called bare multisig, and just like P2PK, it puts every public key in the output from the moment the UTXO is created. It also has no address, so you’d have to send the person paying you the whole script, and they’d pay the fee for all of its bytes.

In 2012, pay to script hash (P2SH) fixed the missing address the same way P2PKH did for P2PK, by having the person paying lock to a hash of the script instead of the script itself [4]. The locking script is

OP_HASH160 <20-byte hash> OP_EQUAL

and the script that got hashed is called the redeem script. Whoever spends the UTXO pushes the redeem script as the last item of the scriptSig, after the signatures. Since the whole redeem script gets pushed as one item, it can be at most 520 bytes. If you run the scriptSig and then the locking script the normal way, you might notice a problem. All that does is check that the redeem script hashes to the right value, and nothing has checked a signature yet. So P2SH adds one more rule: whenever a locking script has exactly this form and passes, the node takes the last item the scriptSig pushed, reads it as a script, and runs it on whatever else the scriptSig left on the stack. The input is only valid if that passes too [4].

P2SH addresses use the same Base58Check encoding as P2PKH ones, but with the version byte 05 instead of 00, which makes them start with a 3. Since a P2SH address is just a hash, the person paying you can’t tell whether it’s multisig or something else entirely.

That also means none of the public keys in a P2SH redeem script are visible until the UTXO is spent. At that point the whole redeem script is out in the open, with every public key in it, including the one whose holder didn’t sign.

#SegWit’s locking scripts

When SegWit moved unlocking data out of scriptSig and into the witness in 2017, it added two new kinds of locking script, one copying P2PKH and one copying P2SH [5].

The first is pay to witness public key hash (P2WPKH), which is

OP_0 <20-byte hash>

and its witness is <sig> <pubkey>. P2WPKH is what the example transaction’s UTXO was actually locked with. On its own, OP_0 <20-byte hash> doesn’t check anything. Instead, when a node sees a locking script that’s OP_0 followed by exactly 20 bytes, it puts the witness items on the stack and runs

OP_DUP OP_HASH160 <those 20 bytes> OP_EQUALVERIFY OP_CHECKSIG

which is the P2PKH script from before [5]. That’s why, when I went through getting your transaction recorded, the check for the example was that the public key hashes to the HASH160⁡\operatorname{HASH160} in the locking script and the signature verifies under it.

The second is pay to witness script hash (P2WSH), which is

OP_0 <32-byte hash>

and it works like P2SH. The last item in the witness is the script itself, the 32 bytes are its SHA-256⁡\operatorname{SHA-256}, and the node checks the hash and then runs the script on the rest of the witness [5]. You might be wondering why this hash is 32 bytes when P2SH’s is 20. A script is often put together by several people, and a dishonest one can try lots of versions of the shared script (each with a different public key of their own in it) against lots of scripts that only they can spend, looking for one of each with the same hash. If they find a pair, coins paid to the shared script can be spent with theirs. Since they get to pick both sides, that’s a collision search, which by the birthday bound takes about 2802^{80} tries for a 160-bit hash, compared with about 21282^{128} for a 256-bit one [5].

The OP_0 at the front of both scripts tells a node to check them with SegWit’s rules, and the number of bytes after it (20 or 32) tells it which of the two it is. Taproot, in the next section, uses OP_1 instead, and OP_2 to OP_16 are kept free for kinds of locking script that haven’t been made yet [5].

Both of SegWit’s types use Bech32 addresses. Like the version byte in a Base58Check address, a Bech32 address carries a number saying which kind of locking script it’s for, here the 0 from the OP_0. Bech32 has its own set of digits, the same way base 58 does, and q is its digit for 0, so these addresses start with bc1q. Taproot addresses use the Bech32m variant and start with bc1p, since p is the digit for 1.

The public keys work out the same as in the types SegWit copied. A P2WPKH UTXO hides its public key behind a hash until it’s spent, and then the public key is in the witness. A P2WSH UTXO shows nothing until it’s spent, and then the whole script comes out, with every public key in it.

#Taproot

Every kind of locking script so far has the same problem with more complicated scripts. When you spend from P2SH or P2WSH, you reveal the whole script, including every condition you didn’t use. Taproot, added in 2021, fixes this [6]. A single Taproot UTXO can be spent either with one signature, or with any one of a list of scripts, and spending with a script only reveals that one script.

The locking script is

OP_1 <32-byte key>

where the 32 bytes are a public key called the output key, QQ. They’re only the xx-coordinate of QQ, without the 02 or 03 byte from the compressed format, since Taproot always takes yy to be the even one [7].

#The key path

The simple way to spend a Taproot UTXO is the key path, where the witness is just one signature that has to verify under QQ [6]. Taproot signatures are Schnorr signatures, not ECDSA. Remember that Schnorr signatures are linear, so with a special protocol several people can produce one signature together that looks like a single person’s. The same linearity lets them add their public keys up into one key that the signature verifies under, so anyone reading the record just sees one public key and one signature, the same as for a single person.

#Hiding the scripts inside the output key

So where do the scripts go? Say you have a public key P=dGP = dG, called the internal key, and a list of scripts. First you put the scripts into a Merkle tree, one script per leaf, and get its root hrooth_\text{root}. Then you shift PP by a number that depends on both PP and the root,

Q=P+tG,where t=hash⁡(P∥hroot),Q = P + tG, \quad \text{where } t = \operatorname{hash}(P \| h_\text{root}),(1)

read as a number [6]. The hash here is SHA-256⁡\operatorname{SHA-256} with a tag mixed in, which is the same idea as the 8-bit tags for telling items apart from hashes higher up, so this hash can’t be mixed up with any other hash Taproot makes [7].

Since P=dGP = dG,

Q=dG+tG=(d+t)G,Q = dG + tG = (d + t)G,(2)

so whoever knows dd also knows the private key for QQ, which is d+t mod nd + t \bmod n. That’s how the owner of PP can still spend with the key path.

Someone with a different set of scripts can’t claim their scripts are inside QQ. Different scripts give a different hrooth_\text{root}, so a different tt, so a different point. To land exactly on QQ, they’d need some PP and tree with P+tG=QP + tG = Q, but tt is a hash of PP itself, so every guess at PP changes tt unpredictably. They’re stuck guessing, which takes about as many tries as finding a preimage.

#The script path

The other way to spend is the script path, where the witness has the items one of the scripts needs (like signatures), the script itself, the internal key PP, and a Merkle proof that the script is in the tree [6]. A node hashes the script into a leaf, follows the Merkle proof up to hrooth_\text{root}, works out tt from PP and hrooth_\text{root}, and checks that P+tGP + tG is QQ. If it is, the script really was committed to when QQ was made, and the node runs it on those items. Inside these scripts, OP_CHECKSIG checks a Schnorr signature instead of an ECDSA one [1].

Figure 2: How a Taproot output key QQ is built from the internal key PP and four scripts, s1s_1 to s4s_4, marked up for spending with the script path using s3s_3. Each line joins a box to a box computed from it: the scripts are hashed into the leaves h1h_1 to h4h_4 of a Merkle tree with root hrooth_\text{root}, tt is the hash of PP and hrooth_\text{root}, and Q=P+tGQ = P + tG. The shaded boxes are s3s_3 and everything the node computes from it, joined by thick lines, ending with QQ, which it checks against the locking script. The dashed boxes, PP, h12h_{12}, and h4h_4, are given in the witness. The node never sees the faded boxes.

Only the script you used gets revealed, since the rest of the tree only shows up as the sibling hashes in the proof, and those say nothing about what’s in the other scripts.

Every Taproot UTXO has a key path, though. Even if you only ever meant to spend with a script, the locking script is still the public key QQ, and a valid signature under QQ will always spend it.

For the public key, Taproot ends up like P2PK, since QQ is a public key sitting in the locking script from the moment the UTXO is created. Spending with the script path also reveals PP, plus any public keys in the script that got used.

#Where the public key is

Here’s every kind of locking script from this post in one place.

TypeLocking scriptPublic key becomes public
P2PK<pubkey> OP_CHECKSIGwhen the UTXO is created
Bare multisigOP_2 <pubkey1> <pubkey2> <pubkey3> OP_3 OP_CHECKMULTISIG (for 2-of-3)when the UTXO is created, all of them
P2PKHOP_DUP OP_HASH160 <20-byte hash> OP_EQUALVERIFY OP_CHECKSIGwhen the UTXO is spent
P2SHOP_HASH160 <20-byte hash> OP_EQUALwhen the UTXO is spent, every key in the redeem script
P2WPKHOP_0 <20-byte hash>when the UTXO is spent
P2WSHOP_0 <32-byte hash>when the UTXO is spent, every key in the script
P2TR (Taproot)OP_1 <32-byte key>when the UTXO is created (QQ), plus PP and the used script’s keys when spent with the script path

So the types split into two groups. P2PK, bare multisig, and Taproot put a public key in the locking script, so it’s public from the moment the UTXO exists. For Taproot there’s no way around this, since the key path needs a node to check a signature against QQ. Every other type only has a hash in the locking script, and the public key comes out when the UTXO is spent. “When it’s spent” really means when the transaction is broadcast, since that’s when it starts sitting in mempools all over the network, before it’s ever recorded.

There are a couple of catches with the second group. First, “hidden until spent” only holds if the key is used once. Like I showed in spending puts your public key out in the open, once you’ve spent from an address, every UTXO still locked to it is locked to a public key anyone can read. Second, P2SH and P2WSH reveal the whole script when you spend, so a 2-of-3 multisig reveals all three public keys even though only two people signed.

So, back to why I went this deep into locking scripts. Which kind of locking script your bitcoin sits behind decides whether anyone can see your public key right now, or only once you spend it, and that matters a lot once we get to the quantum threat.

[1]
Wuille P, Nick J, Towns A. Validation of Taproot Scripts [Internet]. Bitcoin Improvement Proposal 342; 2020. Available from: https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki
[2]
Antonopoulos AM. Mastering Bitcoin: Programming the Open Blockchain. 2nd ed. O’Reilly Media; 2017.
[3]
Finney H. Bitcoin and Me (Hal Finney) [Internet]. Bitcointalk forum post; 2013. Available from: https://bitcointalk.org/index.php?topic=155054.0
[4]
Andresen G. Pay to Script Hash [Internet]. Bitcoin Improvement Proposal 16; 2012. Available from: https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki
[5]
Lombrozo E, Lau J, Wuille P. Segregated Witness (Consensus Layer) [Internet]. Bitcoin Improvement Proposal 141; 2015. Available from: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
[6]
Wuille P, Nick J, Towns A. Taproot: SegWit version 1 spending rules [Internet]. Bitcoin Improvement Proposal 341; 2020. Available from: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
[7]
Wuille P, Nick J, Ruffing T. Schnorr Signatures for secp256k1 [Internet]. Bitcoin Improvement Proposal 340; 2020. Available from: https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki