Exemplo n.º 1
0
        public async Task BroadcastTx_FromStream_Test()
        {
            var received = new List <TransactionsReceivedEvent>();

            _eventBus.Subscribe <TransactionsReceivedEvent>(t =>
            {
                received.Add(t);
                return(Task.CompletedTask);
            });

            var      pubKey   = "SomePubKey";
            Metadata metadata = new Metadata {
                { GrpcConstants.PubkeyMetadataKey, pubKey }
            };
            var context = BuildServerCallContext(metadata);

            _peerPool.TryAddPeer(GrpcTestPeerHelpers.CreateBasicPeer("127.0.0.1:500", context.GetPublicKey()));
            var transactions = await _osTestHelper.GenerateTransferTransactions(3);

            var requestStream = new TestAsyncStreamReader <Transaction>(transactions.ToArray());

            var result = await _serverService.TransactionBroadcastStream(requestStream, context);

            result.ShouldBe(new VoidReply());

            received.Count.ShouldBe(3);
        }
Exemplo n.º 2
0
        private TaskCompletionSource <VoidReply> _testCompletionSource; // completion for all

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var mockClient = new Mock <PeerService.PeerServiceClient>();

            _testCompletionSource = new TaskCompletionSource <VoidReply>();

            // setup mock announcement stream
            var announcementStreamCall = MockStreamCall <BlockAnnouncement, VoidReply>(_testCompletionSource.Task);

            mockClient.Setup(m => m.AnnouncementBroadcastStream(null, null, CancellationToken.None))
            .Returns(announcementStreamCall);

            // setup mock transaction stream
            var transactionStreamCall = MockStreamCall <Transaction, VoidReply>(_testCompletionSource.Task);

            mockClient.Setup(m => m.TransactionBroadcastStream(null, null, CancellationToken.None))
            .Returns(transactionStreamCall);

            // setup mock block stream
            var blockStreamCall = MockStreamCall <BlockWithTransactions, VoidReply>(_testCompletionSource.Task);

            mockClient.Setup(m => m.BlockBroadcastStream(null, null, CancellationToken.None))
            .Returns(blockStreamCall);

            // create peer
            _peerUnderTest = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.FakeIpEndpoint,
                                                                      NetworkTestConstants.FakePubkey, mockClient.Object);

            _peerUnderTest.IsConnected = true;

            context.Services.AddSingleton <IPeer>(_peerUnderTest);
        }
Exemplo n.º 3
0
        public async Task SendTx_ShouldPublishEvent_Test()
        {
            TransactionsReceivedEvent received = null;

            _eventBus.Subscribe <TransactionsReceivedEvent>(t =>
            {
                received = t;
                return(Task.CompletedTask);
            });

            var tx = new Transaction
            {
                From           = SampleAddress.AddressList[0],
                To             = SampleAddress.AddressList[1],
                RefBlockNumber = 1,
                MethodName     = "Hello"
            };

            var      pubKey   = "SomePubKey";
            Metadata metadata = new Metadata {
                { GrpcConstants.PubkeyMetadataKey, pubKey }
            };
            var reqBlockCtxt = BuildServerCallContext(metadata);

            _peerPool.TryAddPeer(GrpcTestPeerHelpers.CreateBasicPeer("127.0.0.1:1245", pubKey));

            await _serverService.SendTransaction(tx, reqBlockCtxt);

            received.Transactions.ShouldNotBeNull();
            received.Transactions.Count().ShouldBe(1);
            received.Transactions.First().From.ShouldBe(tx.From);
        }
