addPeer method
Add a peer to the manager Throws PeerNetworkMismatchException if peer network doesn't match
Implementation
@override
Future<void> addPeer(PeerI peerInterface) async {
if (_isShutdown) {
throw ConnectionException('Peer manager is shutdown');
}
if (peerInterface is! Peer) {
throw ArgumentError('PeerManager only supports Peer instances');
}
final peer = peerInterface as Peer;
final peerId = '${peer.address}:${peer.port}';
// Validate network compatibility
if (peer.network != _network) {
throw PeerNetworkMismatchException(
'Peer network ${peer.network} does not match manager network $_network',
);
}
// Check if peer already exists
if (_peers.containsKey(peerId) || _connectingPeers.contains(peerId)) {
throw ConnectionException('Peer already exists: $peerId');
}
// Check peer limits
if (_peers.length >= config.maxPeers) {
throw ConnectionException('Maximum peers reached: ${config.maxPeers}');
}
logger.info('Adding peer: $peerId');
_connectingPeers.add(peerId);
try {
// Set up peer event listeners
_setupPeerListeners(peer, peerId);
// Register with chain tip tracker
_chainTipTracker.registerPeer(peerId);
// Connect the peer
await peer.connect();
// Move from connecting to connected
_connectingPeers.remove(peerId);
_peers[peerId] = peer;
_peerAddedController.add(peer);
logger.info('Successfully added peer: $peerId');
} catch (e) {
_connectingPeers.remove(peerId);
logger.warning('Failed to add peer $peerId: $e');
rethrow;
}
}