Saturday, June 27, 2026
HomeBitcoinbitcoin core - What's the distinction between the CompactSize and VarInt encodings?

bitcoin core – What’s the distinction between the CompactSize and VarInt encodings?

There are two distinct variable-length integer encodings carried out in Bitcoin Core’s serialization framework:

  1. The encoding used within the P2P protocol for the lengths of vectors (variety of transactions in blocks, variety of inputs/outputs in transactions, variety of entries in inv/addr messages, …) is thought contained in the Bitcoin Core codebase because the “CompactSize” encoding, although it has traditionally been referred to in exterior protocol documentation as “VarInt”.
  2. One other encoding which is just used internally in Bitcoin Core, in e.g. its UTXO database on disk, however is not used anyplace within the P2P protocol. That is referred to contained in the Bitcoin Core codebase as “VarInt”.

For reference, the 2 encodings are:

  1. The “CompactSize” encoding (also called “VarInt” outdoors Bitcoin Core):
  • 0..0xfc: 1 byte (the worth itself)
  • 0xfd..0xffff: 3 bytes (0xfd + 2 byte little endian encoding)
  • 0x10000..0xffffffff: 5 bytes (0xfe + 4 byte little endian encoding)
  • 0x100000000..0xffffffffffffffff: 9 bytes (0xff + 8 byte little endian encoding)
  1. The “VarInt” encoding (not used outdoors Bitcoin Core) is described contained in the codebase as follows:

Variable-length integers: bytes are a MSB base-128 encoding of the quantity.
The excessive bit in every byte signifies whether or not one other digit follows. To make
certain the encoding is one-to-one, one is subtracted from all however the final digit.
Thus, the byte sequence a[] with size len, the place all however the final byte
has bit 128 set, encodes the quantity:

(a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))

It leads to the next sizes:

  • 0..0x7f: 1 byte
  • 0x80..0x407f: 2 bytes
  • 0x4080..0x20407f: 3 bytes
  • 0x204080..0x1020407f: 4 bytes
  • 0x10204080..0x81020407f: 5 bytes

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments