This is a read note of Programming Bitcoin Ch13: Segwit. Segwit stands for “segragated witness” that is a backward-compatible upgrade or soft fork that activated on the Bitcoin network in August 2017. Segwit incorporated a multitude of changes:
- Block size increase
- Transaction malleability fix
- Segwit versioning for clear upgrade paths
- Quadratic hashing fix
- Offline wallet fee calculation security
1 Pay-to-Witness-Pubkey-Hash (p2wpkh)
Pay-to-witness-pubkey-hash (p2wpkh) is one of four types of scripts defined by Segwit in BIP0141 and BIP0143. The main change from p2pkh is that the data for the ScriptSig is now in the witness field. The rearrangement is to fix transaction malleability. Transaction malleability is the ability to change the transaction’s ID without altering the transaction’s meaning.
The reason why transaction malleability is a problem at all is because the transaction ID is calculated from the entire transaction. The ID of the transaction is the
hash256 of the transaction. Most of the fields in a transaction cannot be changed without invalidating the transaction’s signature (and thus the transaction itself), so from a malleability standpoint, these fields are not a problem.
The one field that does allow for some manipulation without invalidating the signature is the
ScriptSig field on each input. The
ScriptSig is emptied before creating the signature hash, so it’s possible to change the
ScriptSig without invalidating the signature. This makes the
ScriptSig field malleable, that is, able to be changed without changing the meaning, and means that the entire transaction, and the transaction ID, are malleable.
Transaction malleability is fixed by emptying the
ScriptSig field and putting the data in a
witness field that’s not used for ID calculation. The
witness field in
p2wpkh has the signature and pubkey as its two elements. These will be used for validation for upgraded nodes only.
2 Pay-to-Witness-Script-Hash (p2wsh)
p2wsh is like
p2sh, but with all the
ScriptSig data in the
witness field instead.
p2wsh script is
OP_0 <32-byte hash>. This sequence triggers another special rule. The
ScriptSig, as with
p2wpkh, is empty.