示例#1
0
        /// <summary>
        /// Connects to a node with the given ip address and adds it to the node's peer pool.
        /// </summary>
        /// <param name="endpoint">the ip address of the distant node</param>
        /// <returns>True if the connection was successful, false otherwise</returns>
        public async Task <bool> ConnectAsync(IPEndPoint endpoint)
        {
            Logger.LogTrace($"Attempting to reach {endpoint}.");

            if (_peerPool.FindPeerByEndpoint(endpoint) != null)
            {
                Logger.LogWarning($"Peer {endpoint} is already in the pool.");
                return(false);
            }

            GrpcPeer peer;

            try
            {
                // create the connection to the distant node
                peer = await _peerDialer.DialPeerAsync(endpoint);
            }
            catch (PeerDialException ex)
            {
                Logger.LogError(ex, $"Dial exception {endpoint}:");
                return(false);
            }

            var peerPubkey = peer.Info.Pubkey;

            if (!_peerPool.TryAddPeer(peer))
            {
                Logger.LogWarning($"Peer {peerPubkey} is already in the pool.");
                await peer.DisconnectAsync(false);

                return(false);
            }

            Handshake peerHandshake;

            try
            {
                peerHandshake = await peer.DoHandshakeAsync(await _handshakeProvider.GetHandshakeAsync());
            }
            catch (NetworkException ex)
            {
                Logger.LogError(ex, $"Handshake failed to {endpoint} - {peerPubkey}.");
                await DisconnectAsync(peer);

                return(false);
            }

            HandshakeError handshakeError = ValidateHandshake(peerHandshake, peerPubkey);

            if (handshakeError != HandshakeError.HandshakeOk)
            {
                Logger.LogWarning($"Invalid handshake [{handshakeError}] from {endpoint} - {peerPubkey}");
                await DisconnectAsync(peer);

                return(false);
            }

            Logger.LogTrace($"Connected to {peer} - LIB height {peer.LastKnownLibHeight}, " +
                            $"best chain [{peer.CurrentBlockHeight}, {peer.CurrentBlockHash}].");

            FireConnectionEvent(peer);

            return(true);
        }
示例#2
0
 protected void OnHandshakeError(HandshakeState handshakeState, string errorMessage)
 {
     HandshakeError?.Invoke(this, new HandshakeErrorEventArgs(handshakeState, errorMessage));
 }