Example #1
0
        public void SetUp()
        {
            _trueCryptoRandom = new CryptoRandom();

            // WARN: order reflects the internal implementation of the service (tests may fail after any refactoring)
            _testRandom = new TestRandom(
                NetTestVectors.NonceA,
                NetTestVectors.EphemeralKeyA.KeyBytes,
                _trueCryptoRandom.GenerateRandomBytes(100),
                NetTestVectors.NonceB,
                NetTestVectors.EphemeralKeyB.KeyBytes,
                _trueCryptoRandom.GenerateRandomBytes(100));

            _messageSerializationService = new MessageSerializationService();
            _messageSerializationService.Register(new AuthMessageSerializer());
            _messageSerializationService.Register(new AuthEip8MessageSerializer(new Eip8MessagePad(_testRandom)));
            _messageSerializationService.Register(new AckMessageSerializer());
            _messageSerializationService.Register(new AckEip8MessageSerializer(new Eip8MessagePad(_testRandom)));

            _eciesCipher = new EciesCipher(_trueCryptoRandom); // TODO: provide a separate test random with specific IV and epehemeral key for testing

            _initiatorService = new EncryptionHandshakeService(_messageSerializationService, _eciesCipher, _testRandom, _signer, NetTestVectors.StaticKeyA, NullLogManager.Instance);
            _recipientService = new EncryptionHandshakeService(_messageSerializationService, _eciesCipher, _testRandom, _signer, NetTestVectors.StaticKeyB, NullLogManager.Instance);

            _initiatorHandshake = new EncryptionHandshake();
            _recipientHandshake = new EncryptionHandshake();

            _auth = null;
            _ack  = null;
        }
        public void Will_not_serve_receipts_requests_above_512()
        {
            StatusMessageSerializer   statusMessageSerializer = new StatusMessageSerializer();
            ReceiptsMessageSerializer receiptMessageSerializer
                = new ReceiptsMessageSerializer(MainnetSpecProvider.Instance);
            GetReceiptsMessageSerializer getReceiptMessageSerializer
                = new GetReceiptsMessageSerializer();
            MessageSerializationService serializationService = new MessageSerializationService();

            serializationService.Register(statusMessageSerializer);
            serializationService.Register(receiptMessageSerializer);
            serializationService.Register(getReceiptMessageSerializer);

            ISyncServer          syncServer      = Substitute.For <ISyncServer>();
            Eth63ProtocolHandler protocolHandler = new Eth63ProtocolHandler(
                _session,
                serializationService,
                Substitute.For <INodeStatsManager>(),
                syncServer,
                Substitute.For <ITxPool>(),
                LimboLogs.Instance);

            StatusMessage statusMessage = new StatusMessage();
            Packet        statusPacket  =
                new Packet("eth", Eth62MessageCode.Status, statusMessageSerializer.Serialize(statusMessage));

            GetReceiptsMessage getReceiptsMessage = new GetReceiptsMessage(
                Enumerable.Repeat(Keccak.Zero, 513).ToArray());
            Packet getReceiptsPacket =
                new Packet("eth", Eth63MessageCode.GetReceipts, getReceiptMessageSerializer.Serialize(getReceiptsMessage));

            protocolHandler.HandleMessage(statusPacket);
            Assert.Throws <EthSyncException>(() => protocolHandler.HandleMessage(getReceiptsPacket));
        }
Example #3
0
        public void SetUp()
        {
            Console.WriteLine("AAA");
            Session session = new Session(8545, Substitute.For <IChannel>(), Substitute.For <IDisconnectsAnalyzer>(), LimboLogs.Instance);

            session.RemoteNodeId = TestItem.PublicKeyA;
            session.RemoteHost   = "127.0.0.1";
            session.RemotePort   = 30303;
            _ser = new MessageSerializationService();
            _ser.Register(new TransactionsMessageSerializer());
            _ser.Register(new StatusMessageSerializer());
            NodeStatsManager stats = new NodeStatsManager(TimerFactory.Default, LimboLogs.Instance);
            var ecdsa         = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance);
            var tree          = Build.A.BlockTree().TestObject;
            var stateProvider = new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance);
            var specProvider  = MainnetSpecProvider.Instance;

            TxPool.TxPool txPool = new TxPool.TxPool(
                ecdsa,
                new ChainHeadInfoProvider(new FixedBlockChainHeadSpecProvider(MainnetSpecProvider.Instance), tree, stateProvider),
                new TxPoolConfig(),
                new TxValidator(ChainId.Mainnet),
                LimboLogs.Instance,
                new TransactionComparerProvider(specProvider, tree).GetDefaultComparer());
            ISyncServer syncSrv = Substitute.For <ISyncServer>();
            BlockHeader head    = Build.A.BlockHeader.WithNumber(1).TestObject;

            syncSrv.Head.Returns(head);
            _handler = new Eth62ProtocolHandler(session, _ser, stats, syncSrv, txPool, ShouldGossip.Instance, LimboLogs.Instance);
            _handler.DisableTxFiltering();

            StatusMessage statusMessage = new StatusMessage();

            statusMessage.ProtocolVersion = 63;
            statusMessage.BestHash        = Keccak.Compute("1");
            statusMessage.GenesisHash     = Keccak.Compute("0");
            statusMessage.TotalDifficulty = 131200;
            statusMessage.ChainId         = 1;
            IByteBuffer bufStatus = _ser.ZeroSerialize(statusMessage);

            _zeroPacket            = new ZeroPacket(bufStatus);
            _zeroPacket.PacketType = bufStatus.ReadByte();

            _handler.HandleMessage(_zeroPacket);

            Transaction tx = Build.A.Transaction.SignedAndResolved(ecdsa, TestItem.PrivateKeyA).TestObject;

            _txMsg = new TransactionsMessage(new[] { tx });
        }
Example #4
0
        private void SetupAll(bool useLimboOutput = false)
        {
            var secrets = NetTestVectors.GetSecretsPair();

            FrameCipher       frameCipher       = new FrameCipher(secrets.A.AesSecret);
            FrameMacProcessor frameMacProcessor = new FrameMacProcessor(TestItem.IgnoredPublicKey, secrets.A);

            _zeroSplitter = new TestZeroSplitter();
            _zeroSplitter.DisableFraming();
            _zeroEncoder       = new TestZeroEncoder(frameCipher, frameMacProcessor);
            _zeroSnappyEncoder = new TestZeroSnappy();
            Transaction a = Build.A.Transaction.TestObject;
            Transaction b = Build.A.Transaction.TestObject;

            _block = Build.A.Block.WithTransactions(a, b).TestObject;
            _newBlockMessageSerializer = new NewBlockMessageSerializer();
            if (useLimboOutput)
            {
                _outputBuffer = new MockBuffer();
            }

            _newBlockMessage       = new NewBlockMessage();
            _newBlockMessage.Block = _block;
            _serializationService  = new MessageSerializationService();
            _serializationService.Register(_newBlockMessageSerializer);
            _packetSender = new PacketSender(_serializationService, LimboLogs.Instance);
            ResourceLeakDetector.Level = ResourceLeakDetector.DetectionLevel.Paranoid;
        }
        public void SetUp()
        {
            _trueCryptoRandom = new CryptoRandom();

            _testRandom = new BenchmarkTestRandom(_trueCryptoRandom, 6);

            _messageSerializationService = new MessageSerializationService();
            _messageSerializationService.Register(new AuthMessageSerializer());
            _messageSerializationService.Register(new AuthEip8MessageSerializer(new Eip8MessagePad(_testRandom)));
            _messageSerializationService.Register(new AckMessageSerializer());
            _messageSerializationService.Register(new AckEip8MessageSerializer(new Eip8MessagePad(_testRandom)));

            _eciesCipher = new EciesCipher(_trueCryptoRandom); // TODO: provide a separate test random with specific IV and ephemeral key for testing

            _initiatorService = new HandshakeService(_messageSerializationService, _eciesCipher, _testRandom, _ecdsa, NetTestVectors.StaticKeyA, LimboLogs.Instance);
            _recipientService = new HandshakeService(_messageSerializationService, _eciesCipher, _testRandom, _ecdsa, NetTestVectors.StaticKeyB, LimboLogs.Instance);
        }
Example #6
0
        public async Task Can_request_and_handle_receipts()
        {
            Context ctx = new Context();
            StatusMessageSerializer   statusMessageSerializer = new StatusMessageSerializer();
            ReceiptsMessageSerializer receiptMessageSerializer
                = new ReceiptsMessageSerializer(MainnetSpecProvider.Instance);
            MessageSerializationService serializationService = new MessageSerializationService();

            serializationService.Register(statusMessageSerializer);
            serializationService.Register(receiptMessageSerializer);

            Eth63ProtocolHandler protocolHandler = new Eth63ProtocolHandler(
                ctx.Session,
                serializationService,
                Substitute.For <INodeStatsManager>(),
                Substitute.For <ISyncServer>(),
                Substitute.For <ITxPool>(),
                LimboLogs.Instance);

            var receipts = Enumerable.Repeat(
                Enumerable.Repeat(Build.A.Receipt.WithAllFieldsFilled.TestObject, 100).ToArray(),
                1000).ToArray(); // TxReceipt[1000][100]

            StatusMessage statusMessage = new StatusMessage();
            Packet        statusPacket  =
                new Packet("eth", Eth62MessageCode.Status, statusMessageSerializer.Serialize(statusMessage));

            ReceiptsMessage receiptsMsg    = new ReceiptsMessage(receipts);
            Packet          receiptsPacket =
                new Packet("eth", Eth63MessageCode.Receipts, receiptMessageSerializer.Serialize(receiptsMsg));

            protocolHandler.HandleMessage(statusPacket);
            Task <TxReceipt[][]> task = protocolHandler.GetReceipts(
                Enumerable.Repeat(Keccak.Zero, 1000).ToArray(),
                CancellationToken.None);

            protocolHandler.HandleMessage(receiptsPacket);

            var result = await task;

            result.Should().HaveCount(1000);
        }
Example #7
0
        private void BuildSubprotocol()
        {
            ISession                    session              = Substitute.For <ISession>();
            INodeStatsManager           nodeStatsManager     = new NodeStatsManager(Substitute.For <ITimerFactory>(), LimboLogs.Instance);
            MessageSerializationService serializationService = new MessageSerializationService();

            serializationService.Register(typeof(HiMessage).Assembly);
            IConsumerService           consumerService        = Substitute.For <IConsumerService>();
            INdmConsumerChannelManager consumerChannelManager = Substitute.For <INdmConsumerChannelManager>();
            EthereumEcdsa ecdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance);

            _subprotocol = new NdmSubprotocol(session, nodeStatsManager, serializationService, LimboLogs.Instance, consumerService, consumerChannelManager, ecdsa, new DevWallet(new WalletConfig(), LimboLogs.Instance), Substitute.For <INdmFaucet>(), TestItem.PublicKeyB, TestItem.AddressB, TestItem.AddressA, false);
        }
Example #8
0
        public void Will_not_send_messages_larger_than_2MB()
        {
            Context ctx = new Context();
            StatusMessageSerializer   statusMessageSerializer = new StatusMessageSerializer();
            ReceiptsMessageSerializer receiptMessageSerializer
                = new ReceiptsMessageSerializer(MainnetSpecProvider.Instance);
            GetReceiptsMessageSerializer getReceiptMessageSerializer
                = new GetReceiptsMessageSerializer();
            MessageSerializationService serializationService = new MessageSerializationService();

            serializationService.Register(statusMessageSerializer);
            serializationService.Register(receiptMessageSerializer);
            serializationService.Register(getReceiptMessageSerializer);

            ISyncServer          syncServer      = Substitute.For <ISyncServer>();
            Eth63ProtocolHandler protocolHandler = new Eth63ProtocolHandler(
                ctx.Session,
                serializationService,
                Substitute.For <INodeStatsManager>(),
                syncServer,
                Substitute.For <ITxPool>(),
                LimboLogs.Instance);

            syncServer.GetReceipts(Arg.Any <Keccak>()).Returns(
                Enumerable.Repeat(Build.A.Receipt.WithAllFieldsFilled.TestObject, 512).ToArray());

            StatusMessage statusMessage = new StatusMessage();
            Packet        statusPacket  =
                new Packet("eth", Eth62MessageCode.Status, statusMessageSerializer.Serialize(statusMessage));

            GetReceiptsMessage getReceiptsMessage = new GetReceiptsMessage(
                Enumerable.Repeat(Keccak.Zero, 512).ToArray());
            Packet getReceiptsPacket =
                new Packet("eth", Eth63MessageCode.GetReceipts, getReceiptMessageSerializer.Serialize(getReceiptsMessage));

            protocolHandler.HandleMessage(statusPacket);
            protocolHandler.HandleMessage(getReceiptsPacket);
            ctx.Session.Received().DeliverMessage(Arg.Is <ReceiptsMessage>(r => r.TxReceipts.Length == 14));
        }
        public void SetUp()
        {
            _trueCryptoRandom = new CryptoRandom();

            _testRandom = new TestRandom();

            _messageSerializationService = new MessageSerializationService();
            _messageSerializationService.Register(new AuthMessageSerializer());
            _messageSerializationService.Register(new AuthEip8MessageSerializer(new Eip8MessagePad(_testRandom)));
            _messageSerializationService.Register(new AckMessageSerializer());
            _messageSerializationService.Register(new AckEip8MessageSerializer(new Eip8MessagePad(_testRandom)));

            _eciesCipher = new EciesCipher(_trueCryptoRandom); // TODO: provide a separate test random with specific IV and epehemeral key for testing

            _initiatorService = new HandshakeService(_messageSerializationService, _eciesCipher, _testRandom, _ecdsa, NetTestVectors.StaticKeyA, NullLogManager.Instance);
            _recipientService = new HandshakeService(_messageSerializationService, _eciesCipher, _testRandom, _ecdsa, NetTestVectors.StaticKeyB, NullLogManager.Instance);

            _initiatorHandshake = new EncryptionHandshake();
            _recipientHandshake = new EncryptionHandshake();

            _auth = null;
            _ack  = null;
        }
            public Context()
            {
                MessageSerializationService serializationService = new MessageSerializationService();

                serializationService.Register(typeof(GetBlockWitnessHashesMessage).Assembly);
                Session = Substitute.For <ISession>();
                Session.Node.Returns(new Node(TestItem.PublicKeyA, new IPEndPoint(IPAddress.Loopback, 30303)));
                INodeStatsManager nodeStats = Substitute.For <INodeStatsManager>();

                SyncServer         = Substitute.For <ISyncServer>();
                WitProtocolHandler = new WitProtocolHandler(
                    Session,
                    serializationService,
                    nodeStats,
                    SyncServer,
                    LimboLogs.Instance);
            }
Example #11
0
        public MessageTests()
        {
            _service.Register(typeof(HiMessage).Assembly);

            DataAssetDecoder.Init();
            DataAssetRulesDecoder.Init();
            DataAssetRuleDecoder.Init();
            DataAssetProviderDecoder.Init();
            DataDeliveryReceiptDecoder.Init();
            DataRequestDecoder.Init();
            EarlyRefundTicketDecoder.Init();
            FaucetResponseDecoder.Init();
            FaucetRequestDetailsDecoder.Init();
            DataDeliveryReceiptDecoder.Init();
            DataDeliveryReceiptRequestDecoder.Init();
            UnitsRangeDecoder.Init();
            SessionDecoder.Init();
            DepositApprovalDecoder.Init();
            DataDeliveryReceiptToMergeDecoder.Init();
        }
Example #12
0
        private static async Task InitNet(ChainSpec chainSpec)
        {
            /* tools */
            var serializationService = new MessageSerializationService();
            var cryptoRandom         = new CryptoRandom();
            var signer = new Signer();

            /* rlpx */
            var eciesCipher = new EciesCipher(cryptoRandom);
            var eip8Pad     = new Eip8MessagePad(cryptoRandom);

            serializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            serializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            var encryptionHandshakeServiceA = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _privateKey, NetworkLogger);

            /* p2p */
            serializationService.Register(new HelloMessageSerializer());
            serializationService.Register(new DisconnectMessageSerializer());
            serializationService.Register(new PingMessageSerializer());
            serializationService.Register(new PongMessageSerializer());

            /* eth */
            serializationService.Register(new StatusMessageSerializer());
            serializationService.Register(new TransactionsMessageSerializer());
            serializationService.Register(new GetBlockHeadersMessageSerializer());
            serializationService.Register(new NewBlockHashesMessageSerializer());
            serializationService.Register(new GetBlockBodiesMessageSerializer());
            serializationService.Register(new BlockHeadersMessageSerializer());
            serializationService.Register(new BlockBodiesMessageSerializer());
            serializationService.Register(new NewBlockMessageSerializer());

            NetworkLogger.Info("Initializing server...");
            var localPeer = new RlpxPeer(_privateKey.PublicKey, _listenPort, encryptionHandshakeServiceA, serializationService, _syncManager, NetworkLogger);
            await localPeer.Init();

            // https://stackoverflow.com/questions/6803073/get-local-ip-address?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
            string localIp;

            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect("8.8.8.8", 65530);
                IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                Debug.Assert(endPoint != null, "null endpoint when connecting a UDP socket");
                localIp = endPoint.Address.ToString();
            }

            NetworkLogger.Info($"Node is up and listening on {localIp}:{_listenPort}... press ENTER to exit");
            NetworkLogger.Info($"enode://{_privateKey.PublicKey.ToString(false)}@{localIp}:{_listenPort}");

            foreach (Bootnode bootnode in chainSpec.Bootnodes)
            {
                NetworkLogger.Info($"Connecting to {bootnode.Description} @ {bootnode.Host}:{bootnode.Port}");
                await localPeer.ConnectAsync(bootnode.PublicKey, bootnode.Host, bootnode.Port);

                NetworkLogger.Info("Testnet connected...");
            }

            Console.ReadLine();
            NetworkLogger.Info("Shutting down...");
            NetworkLogger.Info("Stopping sync manager...");
            await _syncManager.StopAsync();

            NetworkLogger.Info("Stopping blockchain processor...");
            await _blockchainProcessor.StopAsync();

            NetworkLogger.Info("Stopping local peer...");
            await localPeer.Shutdown();

            NetworkLogger.Info("Goodbye...");
        }
Example #13
0
        private static void Start()
        {
            var privateKeyProvider = new PrivateKeyProvider(PrivateKey);
            var config             = new DiscoveryConfigurationProvider(new NetworkHelper(Logger));
            var signer             = new Signer();
            var cryptoRandom       = new CryptoRandom();
            var configProvider     = new ConfigurationProvider();

            var nodeFactory = new NodeFactory();
            var calculator  = new NodeDistanceCalculator(config);

            var nodeTable = new NodeTable(config, nodeFactory, new FileKeyStore(configProvider, new JsonSerializer(Logger), new AesEncrypter(configProvider, Logger), cryptoRandom, Logger), Logger, calculator);

            var evictionManager  = new EvictionManager(nodeTable, Logger);
            var lifecycleFactory = new NodeLifecycleManagerFactory(nodeFactory, nodeTable, Logger, config, new DiscoveryMessageFactory(config), evictionManager);

            var discoveryManager = new DiscoveryManager(Logger, config, lifecycleFactory, nodeFactory, nodeTable);

            var nodesLocator           = new NodesLocator(nodeTable, discoveryManager, config, Logger);
            var discoveryMesageFactory = new DiscoveryMessageFactory(config);
            var nodeIdResolver         = new NodeIdResolver(signer);

            var pingSerializer      = new PingMessageSerializer(signer, privateKeyProvider, discoveryMesageFactory, nodeIdResolver, nodeFactory);
            var pongSerializer      = new PongMessageSerializer(signer, privateKeyProvider, discoveryMesageFactory, nodeIdResolver, nodeFactory);
            var findNodeSerializer  = new FindNodeMessageSerializer(signer, privateKeyProvider, discoveryMesageFactory, nodeIdResolver, nodeFactory);
            var neighborsSerializer = new NeighborsMessageSerializer(signer, privateKeyProvider, discoveryMesageFactory, nodeIdResolver, nodeFactory);

            var messageSerializationService = new MessageSerializationService();

            messageSerializationService.Register(pingSerializer);
            messageSerializationService.Register(pongSerializer);
            messageSerializationService.Register(findNodeSerializer);
            messageSerializationService.Register(neighborsSerializer);


            //P2P initialization
            IMessagePad eip8Pad = new Eip8MessagePad(cryptoRandom);

            messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            messageSerializationService.Register(new HelloMessageSerializer());
            messageSerializationService.Register(new DisconnectMessageSerializer());
            messageSerializationService.Register(new Nethermind.Network.P2P.PingMessageSerializer());
            messageSerializationService.Register(new Nethermind.Network.P2P.PongMessageSerializer());
            messageSerializationService.Register(new StatusMessageSerializer());
            IEciesCipher eciesCipher = new EciesCipher(cryptoRandom);
            IEncryptionHandshakeService encryptionHandshakeService = new EncryptionHandshakeService(messageSerializationService, eciesCipher, cryptoRandom, signer, PrivateKey, Logger);
            var p2pManager = new P2PManager(encryptionHandshakeService, Logger, messageSerializationService, Substitute.For <ISynchronizationManager>());

            //Connect discovery with P2P
            discoveryManager.RegisterDiscoveryListener(p2pManager);

            _discoveryApp = new DiscoveryApp(config, nodesLocator, Logger, discoveryManager, nodeFactory, nodeTable, messageSerializationService, cryptoRandom);
            _discoveryApp.Start(PrivateKey.PublicKey);
        }