Exemplo n.º 4
0
        private GrpcPeer MockServiceClient(string ipAddress)
        {
            var mockClient = new Mock<PeerService.PeerServiceClient>();
            var testCompletionSource = Task.FromResult(new VoidReply());

            // setup mock announcement stream
            var announcementStreamCall = MockStreamCall<BlockAnnouncement, VoidReply>(testCompletionSource);
            mockClient.Setup(m => m.AnnouncementBroadcastStream(It.IsAny<Metadata>(), null, CancellationToken.None))
                .Returns(announcementStreamCall);
            
            // setup mock transaction stream
            var transactionStreamCall = MockStreamCall<Transaction, VoidReply>(testCompletionSource);
            mockClient.Setup(m => m.TransactionBroadcastStream(It.IsAny<Metadata>(), null, CancellationToken.None))
                .Returns(transactionStreamCall);
            
            // setup mock block stream
            var blockStreamCall = MockStreamCall<BlockWithTransactions, VoidReply>(testCompletionSource);
            mockClient.Setup(m => m.BlockBroadcastStream(It.IsAny<Metadata>(), null, CancellationToken.None))
                .Returns(blockStreamCall);
            
            // create peer
            var grpcPeer = GrpcTestPeerHelpers.CreatePeerWithClient(ipAddress, 
                NetworkTestConstants.FakePubkey, mockClient.Object);
            
            grpcPeer.IsConnected = true;

            return grpcPeer;
        }
Exemplo n.º 5
0
        private GrpcPeer AddPeerToPool(string ip     = NetworkTestConstants.FakeIpEndpoint,
                                       string pubkey = NetworkTestConstants.FakePubkey)
        {
            var  peer  = GrpcTestPeerHelpers.CreateBasicPeer(ip, pubkey);
            bool added = _peerPool.TryAddPeer(peer);

            Assert.True(added);

            return(peer);
        }
Exemplo n.º 6
0
        public async Task RequestBlockAsync_Failed()
        {
            _grpcPeer = GrpcTestPeerHelpers.CreateNewPeer("127.0.0.1:3000", false);
            _pool.TryAddPeer(_grpcPeer);

            var blockHeader = await _blockchainService.GetBestChainLastBlockHeaderAsync();

            var block = await _grpcPeer.GetBlockByHashAsync(blockHeader.GetHash());

            block.ShouldBeNull();
        }
Exemplo n.º 7
0
        public GrpcPeerTests()
        {
            _blockchainService = GetRequiredService <IBlockchainService>();
            _networkServer     = GetRequiredService <IAElfNetworkServer>();
            _eventBus          = GetRequiredService <ILocalEventBus>();
            _osTestHelper      = GetRequiredService <OSTestHelper>();
            _pool = GetRequiredService <IPeerPool>();

            _grpcPeer = GrpcTestPeerHelpers.CreateNewPeer();
            _pool.TryAddPeer(_grpcPeer);
        }
Exemplo n.º 8
0
        public GrpcPeerTests()
        {
            _blockchainService = GetRequiredService<IBlockchainService>();
            _networkServer = GetRequiredService<IAElfNetworkServer>();
            _pool = GetRequiredService<IPeerPool>();

            _grpcPeer = GrpcTestPeerHelpers.CreateNewPeer();
            _grpcPeer.IsConnected = true;

            //_nonInterceptedPeer = GrpcTestPeerHelpers.CreateNewPeer("127.0.0.1:2000", false);
            //_nonInterceptedPeer.IsConnected = true;
            _nonInterceptedPeer = MockServiceClient("127.0.0.1:2000");

            _pool.TryAddPeer(_grpcPeer);
        }
Exemplo n.º 9
0
        public async Task RequestBlock_Random_ReturnsBlock_Test()
        {
            var      pubKey   = "SomePubKey";
            Metadata metadata = new Metadata {
                { GrpcConstants.PubkeyMetadataKey, pubKey }
            };
            var context = BuildServerCallContext(metadata);

            _peerPool.TryAddPeer(GrpcTestPeerHelpers.CreateBasicPeer("127.0.0.1:500", context.GetPublicKey()));
            var chain = await _blockchainService.GetChainAsync();

            var reply = await _serverService.RequestBlock(new BlockRequest { Hash = chain.LongestChainHash }, context);

            Assert.NotNull(reply.Block);
            Assert.True(reply.Block.GetHash() == chain.LongestChainHash);
        }
