fromMultiaddr static method

Future<Peer> fromMultiaddr(
  1. String multiaddr
)

Creates a Peer from a multiaddr string

Implementation

static Future<Peer> fromMultiaddr(String multiaddr) async {
  try {
    // Parse the multiaddr to extract peer ID and address
    final parts = multiaddr.split('/');

    // The peer ID is the component after '/p2p/'
    final p2pIndex = parts.indexOf('p2p');
    if (p2pIndex == -1 || p2pIndex + 1 >= parts.length) {
      throw FormatException('No peer ID found in multiaddr: $multiaddr');
    }

    final peerIdStr = parts[p2pIndex + 1];
    if (peerIdStr.isEmpty) {
      throw FormatException('Empty peer ID in multiaddr: $multiaddr');
    }
    final peerId = PeerId(value: Base58().base58Decode(peerIdStr));

    // Parse the address portion
    final address = parseMultiaddrString(multiaddr);
    if (address == null) {
      throw FormatException('Invalid address in multiaddr: $multiaddr');
    }

    return Peer(
      id: peerId,
      addresses: [address],
      latency: 0, // Default latency for new peers
      agentVersion: '', // Empty version since we don't know it yet
    );
  } on FormatException {
    rethrow;
  } catch (e) {
    throw FormatException('Error parsing multiaddr: $e');
  }
}