multiaddrFromBytes function

FullAddress? multiaddrFromBytes(
  1. Uint8List bytes
)

Helper to decode binary multiaddr to FullAddress

Implementation

FullAddress? multiaddrFromBytes(Uint8List bytes) {
  try {
    var offset = 0;
    // Protocol code 1
    final p1 = bytes[offset++];

    String? ip;
    int? port;

    if (p1 == 4) {
      // ip4
      if (bytes.length < offset + 4) return null;
      ip = bytes.sublist(offset, offset + 4).join('.');
      offset += 4;
    } else if (p1 == 41) {
      // ip6
      if (bytes.length < offset + 16) return null;
      // Simple hex conversion for IPv6
      final hex = bytes
          .sublist(offset, offset + 16)
          .map((b) => b.toRadixString(16).padLeft(2, '0'))
          .toList();
      final groups = <String>[];
      for (var i = 0; i < 16; i += 2) {
        groups.add('${hex[i]}${hex[i + 1]}');
      }
      ip = groups.join(':');
      if (ip == '0000:0000:0000:0000:0000:0000:0000:0001') ip = '::1';
      offset += 16;
    } else {
      return null; // Unsupported transport
    }

    if (offset >= bytes.length) return null;
    final p2 = bytes[offset++];

    if (p2 == 6) {
      // tcp
      if (bytes.length < offset + 2) return null;
      final portBytes = bytes.sublist(offset, offset + 2);
      port = (portBytes[0] << 8) | portBytes[1];
      offset += 2;
    } else if (p2 == 17) {
      // udp
      if (bytes.length < offset + 2) return null;
      final portBytes = bytes.sublist(offset, offset + 2);
      port = (portBytes[0] << 8) | portBytes[1];
      offset += 2;
    }

    if (port != null) {
      return FullAddress(address: ip, port: port);
    }
    return null;
  } catch (e) {
    return null;
  }
}