CompactSize Varint

easy · bitcoin, encoding, varint

CompactSize Varint

Bitcoin uses a compact variable-length integer encoding ("CompactSize") for counts and script lengths.

Encoding

  • If n < 0xfd, encode as a single byte n.
  • If n <= 0xffff, encode as 0xfd followed by little-endian uint16.
  • If n <= 0xffffffff, encode as 0xfe followed by little-endian uint32.
  • Otherwise, encode as 0xff followed by little-endian uint64.

Canonical decoding

Decoding must reject non-canonical encodings:

  • 0xfd prefix is invalid if the value < 0xfd.
  • 0xfe prefix is invalid if the value < 0x10000.
  • 0xff prefix is invalid if the value < 0x100000000.

Functions

func EncodeCompactSize(n uint64) []byte
func DecodeCompactSize(data []byte) (value uint64, size int, ok bool)

Notes

  • DecodeCompactSize returns (0, 0, false) on insufficient data or non-canonical encodings.
  • size is the number of bytes consumed.
Run tests to see results
No issues detected