BlockHeader.deserialize constructor

BlockHeader.deserialize(
  1. Uint8List data
)

Deserializes a block header from bytes using Bitcoin protocol encoding.

Implementation

factory BlockHeader.deserialize(Uint8List data) {
  if (data.length < blockHeaderLen) {
    throw WireException('block_header',
        'Insufficient data for block header: need $blockHeaderLen, got ${data.length}');
  }

  final buffer = ByteData.sublistView(data);
  var offset = 0;

  // Version (4 bytes, little endian)
  final version = buffer.getUint32(offset, Endian.little);
  offset += 4;

  // Previous block hash (32 bytes)
  final prevBlockBytes = Uint8List(hashSize);
  for (int i = 0; i < hashSize; i++) {
    prevBlockBytes[i] = buffer.getUint8(offset + i);
  }
  final prevBlock = Hash.fromBytes(prevBlockBytes);
  offset += hashSize;

  // Merkle root hash (32 bytes)
  final merkleRootBytes = Uint8List(hashSize);
  for (int i = 0; i < hashSize; i++) {
    merkleRootBytes[i] = buffer.getUint8(offset + i);
  }
  final merkleRoot = Hash.fromBytes(merkleRootBytes);
  offset += hashSize;

  // Timestamp (4 bytes, little endian)
  final timestampSeconds = buffer.getUint32(offset, Endian.little);
  final timestamp = DateTime.fromMillisecondsSinceEpoch(timestampSeconds * 1000);
  offset += 4;

  // Bits (4 bytes, little endian)
  final bits = buffer.getUint32(offset, Endian.little);
  offset += 4;

  // Nonce (4 bytes, little endian)
  final nonce = buffer.getUint32(offset, Endian.little);

  return BlockHeader(
    version: version,
    prevBlock: prevBlock,
    merkleRoot: merkleRoot,
    timestamp: timestamp,
    bits: bits,
    nonce: nonce,
  );
}