Witness Serialization
Witness Serialization
Understanding the raw binary format of the Witness is essential for parsing modern Bitcoin transactions. Unlike inputs and outputs, which are interleaved, the witness data for all inputs is collected at the very end of the transaction.
1. Global Positioning
A SegWit transaction follows this high-level structure:
[Version][Marker][Flag][Inputs][Outputs][Witness Data][Locktime]
The Witness Data section contains the proofs for every input in the order they appeared in the transaction.
2. Serialization per Input
For each input, the witness data consists of:
-
Item Count: A VarInt representing how many pieces of data are in this witness.
-
Items: For each item, there is a length prefix followed by the raw data.
Example: P2WPKH Input
-
Count:
02(Signature + PubKey) -
Item 1 Length:
47(71 bytes) -
Item 1 Data:
[The Signature] -
Item 2 Length:
21(33 bytes) -
Item 2 Data:
[The Public Key]
3. Empty Witnesses
If a transaction has a mix of legacy and SegWit inputs:
-
The legacy input still needs a slot in the Witness section.
-
The slot will simply contain a count of 0 (
0x00). This ensures that the node can correctly map each witness to the correct input.
4. Total Serialization Cheat Sheet
| Field | Size | Description |
|---|---|---|
| Marker | 1 Byte | Always 0x00 |
| Flag | 1 Byte | Always 0x01 (for SegWit) |
| Witness Count | VarInt | Number of items for Input 0 |
| Witness Item | VarLen | First item for Input 0 |
| ... | ... | Repeat for all inputs |
In the next section, we will discuss the Marker and Flag bytes that signal a SegWit transaction.
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: