connect method

Future<void> connect()

Connect to the peer and perform Bitcoin protocol handshake

Implementation

Future<void> connect() async {
  if (_state != PeerState.disconnected) {
    throw ConnectionException('Peer is already connected or connecting');
  }

  _setState(PeerState.connecting);
  logger.info('Connecting to peer $address:$port...');

  try {
    // Create underlying connection
    _connection = PeerConnection(
      address: address,
      port: port,
      network: _network,
      logger: logger,
    );

    // Set up event listeners
    _setupConnectionListeners();

    // Connect to peer
    await _connection!.connect();
    _connectedAt = DateTime.now();
    _setState(PeerState.connected);

    // Start Bitcoin protocol handshake
    await _performHandshake();

  } catch (e) {
    logger.warning('Failed to connect to peer: $e');
    _setState(PeerState.error);
    await _cleanup();
    rethrow;
  }
}