Exemple #1
0
        public void PeerFile_CanSaveAndLoadPeers_PeerConnected()
        {
            var ipAddress      = IPAddress.Parse("::ffff:192.168.0.1");
            var networkAddress = new NetworkAddress(ipAddress, 80);

            var peerFolder     = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));
            var addressManager = new PeerAddressManager(peerFolder, this.loggerFactory);

            addressManager.AddPeer(networkAddress, IPAddress.Loopback);

            var applicableDate = DateTime.UtcNow.Date;

            addressManager.PeerAttempted(networkAddress.Endpoint, applicableDate);
            addressManager.PeerConnected(networkAddress.Endpoint, applicableDate);

            addressManager.SavePeers();
            addressManager.LoadPeers();

            var savedPeer = addressManager.FindPeer(networkAddress.Endpoint);

            Assert.Equal("::ffff:192.168.0.1", savedPeer.EndPoint.Address.ToString());
            Assert.Equal(80, savedPeer.EndPoint.Port);
            Assert.Equal(0, savedPeer.ConnectionAttempts);
            Assert.Equal(applicableDate, savedPeer.LastConnectionSuccess.Value.Date);
            Assert.Null(savedPeer.LastConnectionHandshake);
            Assert.Equal("127.0.0.1", savedPeer.Loopback.ToString());
        }
        public void PeerState_TestReturnFromPeerAttemptedSet_IgnoringBannedPeer()
        {
            var ipAddress   = IPAddress.Parse("::ffff:192.168.0.1");
            var endPointOne = new IPEndPoint(ipAddress, 80);

            ipAddress = IPAddress.Parse("::ffff:192.168.0.2");
            var endPointTwo = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory, new SelfEndpointTracker());

            peerAddressManager.AddPeer(endPointOne, IPAddress.Loopback);
            peerAddressManager.AddPeer(endPointTwo, IPAddress.Loopback);

            peerAddressManager.FindPeer(endPointTwo).BanUntil = DateTime.UtcNow.AddMinutes(1);

            peerAddressManager.PeerAttempted(endPointOne, DateTime.UtcNow.AddHours(-2));
            peerAddressManager.PeerAttempted(endPointTwo, DateTime.UtcNow.AddHours(-2));

            IEnumerable <PeerAddress> peers = peerAddressManager.PeerSelector.Attempted();

            Assert.Single(peers);
            Assert.Contains(peers, p => p.Endpoint.Match(endPointOne));
        }
        public void PeerSelector_ReturnPeersForDiscovery_IgnoringBannedPeer()
        {
            string discoveredpeer = "::ffff:192.168.0.2";

            IPAddress ipAddress   = IPAddress.Parse("::ffff:192.168.0.1");
            var       endPointOne = new IPEndPoint(ipAddress, 80);

            ipAddress = IPAddress.Parse(discoveredpeer);
            var endPointTwo = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = CreateDataFolder(this);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory, new SelfEndpointTracker());

            peerAddressManager.AddPeer(endPointOne, IPAddress.Loopback);
            peerAddressManager.AddPeer(endPointTwo, IPAddress.Loopback);

            // Discovered peer.
            ipAddress = IPAddress.Parse(discoveredpeer);
            peerAddressManager.PeerDiscoveredFrom(new IPEndPoint(ipAddress, 80), DateTime.UtcNow.AddHours(-25));

            // Banned peer.
            peerAddressManager.FindPeer(endPointOne).BanUntil = DateTime.UtcNow.AddMinutes(1);

            IEnumerable <PeerAddress> peers = peerAddressManager.PeerSelector.SelectPeersForDiscovery(2);

            Assert.Single(peers);
            Assert.Contains(peers, p => p.Endpoint.Match(endPointTwo));
        }
        public void PeerState_TestReturnFromPeerHandshakedSet_IgnoringBanned()
        {
            IPAddress ipAddress   = IPAddress.Parse("::ffff:192.168.0.1");
            var       endPointOne = new IPEndPoint(ipAddress, 80);

            ipAddress = IPAddress.Parse("::ffff:192.168.0.2");
            var endPointTwo = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = CreateDataFolder(this);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory, new SelfEndpointTracker());

            peerAddressManager.AddPeer(endPointOne, IPAddress.Loopback);
            peerAddressManager.AddPeer(endPointTwo, IPAddress.Loopback);

            peerAddressManager.FindPeer(endPointTwo).BanUntil = DateTime.UtcNow.AddMinutes(1);

            peerAddressManager.PeerConnected(endPointOne, DateTime.UtcNow.AddSeconds(-80));
            peerAddressManager.PeerHandshaked(endPointOne, DateTime.UtcNow.AddSeconds(-80));

            peerAddressManager.PeerConnected(endPointTwo, DateTime.UtcNow.AddSeconds(-80));
            peerAddressManager.PeerHandshaked(endPointTwo, DateTime.UtcNow.AddSeconds(-80));

            IEnumerable <PeerAddress> peers = peerAddressManager.PeerSelector.Handshaked();

            Assert.Single(peers);
            Assert.Contains(peers, p => p.Endpoint.Match(endPointOne));
        }
        public void PeerAddressManagerBehaviour_ReceivedPong_UpdateLastSeen()
        {
            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerFolder     = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManagerBehaviourTests"));
            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.loggerFactory);

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var networkPeer = new NetworkPeer(endpoint, this.network, new NetworkPeerConnectionParameters(), this.networkPeerFactory, DateTimeProvider.Default, this.extendedLoggerFactory);

            networkPeer.SetStateAsync(NetworkPeerState.HandShaked).GetAwaiter().GetResult();

            var behaviour = new PeerAddressManagerBehaviour(DateTimeProvider.Default, addressManager)
            {
                Mode = PeerAddressManagerBehaviourMode.AdvertiseDiscover
            };

            behaviour.Attach(networkPeer);

            var message = new IncomingMessage(new PongPayload(), this.network);

            //Trigger the event handler
            networkPeer.MessageReceived.ExecuteCallbacksAsync(networkPeer, message).GetAwaiter().GetResult();

            var peer = addressManager.FindPeer(endpoint);

            Assert.Equal(DateTimeProvider.Default.GetUtcNow().Date, peer.LastSeen.Value.Date);
        }
Exemple #6
0
        public void PeerFile_CanSaveAndLoadPeers_PeerConnected()
        {
            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerFolder     = CreateDataFolder(this);
            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker());

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var applicableDate = DateTime.UtcNow.Date;

            addressManager.PeerAttempted(endpoint, applicableDate);
            addressManager.PeerConnected(endpoint, applicableDate);

            addressManager.SavePeers();
            addressManager.LoadPeers();

            var savedPeer = addressManager.FindPeer(endpoint);

            Assert.Equal("::ffff:192.168.0.1", savedPeer.Endpoint.Address.ToString());
            Assert.Equal(80, savedPeer.Endpoint.Port);
            Assert.Equal(0, savedPeer.ConnectionAttempts);
            Assert.Equal(applicableDate, savedPeer.LastConnectionSuccess.Value.Date);
            Assert.Null(savedPeer.LastConnectionHandshake);
            Assert.Equal("127.0.0.1", savedPeer.Loopback.ToString());
        }
        public void PeerAddressManager_AttemptThresholdTimeNotReached_DoNotReset()
        {
            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.loggerFactory, new SelfEndpointTracker());

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var applicableDate = DateTimeProvider.Default.GetUtcNow();

            //Ensure that there was 10 failed attempts
            for (int i = 0; i < 10; i++)
            {
                addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-i));
            }

            //Capture the last attempt timestamp
            var lastAttempt = DateTimeProvider.Default.GetUtcNow();

            addressManager.PeerAttempted(endpoint, lastAttempt);

            var savedPeer = addressManager.FindPeer(endpoint);

            Assert.Equal(11, savedPeer.ConnectionAttempts);
            Assert.Equal(lastAttempt, savedPeer.LastAttempt);
            Assert.Null(savedPeer.LastConnectionSuccess);
            Assert.Null(savedPeer.LastConnectionHandshake);
            Assert.Null(savedPeer.LastSeen);
            Assert.Equal("127.0.0.1", savedPeer.Loopback.ToString());
        }
Exemple #8
0
        public void PeerAddressManager_AttemptThresholdTimeNotReached_DoNotReset()
        {
            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = CreateDataFolder(this);

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker(this.LoggerFactory.Object, this.connectionManagerSettings));

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            DateTime applicableDate = DateTimeProvider.Default.GetUtcNow();

            //Ensure that there was 4 failed attempts
            for (int i = 0; i < 4; i++)
            {
                addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-i));
            }

            //Capture the last attempt timestamp
            DateTime lastAttempt = DateTimeProvider.Default.GetUtcNow();

            addressManager.PeerAttempted(endpoint, lastAttempt);

            PeerAddress savedPeer = addressManager.FindPeer(endpoint);

            Assert.Equal(5, savedPeer.ConnectionAttempts);
            Assert.Equal(lastAttempt, savedPeer.LastAttempt);
            Assert.Null(savedPeer.LastConnectionSuccess);
            Assert.Null(savedPeer.LastConnectionHandshake);
            Assert.Null(savedPeer.LastSeen);
            Assert.Equal("::ffff:127.0.0.1", savedPeer.Loopback.ToString());
        }
        public void PeerFile_CanSaveAndLoadPeers_PeerSeen()
        {
            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.loggerFactory, new SelfEndpointTracker());

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var applicableDate = DateTime.UtcNow.Date;

            addressManager.PeerAttempted(endpoint, applicableDate);
            addressManager.PeerConnected(endpoint, applicableDate);
            addressManager.PeerHandshaked(endpoint, applicableDate);
            addressManager.PeerSeen(endpoint, applicableDate);

            addressManager.SavePeers();
            addressManager.LoadPeers();

            var savedPeer = addressManager.FindPeer(endpoint);

            Assert.Equal("::ffff:192.168.0.1", savedPeer.Endpoint.Address.ToString());
            Assert.Equal(80, savedPeer.Endpoint.Port);
            Assert.Equal(0, savedPeer.ConnectionAttempts);
            Assert.Equal(applicableDate, savedPeer.LastConnectionSuccess.Value.Date);
            Assert.Equal(applicableDate, savedPeer.LastConnectionHandshake.Value.Date);
            Assert.Equal(applicableDate, savedPeer.LastSeen.Value.Date);
            Assert.Equal("127.0.0.1", savedPeer.Loopback.ToString());
        }
Exemple #10
0
        public void PeerFile_CanSaveAndLoadPeers_ResetBannedPeers()
        {
            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = CreateDataFolder(this);

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker(this.LoggerFactory.Object, this.connectionManagerSettings));
            var addedPeer      = addressManager.AddPeer(endpoint, IPAddress.Loopback);

            addedPeer.BanReason    = "test";
            addedPeer.BanScore     = 0;
            addedPeer.BanTimeStamp = DateTime.UtcNow.AddHours(-2);
            addedPeer.BanUntil     = DateTime.UtcNow.AddHours(-1);

            addressManager.SavePeers();

            addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker(this.LoggerFactory.Object, this.connectionManagerSettings));
            addressManager.LoadPeers();

            PeerAddress savedPeer = addressManager.FindPeer(endpoint);

            Assert.Null(savedPeer.BanReason);
            Assert.Null(savedPeer.BanScore);
            Assert.Null(savedPeer.BanTimeStamp);
            Assert.Null(savedPeer.BanUntil);
        }
        public void PeerBanning_Add_Peer_To_Address_Manager_And_Ban()
        {
            var dataFolder = CreateDataFolder(this);

            var loggerFactory = ExtendedLoggerFactory.Create();

            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint, endpoint.Address.MapToIPv6());

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint, connectionManagerSettings.BanTimeSeconds, nameof(PeerBanningTest));

            PeerAddress peer = peerAddressManager.FindPeer(endpoint);

            Assert.True(peer.BanUntil.HasValue);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);
        }
Exemple #12
0
        public void CanSaveAndLoadPeerAddressFile_PeerHandshaked()
        {
            var ipAddress      = IPAddress.Parse("::ffff:192.168.0.1");
            var networkAddress = new NetworkAddress(ipAddress, 80);

            var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));

            var addressManager = new PeerAddressManager(peerFolder);

            addressManager.AddPeer(networkAddress, IPAddress.Loopback, PeerIntroductionType.Add);

            addressManager.PeerAttempted(networkAddress.Endpoint, DateTimeOffset.Now);
            addressManager.PeerConnected(networkAddress.Endpoint, DateTimeOffset.Now);
            addressManager.PeerHandshaked(networkAddress.Endpoint, DateTimeOffset.Now);

            addressManager.SavePeers();
            addressManager.LoadPeers();

            var savedPeer = addressManager.FindPeer(networkAddress.Endpoint);

            Assert.Equal("::ffff:192.168.0.1", savedPeer.NetworkAddress.Endpoint.Address.ToString());
            Assert.Equal(DateTimeOffset.Now.Date, savedPeer.NetworkAddress.Time.Date);
            Assert.Equal(80, savedPeer.NetworkAddress.Endpoint.Port);
            Assert.Equal(0, savedPeer.ConnectionAttempts);
            Assert.Equal(DateTime.Today.Date, savedPeer.LastConnectionSuccess.Value.Date);
            Assert.Equal(DateTime.Today.Date, savedPeer.LastConnectionHandshake.Value.Date);
            Assert.Equal("127.0.0.1", savedPeer.Loopback.ToString());
        }
        public void PeerBanning_Add_Peers_To_Address_Manager_And_Ban_IP_Range()
        {
            var dataFolder = CreateDataFolder(this);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            var ipAddress80 = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint80  = new IPEndPoint(ipAddress80, 80);

            var ipAddress81 = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint81  = new IPEndPoint(ipAddress81, 81);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint80, IPAddress.Loopback);
            peerAddressManager.AddPeer(endpoint81, IPAddress.Loopback);

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint80, connectionManagerSettings.BanTimeSeconds, nameof(PeerBanningTest));

            // Both endpoints should be banned.
            PeerAddress peer = peerAddressManager.FindPeer(endpoint80);

            Assert.True(peer.BanUntil.HasValue);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);

            peer = peerAddressManager.FindPeer(endpoint81);
            Assert.True(peer.BanUntil.HasValue);
            Assert.NotNull(peer.BanUntil);
            Assert.NotEmpty(peer.BanReason);
        }
        public void PeerBanning_Add_WhiteListed_Peer_Does_Not_Get_Banned()
        {
            var dataFolder = CreateDataFolder(this);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint, endpoint.Address.MapToIPv6());

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var connectionManagerBehaviour = new Mock <IConnectionManagerBehavior>();

            connectionManagerBehaviour.Setup(c => c.Whitelisted).Returns(true);

            var networkPeer = new Mock <INetworkPeer>();

            networkPeer.Setup(n => n.PeerEndPoint).Returns(endpoint);
            networkPeer.Setup(n => n.Behavior <IConnectionManagerBehavior>()).Returns(connectionManagerBehaviour.Object);

            var networkPeerFactory = new Mock <INetworkPeerFactory>();

            networkPeerFactory.Setup(n => n.CreateConnectedNetworkPeerAsync(endpoint, null, null)).ReturnsAsync(networkPeer.Object);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>()
            {
                networkPeer.Object
            });

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint, connectionManagerSettings.BanTimeSeconds, nameof(PeerBanningTest));

            // Peer is whitelised and will not be banned.
            PeerAddress peer = peerAddressManager.FindPeer(endpoint);

            Assert.False(peer.BanUntil.HasValue);
            Assert.Null(peer.BanUntil);
            Assert.Null(peer.BanReason);
        }
        public void PeerAddressManagerBehaviour_ReceivedPong_UpdateLastSeen()
        {
            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder     = CreateDataFolder(this);
            var        addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object,
                                                               new SelfEndpointTracker(this.extendedLoggerFactory, this.connectionManagerSettings));

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var networkPeer = new Mock <INetworkPeer>();

            networkPeer.SetupGet(n => n.PeerEndPoint).Returns(endpoint);
            networkPeer.SetupGet(n => n.State).Returns(NetworkPeerState.HandShaked);

            var messageReceived = new AsyncExecutionEvent <INetworkPeer, IncomingMessage>();

            networkPeer.SetupGet(n => n.MessageReceived).Returns(messageReceived);

            var stateChanged = new AsyncExecutionEvent <INetworkPeer, NetworkPeerState>();

            networkPeer.SetupGet(n => n.StateChanged).Returns(stateChanged);

            var behaviour = new PeerAddressManagerBehaviour(DateTimeProvider.Default, addressManager, new Mock <IPeerBanning>().Object, this.extendedLoggerFactory)
            {
                Mode = PeerAddressManagerBehaviourMode.AdvertiseDiscover
            };

            behaviour.Attach(networkPeer.Object);

            var incomingMessage = new IncomingMessage();

            incomingMessage.Message = new Message(new PayloadProvider().DiscoverPayloads())
            {
                Magic   = this.Network.Magic,
                Payload = new PingPayload(),
            };

            //Trigger the event handler
            networkPeer.Object.MessageReceived.ExecuteCallbacksAsync(networkPeer.Object, incomingMessage).GetAwaiter().GetResult();

            PeerAddress peer = addressManager.FindPeer(endpoint);

            Assert.Equal(DateTimeProvider.Default.GetUtcNow().Date, peer.LastSeen.Value.Date);
        }
        public void PeerAddressManagerBehaviour_InboundConnectionIsNotLoopBack_Add_AddressFrom_ToAddressBook()
        {
            IPAddress addressFromIPAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       addressFromEndpoint  = new IPEndPoint(addressFromIPAddress, this.Network.DefaultPort);

            IPAddress peerEndPointAddress = IPAddress.Parse("::ffff:192.168.0.2");
            var       peerEndPoint        = new IPEndPoint(peerEndPointAddress, 80);

            DataFolder peerFolder     = CreateDataFolder(this);
            var        addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object,
                                                               new SelfEndpointTracker(this.extendedLoggerFactory, this.connectionManagerSettings));

            var networkPeer = new Mock <INetworkPeer>();

            networkPeer.SetupGet(n => n.Inbound).Returns(true);
            networkPeer.SetupGet(n => n.Network).Returns(this.Network);
            networkPeer.SetupGet(n => n.PeerEndPoint).Returns(peerEndPoint);
            networkPeer.SetupGet(n => n.PeerVersion).Returns(new VersionPayload()
            {
                AddressFrom = addressFromEndpoint
            });
            networkPeer.SetupGet(n => n.State).Returns(NetworkPeerState.HandShaked);

            var messageReceived = new AsyncExecutionEvent <INetworkPeer, IncomingMessage>();

            networkPeer.SetupGet(n => n.MessageReceived).Returns(messageReceived);

            var stateChanged = new AsyncExecutionEvent <INetworkPeer, NetworkPeerState>();

            networkPeer.SetupGet(n => n.StateChanged).Returns(stateChanged);

            var behaviour = new PeerAddressManagerBehaviour(DateTimeProvider.Default, addressManager, new Mock <IPeerBanning>().Object, this.extendedLoggerFactory)
            {
                Mode = PeerAddressManagerBehaviourMode.AdvertiseDiscover
            };

            behaviour.Attach(networkPeer.Object);

            // Trigger the event handler that signals that the peer has handshaked.
            networkPeer.Object.StateChanged.ExecuteCallbacksAsync(networkPeer.Object, NetworkPeerState.HandShaked).GetAwaiter().GetResult();

            // The address manager should contain the inbound peer's address.
            var endpointToFind = new IPEndPoint(addressFromEndpoint.Address, this.Network.DefaultPort);

            Assert.NotNull(addressManager.FindPeer(endpointToFind));
        }
Exemple #17
0
        public void PeerAddressManagerBehaviour_ReceivedPong_UpdateLastSeen()
        {
            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerFolder     = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManagerBehaviourTests"));
            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.loggerFactory);

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var networkPeer = new Mock <INetworkPeer>();

            networkPeer.SetupGet(n => n.PeerEndPoint).Returns(endpoint);
            networkPeer.SetupGet(n => n.State).Returns(NetworkPeerState.HandShaked);

            var messageReceived = new AsyncExecutionEvent <INetworkPeer, IncomingMessage>();

            networkPeer.SetupGet(n => n.MessageReceived).Returns(messageReceived);

            var stateChanged = new AsyncExecutionEvent <INetworkPeer, NetworkPeerState>();

            networkPeer.SetupGet(n => n.StateChanged).Returns(stateChanged);

            var behaviour = new PeerAddressManagerBehaviour(DateTimeProvider.Default, addressManager)
            {
                Mode = PeerAddressManagerBehaviourMode.AdvertiseDiscover
            };

            behaviour.Attach(networkPeer.Object);

            var incomingMessage = new IncomingMessage();

            incomingMessage.Message = new Message(new PayloadProvider().DiscoverPayloads())
            {
                Magic   = this.network.Magic,
                Payload = new PingPayload(),
            };

            //Trigger the event handler
            networkPeer.Object.MessageReceived.ExecuteCallbacksAsync(networkPeer.Object, incomingMessage).GetAwaiter().GetResult();

            var peer = addressManager.FindPeer(endpoint);

            Assert.Equal(DateTimeProvider.Default.GetUtcNow().Date, peer.LastSeen.Value.Date);
        }
        public void PeerBanning_Resetting_Expired_BannedPeer()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            var peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);

            peerAddressManager.AddPeer(endpoint, IPAddress.Loopback);

            var nodeSettings = new NodeSettings(new StratisRegTest());
            var connectionManagerSettings = new ConnectionManagerSettings(nodeSettings);

            var peerCollection = new Mock <IReadOnlyNetworkPeerCollection>();

            peerCollection.Setup(p => p.FindByIp(It.IsAny <IPAddress>())).Returns(new List <INetworkPeer>());

            var connectionManager = new Mock <IConnectionManager>();

            connectionManager.Setup(c => c.ConnectionSettings).Returns(connectionManagerSettings);
            connectionManager.Setup(c => c.ConnectedPeers).Returns(peerCollection.Object);

            var peerBanning = new PeerBanning(connectionManager.Object, loggerFactory, DateTimeProvider.Default, peerAddressManager);

            peerBanning.BanAndDisconnectPeer(endpoint, 1, nameof(PeerBanningTest));

            peerAddressManager.SavePeers();

            // Wait one second for ban to expire.
            Thread.Sleep(1000);

            peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, dataFolder, loggerFactory, new Mock <ISelfEndpointTracker>().Object);
            peerAddressManager.LoadPeers();

            PeerAddress peer = peerAddressManager.FindPeer(endpoint);

            Assert.Null(peer.BanTimeStamp);
            Assert.Null(peer.BanUntil);
            Assert.Empty(peer.BanReason);
        }
Exemple #19
0
        public void PeerSelectability_Decreases_AfterEachFailedAttempt()
        {
            var ipAddress  = IPAddress.Parse("::ffff:192.168.0.1");
            var addressOne = new NetworkAddress(ipAddress, 80);

            var peerFolder     = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));
            var addressManager = new PeerAddressManager(peerFolder);

            addressManager.AddPeer(addressOne, IPAddress.Loopback, PeerIntroductionType.Add);

            var peer = addressManager.FindPeer(addressOne.Endpoint);

            peer.Attempted(DateTimeOffset.Now);
            var resultOne = peer.Selectability;

            peer.Attempted(DateTimeOffset.Now);
            var resultTwo = peer.Selectability;

            Assert.True(resultOne > resultTwo);
        }
Exemple #20
0
        public void PeerFile_CanSaveAndLoadPeers_ResetAttemptThresholdReachedPeers()
        {
            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = CreateDataFolder(this);

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker(this.LoggerFactory.Object, this.connectionManagerSettings));

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            DateTime applicableDate = DateTimeProvider.Default.GetUtcNow();

            // Set the peer's failed attempts count to 4.
            for (int i = 0; i < 4; i++)
            {
                addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-i));
            }

            // Ensure that the last attempt (5) was more than 12 hours ago.
            addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-13));

            // Ensure that the peer is still returned from the selector.
            var peer = addressManager.PeerSelector.SelectPeer();

            Assert.Equal(peer.Endpoint, endpoint);

            // Persist the peers to the json file.
            addressManager.SavePeers();

            // Creat a new address manager instance and load the peers from file.
            addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker(this.LoggerFactory.Object, this.connectionManagerSettings));
            addressManager.LoadPeers();

            PeerAddress savedPeer = addressManager.FindPeer(endpoint);

            // The peer's attempt thresholds should now be reset.
            Assert.False(savedPeer.Attempted);
            Assert.Equal(0, savedPeer.ConnectionAttempts);
            Assert.Null(savedPeer.LastAttempt);
        }
Exemple #21
0
        public void PeerAddressManager_AttemptThresholdReached_ResetAttempts()
        {
            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var       endpoint  = new IPEndPoint(ipAddress, 80);

            DataFolder peerFolder = CreateDataFolder(this);

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.LoggerFactory.Object, new SelfEndpointTracker(this.LoggerFactory.Object, this.connectionManagerSettings));

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            DateTime applicableDate = DateTimeProvider.Default.GetUtcNow();

            // Set the peer's failed attempts count to 4.
            for (int i = 0; i < 4; i++)
            {
                addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-i));
            }

            // Ensure that the last attempt (5) was more than 12 hours ago.
            addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-13));

            // Ensure that the peer is still returned from the selector.
            var peer = addressManager.PeerSelector.SelectPeer();

            Assert.Equal(peer.Endpoint, endpoint);

            // This call should now reset the counts
            DateTime resetTimestamp = DateTimeProvider.Default.GetUtcNow();

            addressManager.PeerAttempted(endpoint, resetTimestamp);

            PeerAddress savedPeer = addressManager.FindPeer(endpoint);

            Assert.Equal(1, savedPeer.ConnectionAttempts);
            Assert.Equal(resetTimestamp, savedPeer.LastAttempt);
            Assert.Null(savedPeer.LastConnectionSuccess);
            Assert.Null(savedPeer.LastConnectionHandshake);
            Assert.Null(savedPeer.LastSeen);
            Assert.Equal("::ffff:127.0.0.1", savedPeer.Loopback.ToString());
        }
Exemple #22
0
        public void PeerState_AllConnectionDataGetsReset()
        {
            IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint = new IPEndPoint(ipAddress, 80);

            PeerAddressManager peerAddressManager = this.CreatePeerAddressManager();
            peerAddressManager.AddPeer(endpoint, IPAddress.Loopback);

            peerAddressManager.PeerConnected(endpoint, DateTime.UtcNow);

            peerAddressManager.PeerAttempted(endpoint, DateTime.UtcNow);
            peerAddressManager.PeerAttempted(endpoint, DateTime.UtcNow);
            peerAddressManager.PeerAttempted(endpoint, DateTime.UtcNow);

            peerAddressManager.PeerConnected(endpoint, DateTime.UtcNow);

            PeerAddress peerOne = peerAddressManager.FindPeer(endpoint);

            Assert.Equal(0, peerOne.ConnectionAttempts);
            Assert.Null(peerOne.LastAttempt);
            Assert.NotNull(peerOne.LastConnectionSuccess);
        }
        public void PeerAddressManager_AttemptThresholdReached_ResetAttempts()
        {
            var ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
            var endpoint  = new IPEndPoint(ipAddress, 80);

            var peerFolder = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));

            var addressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.loggerFactory);

            addressManager.AddPeer(endpoint, IPAddress.Loopback);

            var applicableDate = DateTimeProvider.Default.GetUtcNow();

            //Ensure that there was 10 failed attempts
            for (int i = 0; i < 10; i++)
            {
                addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-i));
            }

            //Ensure that the last attempt was more than 12 hours ago
            addressManager.PeerAttempted(endpoint, applicableDate.AddHours(-13));

            //This call should now reset the counts
            var resetTimestamp = DateTimeProvider.Default.GetUtcNow();

            addressManager.PeerAttempted(endpoint, resetTimestamp);

            var savedPeer = addressManager.FindPeer(endpoint);

            Assert.Equal(1, savedPeer.ConnectionAttempts);
            Assert.Equal(resetTimestamp, savedPeer.LastAttempt);
            Assert.Null(savedPeer.LastConnectionSuccess);
            Assert.Null(savedPeer.LastConnectionHandshake);
            Assert.Null(savedPeer.LastSeen);
            Assert.Equal("127.0.0.1", savedPeer.Loopback.ToString());
        }
        public void PeerState_AllConnectionDataGetsReset()
        {
            var ipAddress      = IPAddress.Parse("::ffff:192.168.0.1");
            var networkAddress = new NetworkAddress(ipAddress, 80);

            var peerFolder     = AssureEmptyDirAsDataFolder(Path.Combine(AppContext.BaseDirectory, "PeerAddressManager"));
            var addressManager = new PeerAddressManager(peerFolder, this.extendedLoggerFactory);

            addressManager.AddPeer(networkAddress, IPAddress.Loopback);

            addressManager.PeerConnected(networkAddress.Endpoint, DateTime.UtcNow);

            addressManager.PeerAttempted(networkAddress.Endpoint, DateTime.UtcNow);
            addressManager.PeerAttempted(networkAddress.Endpoint, DateTime.UtcNow);
            addressManager.PeerAttempted(networkAddress.Endpoint, DateTime.UtcNow);

            addressManager.PeerConnected(networkAddress.Endpoint, DateTime.UtcNow);

            var peerOne = addressManager.FindPeer(networkAddress.Endpoint);

            Assert.Equal(0, peerOne.ConnectionAttempts);
            Assert.Null(peerOne.LastConnectionAttempt);
            Assert.NotNull(peerOne.LastConnectionSuccess);
        }