Beispiel #1
0
        public void Handle(PeerConnected data)
        {
            OmnibusStateEntry entry;

            if (byPeer.TryGetValue(data.Peer, out entry) == false)
            {
                entry = new OmnibusStateEntry(data.Peer);
                byPeer.Add(data.Peer, entry);
            }

            entry.State = new PeerState();
        }
Beispiel #2
0
 /// <inheritdoc/>
 public void OnPeerConnected(NetPeer peer)
 {
     if (masterPeer == null)
     {
         masterPeer = new LiteNetLibPeerManager(peer);
     }
     else if (!Equals(masterPeer.PeerEndPoint, peer.EndPoint))
     {
         throw new ArgumentException("Client can be connected only to a single peer.");
     }
     PeerConnected?.Invoke(masterPeer);
 }
Beispiel #3
0
        private async Task ConnectAndHandshake(Peer peer)
        {
            peer.OnDisconnect += DisconnectPeer;
            if (peer.IsIncoming)
            {
                Interlocked.Increment(ref this.incomingCount);
            }

            // connect
            await peer.ConnectAsync();

            // notify peer is connected
            PeerConnected?.Invoke(peer);

            // setup task to wait for verack
            var verAckTask = peer.Receiver.WaitForMessage(x => x.Command == "verack", HANDSHAKE_TIMEOUT_MS);

            // setup task to wait for version
            var versionTask = peer.Receiver.WaitForMessage(x => x.Command == "version", HANDSHAKE_TIMEOUT_MS);

            // start listening for messages after tasks have been setup
            peer.Receiver.Listen();

            // send our local version
            var nodeId = random.NextUInt64(); //TODO should be generated and verified on version message

            var currentHeight = this.coreDaemon.CurrentChain.Height;
            await peer.Sender.SendVersion(Messaging.GetExternalIPEndPoint(), peer.RemoteEndPoint, nodeId, (UInt32)currentHeight);

            // wait for our local version to be acknowledged by the remote peer
            // wait for remote peer to send their version
            await Task.WhenAll(verAckTask, versionTask);

            //TODO shouldn't have to decode again
            var versionMessage = versionTask.Result;
            var versionPayload = NetworkEncoder.DecodeVersionPayload(versionMessage.Payload.ToArray(), versionMessage.Payload.Length);

            var remoteAddressWithTime = new NetworkAddressWithTime
                                        (
                Time: DateTimeOffset.Now,
                NetworkAddress: new NetworkAddress
                (
                    Services: versionPayload.LocalAddress.Services,
                    IPv6Address: versionPayload.LocalAddress.IPv6Address,
                    Port: versionPayload.LocalAddress.Port
                )
                                        );

            // acknowledge their version
            await peer.Sender.SendVersionAcknowledge();
        }
        /// <inheritdoc/>
        public void OnPeerConnected(NetPeer peer)
        {
            if (MasterPeer != null)
            {
                activeConnections.Remove(peer.EndPoint);
                return;
            }
            if (!activeConnections.TryGetValue(peer.EndPoint, out masterPeer))
            {
                masterPeer = new LiteNetLibPeerManager(peer);
                activeConnections.Add(peer.EndPoint, MasterPeer);
            }

            Log.Info($"{GetType().Name} has connected to the master peer '{MasterPeer.PeerEndPoint}'.");
            PeerConnected?.Invoke(MasterPeer);
        }
        protected virtual void HandleConnect(int connectionID)
        {
            if (NetLogFilter.logDebug)
            {
                Debug.LogFormat("Connection ID: {0} Connected", connectionID);
            }

            var peer = new Peer(connectionID)
            {
                IsConnected = true
            };

            connectedPeers[peer.connectionID] = peer;

            PeerConnected?.Invoke(peer);
        }
Beispiel #6
0
        public async void Initialize()
        {
            if (Conntype == ConnectionType.Server)
            {
                tcpListener  = new TcpListener(iPAddress, Port);
                listenThread = new Thread(tcpListener.Start);
                listenThread.Start();
                Connect();
            }
            else
            {
                tcpClient = new TcpClient();
                await tcpClient.ConnectAsync(iPAddress, Port);

                PeerConnected?.Invoke(null, null);
            }
        }
Beispiel #7
0
        private void Connected(IPeer peer)
        {
            // Listen to messages
            peer.MessageReceived += OnMessageReceived;

            // Save the peer
            _connectedPeers[peer.Id] = peer;

            // Create the security extension
            var extension = peer.AddExtension(new PeerSecurityExtension());

            // Set default permission level
            extension.PermissionLevel = 0;

            _logger.Info($"New Peer connected. ID: {peer.Id}");
            // Invoke the event
            PeerConnected?.Invoke(peer);
        }
