A VarInt (variable integer) is a field used in transaction data to indicate the number of upcoming fields, or the length of an upcoming field.
Here’s a transaction with the VarInt fields highlighted (and if it’s referring to a field length, the length of that field is highlighted too):
A VarInt is most commonly a 1 byte hexadecimal value:
0x6a = 106 bytes --|------------------------------------- ... --| 6a47304402200aa5891780e216bf1941b502de29 ... 926
However, if the VarInt is going to be greater than
0xfc (so the number you’re trying to express won’t fit inside of two hexadecimal characters) then you can expand the field in the following way:
1 byte = 2 characters
1. VarInt =
There is no prefix of
ff, so we know this 1 byte is the VarInt value, and we can convert hexadecimal straight to decimal:
Varint = 6a = 106 bytes
2. VarInt =
The prefix is
fd, so we know the next 2 bytes (in little-endian) is going to give us the size of the upcoming field:
VarInt = fd2606 = 2602 (next 2 bytes) = 0226 ([swap endian](/tools/swapendian)) = 550 bytes
3. Varint =
Similar to the last example, except
fe means it’s the next 4 bytes:
VarInt = fe703a0f00 VarInt = 703a0f00 VarInt = 000f3a70 = 998000 bytes
Why are VarInts used?
In transaction data, fields like the
vout have a fixed size, so you always know where they start and end. However, fields like scriptSig can vary in length, so a VarInt field is placed before it so you know how many bytes in length it is.
These VarInts are essential if you have written a script or program that reads transaction data, as without them you wouldn’t know where the variable length fields end.