decodeVarint static method

Tuple<int, int> decodeVarint(
  1. List<int> byteint
)

Decodes a variable-length byte array into an integer value according to Bitcoin's variable-length integer encoding scheme.

byteint The list of bytes representing the encoded variable-length integer. Returns a tuple containing the decoded integer value and the number of bytes consumed from the input.

If the first byte is less than 253, a single byte is used, returning the value and consuming 1 byte. If the first byte is 253, a 2-byte encoding is used, returning the value and consuming 2 bytes. If the first byte is 254, a 4-byte encoding is used, returning the value and consuming 4 bytes. If the first byte is 255, an 8-byte encoding is used, returning the value and consuming 8 bytes.

Throws a MessageException if the decoded value cannot fit into an integer in the current environment.

Implementation

static Tuple<int, int> decodeVarint(List<int> byteint) {
  final int ni = byteint[0];
  int size = 0;

  if (ni < 253) {
    return Tuple(ni, 1);
  }

  if (ni == 253) {
    size = 2;
  } else if (ni == 254) {
    size = 4;
  } else {
    size = 8;
  }

  final BigInt value = BigintUtils.fromBytes(byteint.sublist(1, 1 + size),
      byteOrder: Endian.little);
  if (!value.isValidInt) {
    throw const MessageException(
        "cannot read variable-length in this environment");
  }
  return Tuple(value.toInt(), size + 1);
}