/// <summary>
        ///     Processes a GetNeighbourResponse item from stream.
        /// </summary>
        /// <param name="peerNeighborsRequest"></param>
        /// <param name="channelHandlerContext"></param>
        /// <param name="senderPeerId"></param>
        /// <param name="correlationId"></param>
        /// <returns></returns>
        protected override PeerNeighborsResponse HandleRequest(PeerNeighborsRequest peerNeighborsRequest,
                                                               IChannelHandlerContext channelHandlerContext,
                                                               PeerId senderPeerId,
                                                               ICorrelationId correlationId)
        {
            Guard.Argument(peerNeighborsRequest, nameof(peerNeighborsRequest)).NotNull();
            Guard.Argument(channelHandlerContext, nameof(channelHandlerContext)).NotNull();
            Guard.Argument(senderPeerId, nameof(senderPeerId)).NotNull();

            Logger.Debug("PeerNeighborsRequest Message Received");

            var activePeersList = _repository
                                  .FindAll(new Specification <Peer>(p => !p.IsAwolPeer))
                                  .Take(Constants.NumberOfRandomPeers) // 😂
                                  .ToList();

            Guard.Argument(activePeersList).MinCount(1);

            var peerNeighborsResponseMessage = new PeerNeighborsResponse();

            for (var i = 0; i < Constants.NumberOfRandomPeers; i++)
            {
                peerNeighborsResponseMessage.Peers.Add(activePeersList.RandomElement().PeerId);
            }

            return(peerNeighborsResponseMessage);
        }
