Variable-Length Integer (VarInt)
VarInt is a compact encoding scheme used in Bitcoin to represent integers that may vary widely in size.
Key Takeaways
- A variable-length integer (VarInt) is a compact encoding that uses 1, 3, 5, or 9 bytes depending on the magnitude of the value. Bitcoin's specific implementation is called CompactSize, and it appears throughout transaction serialization and P2P protocol messages.
- VarInts encode counts and lengths in Bitcoin transactions: the number of inputs, the number of outputs, script lengths, and witness item counts all use this format. This keeps small transactions compact while still supporting large values when needed.
- CompactSize is distinct from the signed Script Number format used inside Bitcoin Script. Confusing the two is a common source of bugs in custom transaction-building software.
What Is a Variable-Length Integer (VarInt)?
A variable-length integer, commonly called a VarInt, is an encoding scheme that represents non-negative integers using a variable number of bytes. Small values occupy fewer bytes, while larger values expand to use more space. In Bitcoin, this format is formally known as CompactSize (after the name used in Bitcoin Core's serialization code), though documentation and tooling often use the terms VarInt and CompactSize interchangeably.
The encoding exists because Bitcoin transactions contain many integer fields whose values span a wide range. A transaction might have 1 input or 2,000 inputs. A script might be 25 bytes or 10,000 bytes. Using a fixed 4-byte or 8-byte integer for every count or length would waste space in the common case where values are small. CompactSize solves this by adapting the byte width to the value being encoded: a single input count takes just 1 byte, not 4 or 8.
Since every transaction serialized on the Bitcoin network uses CompactSize fields, and every node must parse them identically, the encoding is a consensus-critical part of the protocol. Implementations that read or write these fields incorrectly will produce invalid transactions or fail to validate legitimate blocks.
How It Works
CompactSize encoding uses the first byte to signal how many additional bytes follow. The scheme is simple: if the first byte is below a threshold (252), it is the value itself. If the first byte is one of three special prefixes (0xFD, 0xFE, or 0xFF), the actual value follows in the next 2, 4, or 8 bytes respectively, encoded in little-endian byte order.
Encoding Ranges
| Value Range | Total Bytes | Format |
|---|---|---|
| 0 to 252 | 1 | Single byte containing the value |
| 253 to 65,535 | 3 | 0xFD prefix + 2 bytes (little-endian uint16) |
| 65,536 to 4,294,967,295 | 5 | 0xFE prefix + 4 bytes (little-endian uint32) |
| 4,294,967,296 to 264-1 | 9 | 0xFF prefix + 8 bytes (little-endian uint64) |
Encoding Examples
The following examples show how different values are encoded in CompactSize format:
Value: 1
Encoded: 0x01
(1 byte: value fits in a single byte)
Value: 252
Encoded: 0xFC
(1 byte: largest single-byte value)
Value: 253
Encoded: 0xFD 0xFD 0x00
(3 bytes: 0xFD prefix, then 253 as uint16 LE)
Value: 550
Encoded: 0xFD 0x26 0x02
(3 bytes: 0xFD prefix, then 550 as uint16 LE)
Value: 70000
Encoded: 0xFE 0x70 0x11 0x01 0x00
(5 bytes: 0xFE prefix, then 70000 as uint32 LE)Canonical Encoding
The CompactSize format is technically redundant: a small value like 1 could be encoded as a single byte (0x01), or wastefully as three bytes (0xFD 0x01 0x00) using the uint16 prefix. To prevent ambiguity, Bitcoin Core enforces canonical (minimal) encoding. The ReadCompactSize function in Bitcoin Core's serialization code rejects any encoding that uses more bytes than necessary. For example, encoding the value 100 with a 0xFD prefix would be rejected even though it is technically decodable.
This canonical encoding rule is enforced at the P2P network layer. Nodes reject messages containing non-canonical CompactSize values, which prevents peers from sending malformed data that could cause parsing inconsistencies across different implementations.
Where VarInts Appear in Bitcoin
CompactSize integers are used throughout Bitcoin's wire format. Any field that represents a count or a byte length in the serialized data is typically encoded as a CompactSize.
Transaction Serialization
A serialized Bitcoin transaction uses CompactSize in multiple places. For a standard transaction, the layout includes:
- Input count: the number of transaction inputs
- ScriptSig length: the byte length of each input's unlocking script
- Output count: the number of transaction outputs
- ScriptPubKey length: the byte length of each output's locking script
Transaction layout (simplified):
┌──────────┬───────────────┬──────────────┬───────────────┬──────────┐
│ version │ input count │ inputs... │ output count │ outputs │
│ (4 bytes)│ (CompactSize) │ │ (CompactSize) │ │
└──────────┴───────────────┴──────────────┴───────────────┴──────────┘
Each input contains:
┌───────────┬────────────────────┬──────────────┬──────────┐
│ outpoint │ scriptSig length │ scriptSig │ sequence │
│ (36 bytes)│ (CompactSize) │ (variable) │ (4 bytes)│
└───────────┴────────────────────┴──────────────┴──────────┘In a typical transaction with 1 input and 2 outputs, the input count is encoded as a single byte (0x01) and the output count as (0x02). This keeps the overhead minimal for common transaction sizes. For a deeper look at how transactions are assembled, see the Bitcoin transaction lifecycle research article.
Witness Data
With the introduction of Segregated Witness (SegWit), CompactSize encoding gained additional uses in the witness section of transactions:
- Witness item count: the number of witness stack items for each input
- Witness item length: the byte length of each individual witness stack item
These fields directly affect transaction weight calculations. Because witness data receives a discount under the SegWit weight formula, the CompactSize bytes within the witness section count as 1 weight unit each, while CompactSize bytes in the non-witness portion count as 4 weight units. This distinction matters for precise fee estimation.
P2P Protocol Messages
Beyond transactions, CompactSize integers appear in many Bitcoin P2P protocol messages. Inventory vectors, address lists, and block header counts all use the format. For example, the inv message uses a CompactSize to indicate how many inventory entries follow, and the addr message uses one to indicate the number of network addresses being advertised.
CompactSize vs Script Number Format
A common point of confusion is the difference between CompactSize and the number format used inside Bitcoin Script. These are entirely separate encoding systems used in different contexts:
| Property | CompactSize | Script Number (CScriptNum) |
|---|---|---|
| Purpose | Counts and lengths in serialization | Arithmetic operands on the Script stack |
| Signed | No (unsigned only) | Yes (sign-magnitude encoding) |
| Range | 0 to 264-1 | Typically limited to 4 bytes (roughly -231 to 231-1) |
| Byte order | Little-endian with prefix byte | Little-endian with sign in MSB of last byte |
| Zero encoding | 0x00 (one byte) | Empty byte array (zero bytes) |
| Minimal encoding | Enforced at P2P layer | Required by consensus (MINIMALDATA rule) |
Script numbers use a sign-magnitude representation where the highest bit of the last byte indicates the sign. Zero is represented as an empty byte array, and the encoding must be minimal under the MINIMALDATA consensus rule. This format is designed for the arithmetic opcodes (OP_ADD, OP_SUB, and others) that operate on the Script stack.
CompactSize, by contrast, is never negative and never appears on the Script stack. It is purely a framing mechanism for the byte stream that wraps around scripts, counts, and other structural elements in the serialized data.
Bitcoin Core's CVarInt
Adding to the naming confusion, Bitcoin Core also defines a separate encoding called CVarInt for its internal UTXO database (the chainstate). This format uses a 7-bit continuation encoding (similar to protobuf varints) and is more space-efficient than CompactSize for small values, but it is never used in the consensus wire format. When documentation refers to "Bitcoin VarInt," it almost always means CompactSize, not CVarInt.
Why It Matters
CompactSize encoding directly impacts how much block space a transaction consumes and therefore how much it costs in fees. For a standard single-input, two-output transaction, the CompactSize fields add only a few bytes of overhead. But for large transactions with hundreds of inputs or long scripts, the encoding ensures that byte counts remain compact while still supporting the full range of valid sizes.
For developers building Bitcoin Script-based applications or working with raw transaction construction, understanding CompactSize is essential. Incorrect encoding will produce invalid transactions, and confusing CompactSize with Script numbers or other integer formats is a common source of serialization bugs. Libraries like Bitcoin Development Kit (BDK) and rust-bitcoin handle CompactSize automatically, but anyone working at a lower level needs to implement the encoding correctly.
Layer 2 protocols that build on Bitcoin's transaction format, including the Lightning Network and Spark, inherit CompactSize as part of the underlying transaction structure. When Spark constructs on-chain settlement transactions or cooperative exit transactions, CompactSize encoding governs how those transactions are serialized on the base layer.
Risks and Considerations
Implementation Pitfalls
The most common risk with CompactSize is implementation error. Developers who build their own transaction serializers must handle all four encoding ranges correctly and enforce canonical (minimal) encoding on deserialization. Failing to reject non-canonical encodings can create inconsistencies between nodes: if one implementation accepts a non-canonical encoding that another rejects, the network could diverge on which transactions are valid.
Naming Confusion
The term "VarInt" is used in many protocols (Protocol Buffers, SQLite, LEB128) with different encoding schemes. Bitcoin's CompactSize uses a prefix-byte scheme, not the 7-bit continuation encoding common in other systems. Additionally, as noted above, Bitcoin Core itself uses the name "VarInt" for its database encoding, which differs from the CompactSize format used in transactions. When reading documentation or reviewing code, always verify which specific encoding is being referenced.
Size Overhead in Edge Cases
CompactSize is optimized for small values but can be less space-efficient than alternative encodings at certain boundaries. The value 253, for example, requires 3 bytes in CompactSize but only 2 bytes in a 7-bit continuation encoding. For Bitcoin's use cases this tradeoff is acceptable: the simplicity of the prefix-byte scheme makes it easier to implement correctly, and the vast majority of real-world values (input counts, output counts, typical script lengths) fall in the 1-byte range.
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.