P2SH ScriptPubKey Structure
P2SH ScriptPubKey Structure
The beauty of P2SH lies in its minimalist locking script. Regardless of how complex the underlying smart contract is, the ScriptPubKey on the blockchain always looks exactly the same.
1. The Locking Script (ScriptPubKey)
A P2SH script follows this three-part template:
OP_HASH160 [20-Byte Script Hash] OP_EQUAL
-
OP_HASH160: Hashes whatever is on the top of the stack (the Redeem Script provided by the spender) using SHA256 + RIPEMD160.
-
[20-Byte Hash]: The target provided by the sender.
-
OP_EQUAL: Returns
1if the hashes match, otherwise0.
2. Raw Hex Representation
In a raw transaction, a P2SH script is very compact:
a9 14 [20-byte-hash] 87
| Hex | Opcode | Purpose |
|---|---|---|
0x49 |
OP_HASH160 | Hash the provided script |
0x14 |
Push 20 Bytes | The length of the hash data |
0x87 |
OP_EQUAL | Verify the hashes match |
3. Comparison to P2PKH
You might notice that OP_HASH160 and a 20-byte hash are also used in P2PKH.
-
In P2PKH, the hash is of a Public Key.
-
In P2SH, the hash is of a Script (the Redeem Script).
4. The Hidden Logic
Because the script only contains a hash, a miner or observer cannot tell if the output is:
-
A 2-of-3 Multisig.
-
A Timelocked transaction (CLTV).
-
A complex escrow script. This is a massive boost for Privacy and Fungibility, as all P2SH outputs look identical on the ledger.
In the next section, we will break down the Redeem Script and how to unlock a P2SH output.
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: