Glossary

Transaction Serialization

Transaction serialization is the process of encoding a Bitcoin transaction into a byte sequence for network transmission, storage, and hash computation.

Key Takeaways

  • Transaction serialization converts a Bitcoin transaction into a deterministic byte sequence used for network transmission, disk storage, and computing the txid.
  • Two formats exist: legacy serialization (version, inputs, outputs, locktime) and the SegWit extended format defined in BIP 144, which adds marker, flag, and witness fields.
  • The serialized size directly determines transaction weight and fees: non-witness bytes count at 4 weight units each, while witness bytes count at 1, creating the witness discount.

What Is Transaction Serialization?

Transaction serialization is the process of encoding a structured Bitcoin transaction into a flat sequence of bytes. Every Bitcoin transaction consists of fields like version, inputs, outputs, and locktime, but computers and network protocols need a single unambiguous byte string to transmit, store, and hash. Serialization defines the exact rules for converting each field into bytes and concatenating them in a fixed order.

The serialized form is what nodes broadcast over the peer-to-peer network, what gets written to disk in block files, and what gets hashed to produce the transaction's unique identifier. Getting even one byte wrong means the hash changes and the transaction becomes invalid. This is why the serialization format is part of Bitcoin's consensus rules: every node must serialize transactions identically.

Before the SegWit upgrade in August 2017, there was only one serialization format. SegWit introduced a second, extended format that separates signature (witness) data from the rest of the transaction, solving the transaction malleability problem and enabling a more efficient use of block space.

How It Works

A serialized transaction is a concatenation of fields, each encoded according to specific rules. Most numeric fields use little-endian byte ordering, and variable-length collections are prefixed with a CompactSize integer indicating their count.

Legacy Serialization Format

The original Bitcoin transaction format serializes four top-level fields in order:

  1. Version (4 bytes, little-endian): indicates the transaction version number, typically 1 or 2
  2. Input count (CompactSize): the number of inputs that follow
  3. Inputs (variable): each input serialized in sequence
  4. Output count (CompactSize): the number of outputs that follow
  5. Outputs (variable): each output serialized in sequence
  6. Locktime (4 bytes, little-endian): block height or Unix timestamp before which the transaction cannot be included in a block
[version:4] [input_count:compactsize] [inputs:variable]
[output_count:compactsize] [outputs:variable] [locktime:4]

SegWit Extended Format (BIP 144)

The SegWit upgrade added three new fields to the serialization, creating an extended format:

  1. Version (4 bytes, little-endian)
  2. Marker (1 byte): always 0x00
  3. Flag (1 byte): always 0x01 in the current protocol
  4. Input count (CompactSize)
  5. Inputs (variable)
  6. Output count (CompactSize)
  7. Outputs (variable)
  8. Witness (variable): one witness stack per input, containing the signatures and other witness data
  9. Locktime (4 bytes, little-endian)
[version:4] [marker:1] [flag:1] [input_count:compactsize]
[inputs:variable] [output_count:compactsize] [outputs:variable]
[witness:variable] [locktime:4]

Parsers distinguish the two formats by checking the bytes after the version field. If the next byte is 0x00 (which would be an invalid CompactSize input count of zero in the legacy format), the parser knows this is a SegWit transaction and reads the marker and flag before continuing with the inputs.

Input Serialization

Each input is serialized as:

  1. Previous outpoint (36 bytes): the txid (32 bytes, internal byte order) and output index (4 bytes, little-endian) of the UTXO being spent
  2. ScriptSig length (CompactSize): byte length of the unlocking script
  3. ScriptSig (variable): the unlocking script data. For SegWit inputs, this field is empty (zero length) because the unlocking data moves to the witness section
  4. Sequence (4 bytes, little-endian): used for relative timelocks (BIP 68), replace-by-fee signaling, and nLockTime activation
// Input structure
[prev_txid:32] [prev_index:4] [scriptsig_len:compactsize]
[scriptsig:variable] [sequence:4]

Output Serialization

Each output is serialized as:

  1. Value (8 bytes, little-endian): the amount in satoshis
  2. ScriptPubKey length (CompactSize): byte length of the locking script
  3. ScriptPubKey (variable): the locking script that defines the spending conditions
// Output structure
[value:8] [scriptpubkey_len:compactsize] [scriptpubkey:variable]

CompactSize Integers

Bitcoin uses CompactSize (sometimes called VarInt) to encode counts and lengths. This variable-length integer format saves space by using fewer bytes for small values:

Value RangeEncodingBytes
0 to 252Single byte1
253 to 65,5350xFD prefix + 2-byte uint16 (little-endian)3
65,536 to 4,294,967,2950xFE prefix + 4-byte uint32 (little-endian)5
Larger values0xFF prefix + 8-byte uint64 (little-endian)9

Bitcoin Core enforces canonical (minimal) encoding: a value that fits in a smaller tier must not use a larger one. Non-minimal CompactSize values are rejected as invalid.

Transaction Identifiers

The serialization format determines how Bitcoin computes two distinct transaction identifiers:

  • txid: a double SHA-256 hash of the legacy serialization fields only (version, inputs, outputs, locktime). The marker, flag, and witness are excluded. This makes the txid immune to witness changes, which is the core fix for transaction malleability.
  • wtxid: a double SHA-256 hash of the full SegWit serialization, including marker, flag, and witness data. For transactions with no witness data, the wtxid equals the txid.

Both identifiers are 32 bytes (64 hex characters). The txid is used for referencing outputs in input outpoints, while the wtxid is used in the witness commitment structure within blocks. For a detailed walkthrough of how these identifiers fit into the broader transaction flow, see the Bitcoin transaction lifecycle guide.

Serialization and Transaction Weight

The serialized byte count directly determines a transaction's weight, which in turn determines the fees required for block inclusion. BIP 141 replaced the legacy 1 MB block size limit with a 4,000,000 weight unit limit and introduced a formula that discounts witness data:

weight = (base_size * 4) + (witness_size * 1)

// base_size: serialized size without marker, flag, witness
// witness_size: marker + flag + witness fields only

virtual_size = ceil(weight / 4)  // in vbytes

This means every byte of non-witness data (version, inputs, outputs, locktime) costs 4 weight units, while every byte of witness data costs only 1 weight unit. The rationale: witness data does not permanently affect the UTXO set that every full node must maintain, so it imposes a lower long-term cost on the network.

The virtual byte (vbyte) is the fee-relevant unit: miners select transactions based on fee rate measured in satoshis per vbyte. A transaction paying 10 sat/vB with a virtual size of 140 vbytes costs 1,400 satoshis in fees. Understanding serialization structure helps wallet developers estimate fees accurately by predicting the size of each field before constructing the transaction.

Use Cases

Fee Estimation

Wallets must predict the serialized size of a transaction before broadcasting it in order to attach the correct fee. This requires knowing the exact byte count of each input type, output type, and overhead field. For example, a P2WPKH input contributes roughly 41 non-witness bytes (outpoint, empty scriptSig, sequence) plus about 107 witness bytes (signature and public key), while a legacy P2PKH input puts all its data in the scriptSig with no witness savings.

Transaction Parsing and Validation

Every Bitcoin node deserializes incoming transactions to validate them. The serialization format acts as the wire protocol for the peer-to-peer network. Block explorers, indexers, and analysis tools all implement deserializers that reverse the encoding to extract structured transaction data. The deterministic nature of serialization ensures every parser produces identical results.

PSBT Workflows

The Partially Signed Bitcoin Transaction format (BIP 174) builds on transaction serialization by wrapping an unsigned transaction with additional metadata for multi-party signing workflows. The core serialized transaction inside a PSBT uses the standard format, with signing data attached as separate key-value pairs. Hardware wallets, multisig coordinators, and cold storage setups all rely on correct serialization to pass transactions between devices.

Layer 2 Protocols

Off-chain protocols like the Lightning Network and Spark construct pre-signed transactions that are serialized but not immediately broadcast. Correct serialization is critical because the txid of an unbroadcast transaction is computed from its serialized form, and child transactions reference that txid. If the serialization were to change (as was possible before SegWit due to malleability), the child transactions would become invalid.

Risks and Considerations

Byte Ordering Pitfalls

Bitcoin uses little-endian encoding for most numeric fields (version, value, locktime, sequence), but the txid within an outpoint is stored in internal byte order, which is reversed from the display format shown by block explorers. This inconsistency is a common source of bugs in custom transaction builders. Reversing the wrong field can produce a valid-looking but completely wrong serialization.

Non-Canonical Encodings

CompactSize integers must use the minimal encoding for their value. A value of 100 encoded with an 0xFD prefix (using 3 bytes instead of 1) is technically unambiguous but violates consensus rules. Bitcoin Core rejects transactions with non-canonical CompactSize values. Implementations that produce non-minimal encodings will create transactions that no node accepts.

Size Estimation Errors

Incorrect size estimation leads to under- or over-paying fees. The most common mistake is failing to account for the difference between serialized size and virtual size. A SegWit transaction might be 250 bytes on the wire but only 140 virtual bytes for fee calculation purposes. Using raw byte count instead of virtual size results in overpaying by roughly 40-75%, depending on the input types. Tools like the fee estimation algorithm comparison guide cover this topic in depth.

Format Detection Ambiguity

Parsers must handle both legacy and SegWit formats correctly. The 0x00 marker byte after the version field serves as a disambiguator because a legacy transaction can never have zero inputs. However, test vectors and edge cases (such as empty transactions used in some testing contexts) can trip up parsers that do not carefully check both the marker and flag bytes before switching to SegWit deserialization.

This glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.