dial method

  1. @override
Future<TransportConn> dial(
  1. MultiAddr addr, {
  2. Duration? timeout,
})
override

Dials a peer at the given multiaddress with optional timeout override Returns a connection to the peer if successful

Implementation

@override
Future<TransportConn> dial(MultiAddr addr, {Duration? timeout}) async {
  final host = addr.valueForProtocol('ip4') ?? addr.valueForProtocol('ip6');
  final port = int.parse(addr.valueForProtocol('tcp') ?? '0');

  if (host == null || port == 0) {
    throw ArgumentError('Invalid multiaddr: $addr');
  }

  // Use the provided timeout or fall back to the configured dial timeout
  final effectiveTimeout = timeout ?? config.dialTimeout;

  try {
    final socket = await Socket.connect(
      host,
      port,
      timeout: effectiveTimeout,
    ).timeout(
      effectiveTimeout,
      onTimeout: () => throw TimeoutException(
        'Connection timed out after ${effectiveTimeout.inSeconds} seconds',
      ),
    );

    // Create multiaddrs for local and remote endpoints
    final localAddr = MultiAddr('/ip4/${socket.address.address}/tcp/${socket.port}');
    final remoteAddr = MultiAddr('/ip4/${socket.remoteAddress.address}/tcp/${socket.remotePort}');

    // Placeholder PeerIDs - these should be derived from a security handshake
    // which typically happens before or as part of the transport upgrade process.
    // For now, using fixed placeholders. This is a CRITICAL point for a real system.
    final localPeerId = await PeerId.random(); // Using PeerId.random()
    final remotePeerId = await PeerId.random(); // Placeholder for remote PeerId (SHOULD COME FROM HANDSHAKE)


    final connection = await TCPConnection.create(
      socket,
      localAddr,
      remoteAddr,
      localPeerId,
      remotePeerId,
      // multiplexer, // Removed
      resourceManager,
      false, // isServer = false for dial
      legacyConnManager: _connManager
      // onIncomingStream callback removed from TCPConnection.create
    );

    // Set read/write timeouts from config (these are for the raw socket, may be deprecated)
    // connection.setReadTimeout(config.readTimeout);
    // connection.setWriteTimeout(config.writeTimeout);
    // Stream-level deadlines are preferred with multiplexing.

    return connection;
  } on TimeoutException catch (e) {
    throw e;
  } catch (e) {
    throw Exception('Failed to connect: $e');
  }
}