TeachMeBitcoin

Witness Serialization

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

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:

  1. Item Count: A VarInt representing how many pieces of data are in this witness.

  2. Items: For each item, there is a length prefix followed by the raw data.

Example: P2WPKH Input

  1. Count: 02 (Signature + PubKey)

  2. Item 1 Length: 47 (71 bytes)

  3. Item 1 Data: [The Signature]

  4. Item 2 Length: 21 (33 bytes)

  5. Item 2 Data: [The Public Key]

3. Empty Witnesses

If a transaction has a mix of legacy and SegWit inputs:

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.

☕ Help support TeachMeBitcoin

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:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!