VersionNegotiationPacket.fromBytes constructor

VersionNegotiationPacket.fromBytes(
  1. Uint8List bytes
)

Creates a VERSION_NEGOTIATION packet from raw bytes

Implementation

factory VersionNegotiationPacket.fromBytes(Uint8List bytes) {
  const minLength = 18; // version(4) + dcidLen(1) + scidLen(1) + seq(4) + destId(4) + srcId(4)
  if (bytes.length < minLength) {
    throw ArgumentError(
        'Byte array too short for VersionNegotiationPacket');
  }

  final view =
      ByteData.view(bytes.buffer, bytes.offsetInBytes, bytes.lengthInBytes);
  int offset = 0;

  // Read version (should be 0 for VERSION_NEGOTIATION)
  final version = view.getUint32(offset, Endian.big);
  if (version != 0) {
    throw ArgumentError('Invalid VERSION_NEGOTIATION packet (version != 0)');
  }
  offset += 4;

  // Read destination CID
  final destCidLength = view.getUint8(offset);
  offset += 1;
  final destCid = ConnectionId.fromUint8List(
      bytes.sublist(offset, offset + destCidLength));
  offset += destCidLength;

  // Read source CID
  final srcCidLength = view.getUint8(offset);
  offset += 1;
  final srcCid = ConnectionId.fromUint8List(
      bytes.sublist(offset, offset + srcCidLength));
  offset += srcCidLength;

  // Read supported versions (rest of packet is list of 4-byte version numbers)
  final versions = <int>[];
  while (offset + 4 <= bytes.length) {
    versions.add(view.getUint32(offset, Endian.big));
    offset += 4;
  }

  return VersionNegotiationPacket(
    destinationCid: destCid,
    sourceCid: srcCid,
    supportedVersions: versions,
  );
}