Beispiel #8
0
        /// <summary>
        /// Handles message if it contains heartbeat.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void HandleIfHeartbeat(Message msg)
        {
            var heartbeat = msg.Content as Heartbeat;

            if (heartbeat != null)
            {
                _peerHeartbeatDeadlines.AddOrUpdate(heartbeat.Identity,
                                                    identity =>
                {
                    var deadline = new Deadline(TimeSpan.FromMilliseconds(HeatbeatDeadline));

                    foreach (var handler in PeerConnected?.GetInvocationList().ToArray() ?? new Delegate[0])
                    {
                        ((Action <PeerIdentity>)handler)?.Invoke(heartbeat.Identity);
                    }

                    return(deadline);
                },
                                                    (identity, deadline) => new Deadline(TimeSpan.FromMilliseconds(HeatbeatDeadline)));
            }
        }
Beispiel #9
0
        public void PollEvents()
        {
            while (controller.TryReceiveEvent(out NetEvent evnt))
            {
                var peer = evnt.Peer;

                // No events should fire if the user closed the peer
                if (peer.ClosedByUser == false)
                {
                    switch (evnt.EventType)
                    {
                    case NetEventType.PeerConnected:
                        peer.SetCore(this);
                        peer.OnPeerConnected();
                        PeerConnected?.Invoke(peer, peer.Token);
                        break;

                    case NetEventType.PeerClosed:
                        peer.OnPeerClosed(evnt.CloseReason, evnt.UserKickReason, evnt.SocketError);
                        PeerClosed?.Invoke(peer, evnt.CloseReason, evnt.UserKickReason, evnt.SocketError);
                        break;

                    case NetEventType.Payload:
                        peer.OnPayloadReceived(evnt.EncodedData, evnt.EncodedLength);
                        PeerPayload?.Invoke(peer, evnt.EncodedData, evnt.EncodedLength);
                        break;

                    case NetEventType.Notification:
                        peer.OnNotificationReceived(evnt.EncodedData, evnt.EncodedLength);
                        PeerNotification?.Invoke(peer, evnt.EncodedData, evnt.EncodedLength);
                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }

                controller.RecycleEvent(evnt);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Adds the specified peer to the list of connected peer.
        /// </summary>
        /// <param name="event">The event.</param>
        private void AddConnectedPeer(PeerConnected @event)
        {
            IPEndPoint ipEndPoint = @event.PeerContext.RemoteEndPoint.EnsureIPv6();

            if (@event.PeerContext.Direction == PeerConnectionDirection.Outbound)
            {
                lock (_connectionLock)
                {
                    if (attemptingConnections.Remove(ipEndPoint))
                    {
                        _logger.LogDebug("EndPoint {RemoteEndPoint} Connected!. Removed from attemptingConnections list.", ipEndPoint);
                    }
                    else
                    {
                        _logger.LogDebug("EndPoint {RemoteEndPoint} Connected!. Not found in attemptingConnections list (shouldn't happen, need investigation)", ipEndPoint);
                    }
                }
            }

            ConcurrentDictionary <string, IPeerContext> container = @event.PeerContext.Direction == PeerConnectionDirection.Inbound ? inboundPeers : outboundPeers;

            container[@event.PeerContext.PeerId] = @event.PeerContext;
            _logger.LogDebug("Connected to {RemoteEndPoint}, peer {PeerId} added to the list of connected peers.", ipEndPoint, @event.PeerContext.PeerId);
        }
Beispiel #11
0
 internal void RaisePeerConnected(PeerConnectedEventArgs args)
 {
     PeerConnected?.InvokeAsync(this, args);
 }
 /// <summary>
 /// Adds the specified peer to the list of connected peer.
 /// </summary>
 /// <param name="event">The event.</param>
 private void AddConnectedPeer(PeerConnected @event)
 {
     _connectedPeers[@event.PeerContext.PeerId] = new PeerScore(@event.PeerContext, INITIAL_SCORE);
     _logger.LogDebug("Added peer {PeerId} to the list of PeerBehaviorManager connected peers", @event.PeerContext.PeerId);
 }
Beispiel #13
0
 protected void OnConnected(ConnectionEventArgs args)
 {
     PeerConnected?.Invoke(this, args);
 }
Beispiel #14
0
        internal void OnPeerConnected(PeerConnectedArgs e)
        {
            Logger.Debug($"[{nameof(IpcServerService)}] PeerConnected PeerName={e.PeerName} {e.Ack}");

            PeerConnected?.Invoke(this, e);
        }
Beispiel #15
0
 protected void OnPeerConnected(Peer peer)
 {
     PeerConnected?.Invoke(this, (peer));
 }
Beispiel #16
0
 internal void OnPeerConnected()
 {
     PeerConnected?.Invoke(this, token);
 }
        internal void OnPeerConnected(object?sender, IpcInternalPeerConnectedArgs e)
        {
            Logger.Debug($"[{nameof(IpcServerService)}] PeerConnected PeerName={e.PeerName} {e.Ack}");

            PeerConnected?.Invoke(sender, e);
        }