MsgGetHeaders.deserialize constructor

MsgGetHeaders.deserialize(
  1. Uint8List data
)

Deserializes a MsgGetHeaders from byte data.

Implementation

factory MsgGetHeaders.deserialize(Uint8List data) {
  final buffer = ByteData.sublistView(data);
  var offset = 0;

  // Protocol version (4 bytes, little endian)
  if (offset + 4 > data.length) {
    throw WireException('getheaders', 'Insufficient data for protocol version');
  }
  final protocolVersion = buffer.getUint32(offset, Endian.little);
  offset += 4;

  // Number of block locator hashes (VarInt)
  if (offset >= data.length) {
    throw WireException('getheaders', 'Insufficient data for locator count');
  }
  final count = VarInt.read(buffer, offset);
  offset += VarInt.size(count);

  // Limit to max block locator hashes per message
  if (count > maxBlockLocatorsPerMsg) {
    throw WireException('getheaders',
        'Too many block locator hashes for message: count $count, max $maxBlockLocatorsPerMsg');
  }

  // Block locator hashes (32 bytes each)
  final blockLocatorHashes = <Hash>[];
  for (int i = 0; i < count; i++) {
    if (offset + hashSize > data.length) {
      throw WireException('getheaders',
          'Insufficient data for block locator hash $i: need $hashSize, got ${data.length - offset}');
    }
    final hashBytes = data.sublist(offset, offset + hashSize);
    final hash = Hash.fromBytes(hashBytes);
    blockLocatorHashes.add(hash);
    offset += hashSize;
  }

  // Hash stop (32 bytes)
  if (offset + hashSize > data.length) {
    throw WireException('getheaders',
        'Insufficient data for hash stop: need $hashSize, got ${data.length - offset}');
  }
  final hashStopBytes = data.sublist(offset, offset + hashSize);
  final hashStop = Hash.fromBytes(hashStopBytes);

  return MsgGetHeaders(
    protocolVersion: protocolVersion,
    blockLocatorHashes: blockLocatorHashes,
    hashStop: hashStop,
  );
}