P2WSH Script - Full Witness Execution
6. P2WSH Script — Full Witness Execution
Overview
Pay-to-Witness-Script-Hash (P2WSH) is the SegWit equivalent of P2SH, introduced alongside P2WPKH in BIP 141. Instead of a 20-byte hash, the witness program is a 32-byte SHA256 hash of a witness script, providing stronger pre-image resistance. P2WSH enables complex scripts (multisig, timelocks, custom logic) to benefit from SegWit's weight discount and malleability fix.
Script Structure
Locking script (scriptPubKey) — 34 bytes:
OP_0 <32-byte witness program>
The 32-byte witness program is SHA256(witnessScript) — note: only SHA256, not HASH160.
scriptSig: Empty.
Witness:
<n items satisfying witnessScript>
<serialized witnessScript>
Byte-Level Anatomy
scriptPubKey (34 bytes):
00 <- OP_0 (witness version 0)
20 <- push 32 bytes
<32-byte SHA256(witnessScript)>
Witness for 2-of-3 multisig:
05 <- 5 witness items
00 <- empty dummy (OP_CHECKMULTISIG bug)
47 <- sig1 length
<sig1>
47 <- sig2 length
<sig2>
XX <- witnessScript length
<witnessScript bytes>
Execution Rules
For a 32-byte version 0 witness program:
-
The last witness item is deserialized as the witnessScript.
-
SHA256(witnessScript)is computed and compared to the 32-byte witness program. -
If they match, the witnessScript is executed with the remaining witness items as the initial stack.
Witness stack (before script execution):
[<dummy>, <sig1>, <sig2>]
witnessScript (2-of-3 multisig):
OP_2 <pk1> <pk2> <pk3> OP_3 OP_CHECKMULTISIG
Execution:
→ OP_CHECKMULTISIG verifies 2 of 3 signatures
→ Stack: [1]
→ VALID
Security Upgrade: 32-byte Hash
P2WSH uses a 32-byte SHA256 hash instead of the 20-byte HASH160 used in P2SH. This matters for complex scripts:
P2SH collision resistance: 2^80 (birthday attack on 160-bit hash)
P2WSH collision resistance: 2^128 (birthday attack on 256-bit hash)
For advanced multisig and contract scripts where the script itself is large, the stronger hash prevents theoretical script-substitution attacks.
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: