1

In the bitcoin-book, the "Transaction Counter" part of a block is documented as being 1~9 bytes long instead of a fixed size.

How is this counter parsed from the raw data?

1

This number is encoded as a variable-length integer, see the txn_count in the block protocol message.

The idea is the following:

  • Read the first byte as marker
  • If marker < 0xFD
    • marker is the number
  • If marker == 0xFD
    • read the next 2 bytes as the number
  • If marker == 0xFE
    • read the next 4 bytes as the number
  • If marker == 0xFF
    • read the next 8 bytes as the number

Or, in Python:

def read_varint(byte_array):
    marker = byte_array[0]
    if marker < 0xfd:
        return marker
    elif marker == 0xfd:
        return int.from_bytes(byte_array[1:3], 'little')
    elif marker == 0xfe:
        return int.from_bytes(byte_array[1:5], 'little')
    else:
        return int.from_bytes(byte_array[1:9], 'little')

See also the implementation in Bitcoin Core here.

4
  • Thanks a lot. BTW, this varint algo is not a "watch ahead" I think :)
    – ntk138
    Feb 27 at 12:01
  • Oh i need to edit my answer anyways as i cleaned up your question to make it more concise :) Also, not sure about what you mean by "watch ahead algorithm" ?
    – darosior
    Feb 27 at 12:03
  • "watch ahead" is read some extra data ahead to determine the meaning of the current token. e.g. here if the algo needs to read some bytes of the TX content, then it is a watch ahead. varint is a clever algo does not need to watch ahead.
    – ntk138
    Feb 27 at 12:08
  • Ok, thanks! (random characters here to make the minimum comment length)
    – darosior
    Feb 27 at 12:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.