fromBytes static method

MultiAddr fromBytes(
  1. Uint8List bytes
)

Creates a Multiaddr from bytes

Implementation

static MultiAddr fromBytes(Uint8List bytes) {
  var offset = 0;
  final components = <(Protocol, String)>[];

  while (offset < bytes.length) {
    // Read protocol code
    final (code, protocolBytesRead) = MultiAddrCodec.decodeVarint(bytes, offset);
    offset += protocolBytesRead;

    final protocol = Protocols.byCode(code);
    if (protocol == null) {
      throw FormatException('Unknown protocol code: $code');
    }

    // Read value
    int valueLength;
    if (protocol.isVariableSize) {
      final (length, lengthBytesRead) = MultiAddrCodec.decodeVarint(bytes, offset);
      offset += lengthBytesRead;
      valueLength = length;
    } else {
      valueLength = protocol.size ~/ 8;
    }

    if (offset + valueLength > bytes.length) {
      throw FormatException('Invalid multiaddr bytes: unexpected end of input');
    }

    final valueBytes = bytes.sublist(offset, offset + valueLength);
    final value = MultiAddrCodec.decodeValue(protocol, valueBytes);
    components.add((protocol, value));

    offset += valueLength;
  }

  // Reconstruct string representation
  final sb = StringBuffer();
  for (final (protocol, value) in components) {
    sb.write('/${protocol.name}');
    if (protocol.size != 0) { // Only add value if protocol is not size 0
      sb.write('/$value');
    }
    // If protocol.size == 0, we add nothing more for this component.
  }
  final finalAddrString = sb.toString();
  return MultiAddr(finalAddrString);
}