Example #2
0
        /// <summary>
        /// Handle the request for GetPeerInfo
        /// </summary>
        /// <param name="getPeerInfoRequest">The request</param>
        /// <param name="channelHandlerContext">The channel handler context</param>
        /// <param name="senderPeerId">The sender peer identifier</param>
        /// <param name="correlationId">The correlationId</param>
        /// <returns>The GetPeerInfoResponse</returns>
        protected override GetPeerInfoResponse HandleRequest(GetPeerInfoRequest getPeerInfoRequest,
                                                             IChannelHandlerContext channelHandlerContext,
                                                             PeerId senderPeerId,
                                                             ICorrelationId correlationId)
        {
            Guard.Argument(getPeerInfoRequest, nameof(getPeerInfoRequest)).NotNull();
            Guard.Argument(channelHandlerContext, nameof(channelHandlerContext)).NotNull();
            Guard.Argument(senderPeerId, nameof(senderPeerId)).NotNull();
            Logger.Debug("received message of type GetPeerInfoRequest");

            var ip = getPeerInfoRequest.Ip;

            var peerInfo = _peerRepository.FindAll(m => m.PeerId.Ip == ip &&
                                                   m.PeerId.PublicKey == getPeerInfoRequest.PublicKey)
                           .Select(x =>
                                   new PeerInfo
            {
                PeerId        = x.PeerId,
                Reputation    = x.Reputation,
                IsBlacklisted = x.BlackListed,
                IsUnreachable = x.IsAwolPeer,
                InactiveFor   = x.InactiveFor.ToDuration(),
                LastSeen      = x.LastSeen.ToTimestamp(),
                Modified      = x.Modified?.ToTimestamp(),
                Created       = x.Created.ToTimestamp()
            }).ToList();

            var response = new GetPeerInfoResponse();

            response.PeerInfo.AddRange(peerInfo);
            return(response);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="removePeerRequest"></param>
        /// <param name="channelHandlerContext"></param>
        /// <param name="senderPeerId"></param>
        /// <param name="correlationId"></param>
        /// <returns></returns>
        protected override RemovePeerResponse HandleRequest(RemovePeerRequest removePeerRequest,
                                                            IChannelHandlerContext channelHandlerContext,
                                                            PeerId senderPeerId,
                                                            ICorrelationId correlationId)
        {
            Guard.Argument(removePeerRequest, nameof(removePeerRequest)).NotNull();
            Guard.Argument(channelHandlerContext, nameof(channelHandlerContext)).NotNull();
            Guard.Argument(senderPeerId, nameof(senderPeerId)).NotNull();
            Logger.Debug("Received message of type RemovePeerRequest");

            uint peerDeletedCount = 0;

            var publicKeyIsEmpty = removePeerRequest.PublicKey.IsEmpty;

            var peersToDelete = _peerRepository.FindAll(new Specification <Peer>(peer =>
                                                                                 peer.PeerId.Ip.SequenceEqual(removePeerRequest.PeerIp) &&
                                                                                 (publicKeyIsEmpty || peer.PeerId.PublicKey.SequenceEqual(removePeerRequest.PublicKey.ToByteArray())))).ToArray();

            foreach (var peerToDelete in peersToDelete)
            {
                _peerRepository.Delete(peerToDelete);
                peerDeletedCount += 1;
            }

            return(new RemovePeerResponse
            {
                DeletedCount = peerDeletedCount
            });
        }
        /// <summary>Executes the test case.</summary>
        /// <param name="fakePeers">The fake peers.</param>
        /// <param name="withPublicKey">if set to <c>true</c> [send message to handler with the public key].</param>
        private void ExecuteTestCase(IReadOnlyCollection <string> fakePeers, bool withPublicKey)
        {
            var             testScheduler      = new TestScheduler();
            IPeerRepository peerRepository     = Substitute.For <IPeerRepository>();
            Peer            targetPeerToDelete = null;
            var             fakePeerList       = fakePeers.ToList().Select(fakePeer =>
            {
                var peer = new Peer
                {
                    Reputation = 0,
                    LastSeen   = DateTime.Now.Subtract(TimeSpan.FromSeconds(fakePeers.ToList().IndexOf(fakePeer))),
                    PeerId     = PeerIdHelper.GetPeerId(fakePeer)
                };

                if (targetPeerToDelete == null)
                {
                    targetPeerToDelete = peer;
                }

                return(peer);
            }).ToList();

            peerRepository.FindAll(Arg.Any <ISpecification <Peer> >()).Returns(withPublicKey ? new List <Peer> {
                targetPeerToDelete
            } : fakePeerList);

            // Build a fake remote endpoint
            _fakeContext.Channel.RemoteAddress.Returns(EndpointBuilder.BuildNewEndPoint("192.0.0.1", 42042));

            var peerId = PeerIdHelper.GetPeerId("sender");

            var removePeerRequest = new RemovePeerRequest
            {
                PeerIp    = targetPeerToDelete.PeerId.Ip,
                PublicKey = withPublicKey ? targetPeerToDelete.PeerId.PublicKey : ByteString.Empty
            };

            var protocolMessage = removePeerRequest.ToProtocolMessage(peerId);

            var messageStream = MessageStreamHelper.CreateStreamWithMessage(_fakeContext, testScheduler, protocolMessage);

            var peerSettings = peerId.ToSubstitutedPeerSettings();
            var handler      = new RemovePeerRequestObserver(peerSettings, peerRepository, _logger);

            handler.StartObserving(messageStream);

            testScheduler.Start();

            var receivedCalls = _fakeContext.Channel.ReceivedCalls().ToList();

            receivedCalls.Count().Should().Be(1);

            var sentResponseDto = (IMessageDto <ProtocolMessage>)receivedCalls[0].GetArguments().Single();

            var signResponseMessage = sentResponseDto.Content.FromProtocolMessage <RemovePeerResponse>();

            signResponseMessage.DeletedCount.Should().Be(withPublicKey ? 1 : (uint)fakePeers.Count);
        }
Example #5
0
        public GetPeerInfoRequestObserverTests()
        {
            _logger      = Substitute.For <ILogger>();
            _fakeContext = Substitute.For <IChannelHandlerContext>();

            var fakeChannel = Substitute.For <IChannel>();

            _fakeContext.Channel.Returns(fakeChannel);

            var peers = GetPeerTestData();

            _peerRepository = Substitute.For <IPeerRepository>();
            _peerRepository.FindAll(Arg.Any <Expression <Func <Peer, bool> > >())
            .Returns(ci => { return(peers.Where(p => ((Expression <Func <Peer, bool> >)ci[0]).Compile()(p))); });
        }
 private static void AddMockPeerToDbAndSetReturnExpectation(IReadOnlyList <Peer> peer,
                                                            IPeerRepository store)
 {
     store.Add(peer);
     store.FindAll(Arg.Any <Specification <Peer> >()).Returns(peer);
 }