Exemplo n.º 10
0
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var netTestHelper = new NetworkTestContextHelpers();

            context.Services.AddSingleton(netTestHelper);

            Configure <NetworkOptions>(o => {
                o.ListeningPort = 2001;
                o.MaxPeers      = 2;
            });

            context.Services.AddTransient(o =>
            {
                var mockHandshakeProvider = new Mock <IHandshakeProvider>();
                mockHandshakeProvider.Setup(h => h.GetHandshakeAsync()).ReturnsAsync(new Handshake());
                return(mockHandshakeProvider.Object);
            });

            context.Services.AddTransient(sp =>
            {
                var mockDialer = new Mock <IPeerDialer>();

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.FakeIpEndpoint)))
                .Returns <IPEndPoint>(s =>
                {
                    var peer = GrpcTestPeerHelpers.CreateBasicPeer(NetworkTestConstants.FakeIpEndpoint, NetworkTestConstants.FakePubkey);
                    netTestHelper.AddDialedPeer(peer);
                    return(Task.FromResult(peer));
                });

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.FakeIpEndpoint2)))
                .Returns <IPEndPoint>(s =>
                {
                    var peer = GrpcTestPeerHelpers.CreateBasicPeer(NetworkTestConstants.FakeIpEndpoint2, NetworkTestConstants.FakePubkey);
                    netTestHelper.AddDialedPeer(peer);
                    return(Task.FromResult(peer));
                });

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.DialExceptionIpEndpoint)))
                .Throws <PeerDialException>();

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.HandshakeWithNetExceptionIp)))
                .Returns <IPEndPoint>(s =>
                {
                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(), CancellationToken.None))
                    .Throws(new AggregateException());

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.FakeIpEndpoint2, NetworkTestConstants.FakePubkey,
                                                                        mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(Task.FromResult(peer));
                });

                // Incorrect handshake
                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.BadHandshakeIp)))
                .Returns <IPEndPoint>((s) =>
                {
                    var handshakeReply = new HandshakeReply {
                        Error = HandshakeError.InvalidHandshake,
                    };

                    var handshakeCall = TestCalls.AsyncUnaryCall(Task.FromResult(handshakeReply),
                                                                 Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });

                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                             CancellationToken.None)).Returns(handshakeCall);

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.GoodPeerEndpoint,
                                                                        NetworkTestConstants.FakePubkey, mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(Task.FromResult(peer));
                });

                // This peer will pass all checks with success.
                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.GoodPeerEndpoint)))
                .Returns <IPEndPoint>(s =>
                {
                    var keypair        = CryptoHelper.GenerateKeyPair();
                    var handshakeReply = new HandshakeReply {
                        Error     = HandshakeError.HandshakeOk,
                        Handshake = netTestHelper.CreateValidHandshake(keypair, 10)
                    };
                    var handshakeCall = TestCalls.AsyncUnaryCall(Task.FromResult(handshakeReply),
                                                                 Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });

                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                             CancellationToken.None)).Returns(handshakeCall);

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.GoodPeerEndpoint,
                                                                        keypair.PublicKey.ToHex(), mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(Task.FromResult(peer));
                });

                return(mockDialer.Object);
            });
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var netTestHelper = new NetworkTestContext();

            context.Services.AddSingleton(netTestHelper);

            Configure <NetworkOptions>(o => {
                o.ListeningPort = 2001;
                o.MaxPeers      = 2;
            });

            context.Services.AddTransient(o =>
            {
                var mockBlockchainService = new Mock <IBlockchainService>();
                var keyPair = CryptoHelper.GenerateKeyPair();

                mockBlockchainService.Setup(b => b.GetChainAsync()).ReturnsAsync(new Chain
                {
                    Id = NetworkTestConstants.DefaultChainId
                });

                mockBlockchainService.Setup(b => b.GetBlockHeaderByHashAsync(It.IsAny <Hash>())).ReturnsAsync(
                    NetworkTestHelper.CreateFakeBlockHeader(NetworkTestConstants.DefaultChainId, 1, keyPair));

                return(mockBlockchainService.Object);
            });

            context.Services.AddTransient(sp =>
            {
                var mockDialer = new Mock <IPeerDialer>();

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.FakeIpEndpoint)))
                .Returns <IPEndPoint>(s =>
                {
                    var peer = GrpcTestPeerHelpers.CreateBasicPeer(NetworkTestConstants.FakeIpEndpoint, NetworkTestConstants.FakePubkey);
                    netTestHelper.AddDialedPeer(peer);
                    return(Task.FromResult(peer));
                });

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.FakeIpEndpoint2)))
                .Returns <IPEndPoint>(s =>
                {
                    var peer = GrpcTestPeerHelpers.CreateBasicPeer(NetworkTestConstants.FakeIpEndpoint2, NetworkTestConstants.FakePubkey);
                    netTestHelper.AddDialedPeer(peer);
                    return(Task.FromResult(peer));
                });

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants
                                                                         .DialExceptionIpEndpoint)))
                .Throws <Exception>();

                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.HandshakeWithNetExceptionIp)))
                .Returns <IPEndPoint>(s =>
                {
                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(), CancellationToken.None))
                    .Throws(new AggregateException());

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.FakeIpEndpoint2, NetworkTestConstants.FakePubkey,
                                                                        mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(Task.FromResult(peer));
                });

                // Incorrect handshake
                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.BadHandshakeIp)))
                .Returns <IPEndPoint>((s) =>
                {
                    var handshakeReply = new HandshakeReply();

                    var handshakeCall = TestCalls.AsyncUnaryCall(Task.FromResult(handshakeReply),
                                                                 Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });

                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                             CancellationToken.None)).Returns(handshakeCall);
                    mockClient.Setup(m => m.ConfirmHandshakeAsync(It.IsAny <ConfirmHandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                                  CancellationToken.None)).Throws(new AggregateException());

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.GoodPeerEndpoint,
                                                                        NetworkTestConstants.FakePubkey, mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(Task.FromResult(peer));
                });

                // Incorrect handshake signature
                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants
                                                                         .HandshakeWithDataExceptionIp)))
                .Returns <string>(async(s) =>
                {
                    var handshakeProvider        = context.Services.GetServiceLazy <IHandshakeProvider>().Value;
                    var handshake                = await handshakeProvider.GetHandshakeAsync();
                    handshake.HandshakeData.Time = null;
                    var handshakeReply           = new HandshakeReply {
                        Handshake = handshake
                    };

                    var handshakeCall = TestCalls.AsyncUnaryCall(Task.FromResult(handshakeReply),
                                                                 Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });

                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                             CancellationToken.None)).Returns(handshakeCall);

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.GoodPeerEndpoint,
                                                                        NetworkTestConstants.FakePubkey, mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(peer);
                });

                // This peer will pass all checks with success.
                mockDialer.Setup(d => d.DialPeerAsync(It.Is <IPEndPoint>(ip => ip.ToString() == NetworkTestConstants.GoodPeerEndpoint)))
                .Returns <IPEndPoint>(s =>
                {
                    var keyPair        = CryptoHelper.GenerateKeyPair();
                    var handshakeReply = new HandshakeReply {
                        Handshake = NetworkTestHelper.CreateValidHandshake(keyPair, 10)
                    };
                    var handshakeCall = TestCalls.AsyncUnaryCall(Task.FromResult(handshakeReply),
                                                                 Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });
                    var ConfirmHandshakeCall = TestCalls.AsyncUnaryCall(Task.FromResult(new VoidReply()),
                                                                        Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });

                    var mockClient = new Mock <PeerService.PeerServiceClient>();
                    mockClient.Setup(m => m.DoHandshakeAsync(It.IsAny <HandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                             CancellationToken.None)).Returns(handshakeCall);

                    mockClient.Setup(m => m.ConfirmHandshakeAsync(It.IsAny <ConfirmHandshakeRequest>(), It.IsAny <Metadata>(), It.IsAny <DateTime?>(),
                                                                  CancellationToken.None)).Returns(ConfirmHandshakeCall);

                    var peer = GrpcTestPeerHelpers.CreatePeerWithClient(NetworkTestConstants.GoodPeerEndpoint,
                                                                        keyPair.PublicKey.ToHex(), mockClient.Object);

                    netTestHelper.AddDialedPeer(peer);

                    return(Task.FromResult(peer));
                });

                return(mockDialer.Object);
            });
        }