Script Hash and P2SH

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

Script Hash and P2SH

In general, whenever you want to receive coins from someone, you have to specify exactly what script to use. In the above example, all that’s needed is to provide the hash of the public key in a standardized address format, and the sender wallet creates the correct script.

But in the earlier more complicated example, with alternative conditions such as having a parent sign after a few years, communicating this becomes awkward. Even if there was an address standard, it would be a very long address indeed, due to all these different possible constraints.

Fortunately, there’s an alternative to giving the counterparty (the sender) the full script — you can give them the hash of the script, which is always the same length, and also happens to be the same length as a normal address.

In 2012, the Pay-to-Script-Hash (P2SH, BIP16) standard was introduced. These kinds of transactions let you send to a script hash, which is an address beginning with 3, in stead of sending to a public key hash, which is an address beginning with 1.

The person on the other end has to copy-paste it, put it in their Bitcoin wallet, and send money to it. Now, when you want to spend that money, you need to reveal the actual script to the blockchain, which your wallet will handle automatically. Because all you need to share is a hash, the person that’s sending you money doesn’t need to care what this hash actually hides. Only when you spend the coins do you need to reveal the constraints. From a privacy point of view, this is much better than immediately putting the script on the chain. The next chapter will explain how Taproot takes this even further.

Similar to the workflow with regular P2PKH addresses, what you communicate to the sender is just the hash of the script. Before the sender’s wallet puts that on the blockchain, it prepends OP_HASH160 and appends OP_EQUAL. So this is essentially a script within a script. The outer script, which the wallet puts on the blockchain, tells the blockchain there’s an inner script that must be revealed and satisfied by the recipient in order to spend from it.

This last requirement does not actually follow from the script on the blockchain, which only requires the hash of the script to match. This is why the new P2SH address type came with a soft fork to enforce that when such a script within a script is found, it is also executed. This usually means that the spender doesn’t just put the script on the stack, but also the ingredients necessary to satisfy the script, such as a signature.