Esempio n. 1
0
        private void ProcessMessageCore(IncomingMessage message)
        {
            if (message.Message.Payload is VersionPayload)
            {
                VersionPayload version         = message.AssertPayload <VersionPayload>();
                bool           connectedToSelf = version.Nonce == this.Nonce;
                if ((message.NetworkPeer != null) && connectedToSelf)
                {
                    NodeServerTrace.ConnectionToSelfDetected();
                    message.NetworkPeer.DisconnectAsync();
                    return;
                }

                if (message.NetworkPeer == null)
                {
                    IPEndPoint remoteEndpoint = version.AddressFrom;
                    if (!remoteEndpoint.Address.IsRoutable(this.AllowLocalPeers))
                    {
                        // Send his own endpoint.
                        remoteEndpoint = new IPEndPoint(((IPEndPoint)message.Socket.RemoteEndPoint).Address, this.Network.DefaultPort);
                    }

                    var peerAddress = new NetworkAddress()
                    {
                        Endpoint = remoteEndpoint,
                        Time     = DateTimeOffset.UtcNow
                    };

                    NetworkPeer networkPeer = this.networkPeerFactory.CreateNetworkPeer(peerAddress, this.Network, CreateNetworkPeerConnectionParameters(), message.Socket, version);
                    if (connectedToSelf)
                    {
                        networkPeer.SendMessage(CreateNetworkPeerConnectionParameters().CreateVersion(networkPeer.PeerAddress.Endpoint, this.Network));
                        NodeServerTrace.ConnectionToSelfDetected();
                        networkPeer.Disconnect();
                        return;
                    }

                    CancellationTokenSource cancel = new CancellationTokenSource();
                    cancel.CancelAfter(TimeSpan.FromSeconds(10.0));
                    try
                    {
                        this.ConnectedNetworkPeers.Add(networkPeer);
                        networkPeer.StateChanged += Peer_StateChanged;
                        networkPeer.RespondToHandShake(cancel.Token);
                    }
                    catch (OperationCanceledException ex)
                    {
                        NodeServerTrace.Error("The remote peer did not respond fast enough (10 seconds) to the handshake completion, dropping connection", ex);
                        networkPeer.DisconnectAsync();
                        throw;
                    }
                    catch (Exception)
                    {
                        networkPeer.DisconnectAsync();
                        throw;
                    }
                }
            }

            this.MessageReceived?.Invoke(this, message);
        }
        /// <summary>
        /// Processes a new message received from a connected client peer.
        /// </summary>
        /// <param name="message">Message received from the client.</param>
        private void ProcessMessageCore(IncomingMessage message)
        {
            this.logger.LogTrace("({0}:'{1}')", nameof(message), message.Message.Command);

            if (message.Message.Payload is VersionPayload)
            {
                VersionPayload version         = message.AssertPayload <VersionPayload>();
                bool           connectedToSelf = version.Nonce == this.Nonce;

                if (connectedToSelf)
                {
                    this.logger.LogDebug("Connection to self detected and will be aborted.");
                }

                if ((message.NetworkPeer != null) && connectedToSelf)
                {
                    message.NetworkPeer.DisconnectWithException();

                    this.logger.LogTrace("(-)[CONNECTED_TO_SELF]");
                    return;
                }

                if (message.NetworkPeer == null)
                {
                    this.logger.LogDebug("First message received from peer '{0}'.", version.AddressFrom);

                    IPEndPoint remoteEndpoint = version.AddressFrom;
                    if (!remoteEndpoint.Address.IsRoutable(this.AllowLocalPeers))
                    {
                        // Send his own endpoint.
                        remoteEndpoint = new IPEndPoint(((IPEndPoint)message.Socket.RemoteEndPoint).Address, this.Network.DefaultPort);
                    }

                    var peerAddress = new NetworkAddress()
                    {
                        Endpoint = remoteEndpoint,
                        Time     = this.dateTimeProvider.GetUtcNow()
                    };

                    NetworkPeer networkPeer = this.networkPeerFactory.CreateNetworkPeer(peerAddress, this.Network, CreateNetworkPeerConnectionParameters(), message.Socket, version);
                    if (connectedToSelf)
                    {
                        networkPeer.SendMessage(CreateNetworkPeerConnectionParameters().CreateVersion(networkPeer.PeerAddress.Endpoint, this.Network, this.dateTimeProvider.GetTimeOffset()));
                        networkPeer.Disconnect();

                        this.logger.LogTrace("(-)[CONNECTED_TO_SELF_2]");
                        return;
                    }

                    using (CancellationTokenSource cancel = new CancellationTokenSource())
                    {
                        cancel.CancelAfter(TimeSpan.FromSeconds(10.0));
                        try
                        {
                            this.ConnectedNetworkPeers.Add(networkPeer);
                            networkPeer.StateChanged += Peer_StateChanged;
                            networkPeer.RespondToHandShake(cancel.Token);
                        }
                        catch (OperationCanceledException)
                        {
                            this.logger.LogTrace("Remote peer haven't responded within 10 seconds of the handshake completion, dropping connection.");

                            networkPeer.DisconnectWithException();

                            this.logger.LogTrace("(-)[HANDSHAKE_TIMEDOUT]");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            this.logger.LogTrace("Exception occurred: {0}", ex.ToString());

                            networkPeer.DisconnectWithException();

                            this.logger.LogTrace("(-)[HANDSHAKE_EXCEPTION]");
                            throw;
                        }
                    }
                }
            }

            this.logger.LogTrace("(-)");
        }