示例#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;
        }
示例#2
0
        public void Can_decrypt_ack_eip8_message_with_additional_elements()
        {
            Hex hex = "01f004076e58aae772bb101ab1a8e64e01ee96e64857ce82b1113817c6cdd52c09d26f7b90981cd7" +
                      "ae835aeac72e1573b8a0225dd56d157a010846d888dac7464baf53f2ad4e3d584531fa203658fab0" +
                      "3a06c9fd5e35737e417bc28c1cbf5e5dfc666de7090f69c3b29754725f84f75382891c561040ea1d" +
                      "dc0d8f381ed1b9d0d4ad2a0ec021421d847820d6fa0ba66eaf58175f1b235e851c7e2124069fbc20" +
                      "2888ddb3ac4d56bcbd1b9b7eab59e78f2e2d400905050f4a92dec1c4bdf797b3fc9b2f8e84a482f3" +
                      "d800386186712dae00d5c386ec9387a5e9c9a1aca5a573ca91082c7d68421f388e79127a5177d4f8" +
                      "590237364fd348c9611fa39f78dcdceee3f390f07991b7b47e1daa3ebcb6ccc9607811cb17ce51f1" +
                      "c8c2c5098dbdd28fca547b3f58c01a424ac05f869f49c6a34672ea2cbbc558428aa1fe48bbfd6115" +
                      "8b1b735a65d99f21e70dbc020bfdface9f724a0d1fb5895db971cc81aa7608baa0920abb0a565c9c" +
                      "436e2fd13323428296c86385f2384e408a31e104670df0791d93e743a3a5194ee6b076fb6323ca59" +
                      "3011b7348c16cf58f66b9633906ba54a2ee803187344b394f75dd2e663a57b956cb830dd7a908d4f" +
                      "39a2336a61ef9fda549180d4ccde21514d117b6c6fd07a9102b5efe710a32af4eeacae2cb3b1dec0" +
                      "35b9593b48b9d3ca4c13d245d5f04169b0b1";

            byte[] allBytes  = hex;
            byte[] sizeBytes = allBytes.Slice(0, 2);
            int    size      = sizeBytes.ToInt32();

            ICryptoRandom cryptoRandom = new CryptoRandom();
            EciesCipher   cipher       = new EciesCipher(cryptoRandom);

            byte[] deciphered = cipher.Decrypt(NetTestVectors.StaticKeyA, allBytes.Slice(2, size), sizeBytes);

            AckEip8Message ackMessage = _messageSerializationService.Deserialize <AckEip8Message>(deciphered);

            Assert.AreEqual(ackMessage.EphemeralPublicKey, NetTestVectors.EphemeralKeyB.PublicKey);
            Assert.AreEqual(ackMessage.Nonce, NetTestVectors.NonceB);
            Assert.AreEqual(ackMessage.Version, 4);
        }
示例#3
0
        public void Can_decrypt_auth_eip8_message()
        {
            byte[] allBytes = Bytes.FromHexString("01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b" +
                                                  "0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84" +
                                                  "9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c" +
                                                  "da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc" +
                                                  "147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6" +
                                                  "d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee" +
                                                  "70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09" +
                                                  "c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3" +
                                                  "6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e" +
                                                  "2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c" +
                                                  "3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c");

            byte[] sizeBytes = allBytes.Slice(0, 2);
            int    size      = sizeBytes.ToInt32();

            ICryptoRandom cryptoRandom = new CryptoRandom();
            EciesCipher   cipher       = new EciesCipher(cryptoRandom);

            byte[] deciphered = cipher.Decrypt(NetTestVectors.StaticKeyB, allBytes.Slice(2, size), sizeBytes);

            AuthEip8Message authMessage = _messageSerializationService.Deserialize <AuthEip8Message>(deciphered);

            Assert.AreEqual(authMessage.PublicKey, NetTestVectors.StaticKeyA.PublicKey);
            Assert.AreEqual(authMessage.Nonce, NetTestVectors.NonceA);
            Assert.AreEqual(authMessage.Version, 4);
            Assert.NotNull(authMessage.Signature);

            byte[] data = _messageSerializationService.Serialize(authMessage);
            Array.Resize(ref data, deciphered.Length);

            //TODO: check 169
            Assert.AreEqual(deciphered.Slice(0, 169), data.Slice(0, 169), "serialization");
        }
示例#4
0
        private async Task InitPeer()
        {
            /* rlpx */
            var eciesCipher = new EciesCipher(_cryptoRandom);
            var eip8Pad     = new Eip8MessagePad(_cryptoRandom);

            _messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(Assembly.GetAssembly(typeof(HelloMessageSerializer)));

            var encryptionHandshakeServiceA = new EncryptionHandshakeService(_messageSerializationService, eciesCipher,
                                                                             _cryptoRandom, new Ecdsa(), _nodeKey, _logManager);

            var networkConfig = _configProvider.GetConfig <INetworkConfig>();

            _sessionMonitor = new SessionMonitor(networkConfig, _logManager);
            _rlpxPeer       = new RlpxPeer(
                _nodeKey.PublicKey,
                _initConfig.P2PPort,
                encryptionHandshakeServiceA,
                _logManager,
                _sessionMonitor);

            await _rlpxPeer.Init();

            var peerStorage = new NetworkStorage(PeersDbPath, networkConfig, _logManager, _perfService);

            ProtocolValidator protocolValidator = new ProtocolValidator(_nodeStatsManager, _blockTree, _logManager);

            _protocolsManager = new ProtocolsManager(_syncPeerPool, _syncServer, _txPool, _discoveryApp, _messageSerializationService, _rlpxPeer, _nodeStatsManager, protocolValidator, peerStorage, _perfService, _logManager);
            PeerLoader peerLoader = new PeerLoader(networkConfig, _nodeStatsManager, peerStorage, _logManager);

            _peerManager = new PeerManager(_rlpxPeer, _discoveryApp, _nodeStatsManager, peerStorage, peerLoader, networkConfig, _logManager);
            _peerManager.Init();
        }
示例#5
0
        private async Task InitPeer()
        {
            /* rlpx */
            var eciesCipher = new EciesCipher(_cryptoRandom);
            var eip8Pad     = new Eip8MessagePad(_cryptoRandom);

            _messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            var encryptionHandshakeServiceA = new EncryptionHandshakeService(_messageSerializationService, eciesCipher,
                                                                             _cryptoRandom, new Signer(), _nodeKey, _logManager);

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

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

            /* eth63 */
            _messageSerializationService.Register(new GetNodeDataMessageSerializer());
            _messageSerializationService.Register(new NodeDataMessageSerializer());
            _messageSerializationService.Register(new GetReceiptsMessageSerializer());
            _messageSerializationService.Register(new ReceiptsMessageSerializer());

            var             networkConfig  = _configProvider.GetConfig <INetworkConfig>();
            ISessionMonitor sessionMonitor = new SessionMonitor(networkConfig, _logManager);

            _rlpxPeer = new RlpxPeer(
                _nodeKey.PublicKey,
                _initConfig.P2PPort,
                encryptionHandshakeServiceA,
                _logManager,
                _perfService,
                sessionMonitor);

            await _rlpxPeer.Init();


            var peerStorage = new NetworkStorage(PeersDbPath, networkConfig, _logManager, _perfService);

            ProtocolValidator protocolValidator = new ProtocolValidator(_nodeStatsManager, _blockTree, _logManager);

            _protocolsManager = new ProtocolsManager(_syncManager, _transactionPool, _discoveryApp, _messageSerializationService, _rlpxPeer, _nodeStatsManager, protocolValidator, peerStorage, _perfService, _logManager);
            PeerLoader peerLoader = new PeerLoader(networkConfig, _nodeStatsManager, peerStorage, _logManager);

            _peerManager = new PeerManager(_rlpxPeer, _discoveryApp, _nodeStatsManager, peerStorage, peerLoader, networkConfig, _logManager);
            _peerManager.Init();
        }
示例#6
0
        public async Task Can_handshake()
        {
            /* tools */
            var cryptoRandom = new CryptoRandom();
            var testLogger   = new TestLogger();
            var logManager   = new OneLoggerLogManager(testLogger);

            /* rlpx + p2p + eth */
            _keyA = TestObject.PrivateKeyA;
            _keyB = TestObject.PrivateKeyB;
            _keyC = TestObject.PrivateKeyC;

            var signer      = new Signer();
            var eciesCipher = new EciesCipher(cryptoRandom);

            var serializationService = Build.A.SerializationService().WithEncryptionHandshake().WithP2P().WithEth().TestObject;

            var encryptionHandshakeServiceA = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _keyA, logManager);
            var encryptionHandshakeServiceB = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _keyB, logManager);
//            var encryptionHandshakeServiceC = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _keyC, logger);

            var   syncManager  = Substitute.For <ISynchronizationManager>();
            Block genesisBlock = Build.A.Block.Genesis.TestObject;

            syncManager.Head.Returns(genesisBlock.Header);
            syncManager.Genesis.Returns(genesisBlock.Header);

            var peerServerA = new RlpxPeer(new NodeId(_keyA.PublicKey), PortA, encryptionHandshakeServiceA, serializationService, syncManager, logManager);
            var peerServerB = new RlpxPeer(new NodeId(_keyB.PublicKey), PortB, encryptionHandshakeServiceB, serializationService, syncManager, logManager);
//            var peerServerC = new RlpxPeer(_keyC.PublicKey, PortC, encryptionHandshakeServiceC, serializationService, Substitute.For<ISynchronizationManager>(), logger);

            await Task.WhenAll(peerServerA.Init(), peerServerB.Init());

//            await Task.WhenAll(peerServerA.Init(), peerServerB.Init(), peerServerC.Init());

            Console.WriteLine("Servers running...");
            Console.WriteLine("Connecting A to B...");
            await peerServerA.ConnectAsync(new NodeId(_keyB.PublicKey), "127.0.0.1", PortB);

            Console.WriteLine("A to B connected...");

//            Console.WriteLine("Connecting A to C...");
//            await peerServerA.ConnectAsync(_keyC.PublicKey, "127.0.0.1", PortC);
//            Console.WriteLine("A to C connected...");
//
//            Console.WriteLine("Connecting C to C...");
//            await peerServerB.ConnectAsync(_keyA.PublicKey, "127.0.0.1", PortA);
//            Console.WriteLine("C to C connected...");

            Console.WriteLine("Shutting down...");
            await Task.WhenAll(peerServerA.Shutdown(), peerServerB.Shutdown());

            Console.WriteLine("Goodbye...");

            Assert.True(testLogger.LogList.Count(l => l.Contains("ETH received status with")) == 2, "ETH status exchange");
        }
示例#7
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);
        }
        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);
        }
示例#9
0
        private async Task InitPeer()
        {
            /* rlpx */
            var eciesCipher = new EciesCipher(_cryptoRandom);
            var eip8Pad     = new Eip8MessagePad(_cryptoRandom);

            _messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            var encryptionHandshakeServiceA = new EncryptionHandshakeService(_messageSerializationService, eciesCipher,
                                                                             _cryptoRandom, new Signer(), _privateKey, _logManager);

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

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

            _rlpxPeer = new RlpxPeer(new NodeId(_privateKey.PublicKey), _initConfig.P2PPort,
                                     _syncManager,
                                     _messageSerializationService,
                                     encryptionHandshakeServiceA,
                                     _nodeStatsProvider,
                                     _logManager, _perfService);

            await _rlpxPeer.Init();

            var peerStorage = new NetworkStorage(PeersDbPath, _configProvider.GetConfig <INetworkConfig>(), _logManager, _perfService);

            _peerManager = new PeerManager(_rlpxPeer, _discoveryManager, _syncManager, _nodeStatsProvider, peerStorage,
                                           _nodeFactory, _configProvider, _perfService, _logManager);
            _peerManager.Init(_initConfig.DiscoveryEnabled);
        }
示例#10
0
        private async Task InitNet(int listenPort)
        {
            /* tools */
            _messageSerializationService = new MessageSerializationService();
            _cryptoRandom = new CryptoRandom();
            _signer       = new Signer();

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

            _messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            var encryptionHandshakeServiceA = new EncryptionHandshakeService(_messageSerializationService, eciesCipher, _cryptoRandom, _signer, _privateKey, _logManager);

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

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

            _logger.Info("Initializing server...");
            _localPeer = new RlpxPeer(new NodeId(_privateKey.PublicKey), listenPort, encryptionHandshakeServiceA, _messageSerializationService, _syncManager, _logManager);
            await _localPeer.Init();

            var localIp = _networkHelper.GetLocalIp();

            _logger.Info($"Node is up and listening on {localIp}:{listenPort}... press ENTER to exit");
            _logger.Info($"enode://{_privateKey.PublicKey}@{localIp}:{listenPort}");
        }
        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;
        }
示例#12
0
        public void Can_decrypt_ack_eip8_message()
        {
            Hex hex = "01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470" +
                      "b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de" +
                      "05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814" +
                      "c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171" +
                      "ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f" +
                      "6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb" +
                      "e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d" +
                      "3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b" +
                      "201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8" +
                      "797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac" +
                      "8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7" +
                      "1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7" +
                      "5833c2464c805246155289f4";

            byte[] allBytes  = hex;
            byte[] sizeBytes = allBytes.Slice(0, 2);
            int    size      = sizeBytes.ToInt32();

            ICryptoRandom cryptoRandom = new CryptoRandom();
            EciesCipher   cipher       = new EciesCipher(cryptoRandom);

            byte[] deciphered = cipher.Decrypt(NetTestVectors.StaticKeyA, allBytes.Slice(2, size), sizeBytes);

            AckEip8Message ackMessage = _messageSerializationService.Deserialize <AckEip8Message>(deciphered);

            Assert.AreEqual(ackMessage.EphemeralPublicKey, NetTestVectors.EphemeralKeyB.PublicKey);
            Assert.AreEqual(ackMessage.Nonce, NetTestVectors.NonceB);
            Assert.AreEqual(ackMessage.Version, 4);

            byte[] data = _messageSerializationService.Serialize(ackMessage);
            Array.Resize(ref data, deciphered.Length);

            // TODO: check 102
            Assert.AreEqual(deciphered.Slice(0, 102), data.Slice(0, 102), "serialization");
        }
示例#13
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...");
        }
示例#14
0
        private async Task InitPeer()
        {
            if (_ctx.DbProvider == null)
            {
                throw new StepDependencyException(nameof(_ctx.DbProvider));
            }
            if (_ctx.BlockTree == null)
            {
                throw new StepDependencyException(nameof(_ctx.BlockTree));
            }
            if (_ctx.ReceiptStorage == null)
            {
                throw new StepDependencyException(nameof(_ctx.ReceiptStorage));
            }
            if (_ctx.BlockValidator == null)
            {
                throw new StepDependencyException(nameof(_ctx.BlockValidator));
            }
            if (_ctx.SyncPeerPool == null)
            {
                throw new StepDependencyException(nameof(_ctx.SyncPeerPool));
            }
            if (_ctx.Synchronizer == null)
            {
                throw new StepDependencyException(nameof(_ctx.Synchronizer));
            }
            if (_ctx.Enode == null)
            {
                throw new StepDependencyException(nameof(_ctx.Enode));
            }
            if (_ctx.NodeKey == null)
            {
                throw new StepDependencyException(nameof(_ctx.NodeKey));
            }
            if (_ctx.MainBlockProcessor == null)
            {
                throw new StepDependencyException(nameof(_ctx.MainBlockProcessor));
            }
            if (_ctx.NodeStatsManager == null)
            {
                throw new StepDependencyException(nameof(_ctx.NodeStatsManager));
            }
            if (_ctx.KeyStore == null)
            {
                throw new StepDependencyException(nameof(_ctx.KeyStore));
            }
            if (_ctx.RpcModuleProvider == null)
            {
                throw new StepDependencyException(nameof(_ctx.RpcModuleProvider));
            }
            if (_ctx.Wallet == null)
            {
                throw new StepDependencyException(nameof(_ctx.Wallet));
            }
            if (_ctx.EthereumEcdsa == null)
            {
                throw new StepDependencyException(nameof(_ctx.EthereumEcdsa));
            }
            if (_ctx.SpecProvider == null)
            {
                throw new StepDependencyException(nameof(_ctx.SpecProvider));
            }
            if (_ctx.TxPool == null)
            {
                throw new StepDependencyException(nameof(_ctx.TxPool));
            }
            if (_ctx.EthereumJsonSerializer == null)
            {
                throw new StepDependencyException(nameof(_ctx.EthereumJsonSerializer));
            }

            /* rlpx */
            EciesCipher    eciesCipher = new EciesCipher(_ctx.CryptoRandom);
            Eip8MessagePad eip8Pad     = new Eip8MessagePad(_ctx.CryptoRandom);

            _ctx._messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            _ctx._messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            _ctx._messageSerializationService.Register(Assembly.GetAssembly(typeof(HelloMessageSerializer)));
            _ctx._messageSerializationService.Register(new ReceiptsMessageSerializer(_ctx.SpecProvider));

            HandshakeService encryptionHandshakeServiceA = new HandshakeService(_ctx._messageSerializationService, eciesCipher,
                                                                                _ctx.CryptoRandom, new Ecdsa(), _ctx.NodeKey.Unprotect(), _ctx.LogManager);

            _ctx._messageSerializationService.Register(Assembly.GetAssembly(typeof(HiMessageSerializer)));

            IDiscoveryConfig discoveryConfig = _ctx.Config <IDiscoveryConfig>();
            IInitConfig      initConfig      = _ctx.Config <IInitConfig>();

            _ctx.SessionMonitor = new SessionMonitor(_networkConfig, _ctx.LogManager);
            _ctx.RlpxPeer       = new RlpxPeer(
                _ctx._messageSerializationService,
                _ctx.NodeKey.PublicKey,
                _networkConfig.P2PPort,
                encryptionHandshakeServiceA,
                _ctx.LogManager,
                _ctx.SessionMonitor);

            await _ctx.RlpxPeer.Init();

            _ctx.StaticNodesManager = new StaticNodesManager(initConfig.StaticNodesPath, _ctx.LogManager);
            await _ctx.StaticNodesManager.InitAsync();

            var     dbName  = "PeersDB";
            IFullDb peersDb = initConfig.DiagnosticMode == DiagnosticMode.MemDb
                ? (IFullDb) new MemDb(dbName)
                : new SimpleFilePublicKeyDb(dbName, PeersDbPath.GetApplicationResourcePath(initConfig.BaseDbPath), _ctx.LogManager);

            NetworkStorage peerStorage = new NetworkStorage(peersDb, _ctx.LogManager);

            ProtocolValidator protocolValidator = new ProtocolValidator(_ctx.NodeStatsManager, _ctx.BlockTree, _ctx.LogManager);

            _ctx.ProtocolsManager = new ProtocolsManager(_ctx.SyncPeerPool, _ctx.SyncServer, _ctx.TxPool, _ctx.DiscoveryApp, _ctx._messageSerializationService, _ctx.RlpxPeer, _ctx.NodeStatsManager, protocolValidator, peerStorage, _ctx.SpecProvider, _ctx.LogManager);

            if (!(_ctx.NdmInitializer is null))
            {
                if (_ctx.WebSocketsManager == null)
                {
                    throw new StepDependencyException(nameof(_ctx.WebSocketsManager));
                }
                if (_ctx.GrpcServer == null)
                {
                    throw new StepDependencyException(nameof(_ctx.GrpcServer));
                }
                if (_ctx.NdmDataPublisher == null)
                {
                    throw new StepDependencyException(nameof(_ctx.NdmDataPublisher));
                }
                if (_ctx.NdmConsumerChannelManager == null)
                {
                    throw new StepDependencyException(nameof(_ctx.NdmConsumerChannelManager));
                }
                if (_ctx.BloomStorage == null)
                {
                    throw new StepDependencyException(nameof(_ctx.BloomStorage));
                }
                if (_ctx.ReceiptFinder == null)
                {
                    throw new StepDependencyException(nameof(_ctx.ReceiptFinder));
                }

                if (_logger.IsInfo)
                {
                    _logger.Info($"Initializing NDM...");
                }
                _ctx.HttpClient = new DefaultHttpClient(new HttpClient(), _ctx.EthereumJsonSerializer, _ctx.LogManager);
                INdmConfig ndmConfig = _ctx.Config <INdmConfig>();
                if (ndmConfig.ProxyEnabled)
                {
                    _ctx.JsonRpcClientProxy = new JsonRpcClientProxy(_ctx.HttpClient, ndmConfig.JsonRpcUrlProxies,
                                                                     _ctx.LogManager);
                    _ctx.EthJsonRpcClientProxy = new EthJsonRpcClientProxy(_ctx.JsonRpcClientProxy);
                }

                FilterStore             filterStore         = new FilterStore();
                FilterManager           filterManager       = new FilterManager(filterStore, _ctx.MainBlockProcessor, _ctx.TxPool, _ctx.LogManager);
                INdmCapabilityConnector capabilityConnector = await _ctx.NdmInitializer.InitAsync(
                    _ctx.ConfigProvider,
                    _ctx.DbProvider,
                    initConfig.BaseDbPath,
                    _ctx.BlockTree,
                    _ctx.TxPool,
                    _ctx.SpecProvider,
                    _ctx.ReceiptFinder,
                    _ctx.Wallet,
                    filterStore,
                    filterManager,
                    _ctx.Timestamper,
                    _ctx.EthereumEcdsa,
                    _ctx.RpcModuleProvider,
                    _ctx.KeyStore,
                    _ctx.EthereumJsonSerializer,
                    _ctx.CryptoRandom,
                    _ctx.Enode,
                    _ctx.NdmConsumerChannelManager,
                    _ctx.NdmDataPublisher,
                    _ctx.GrpcServer,
                    _ctx.NodeStatsManager,
                    _ctx.ProtocolsManager,
                    protocolValidator,
                    _ctx._messageSerializationService,
                    initConfig.EnableUnsecuredDevWallet,
                    _ctx.WebSocketsManager,
                    _ctx.LogManager,
                    _ctx.MainBlockProcessor,
                    _ctx.JsonRpcClientProxy,
                    _ctx.EthJsonRpcClientProxy,
                    _ctx.HttpClient,
                    _ctx.MonitoringService,
                    _ctx.BloomStorage);

                capabilityConnector.Init();
                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM initialized.");
                }
            }

            PeerLoader peerLoader = new PeerLoader(_networkConfig, discoveryConfig, _ctx.NodeStatsManager, peerStorage, _ctx.LogManager);

            _ctx.PeerManager = new PeerManager(_ctx.RlpxPeer, _ctx.DiscoveryApp, _ctx.NodeStatsManager, peerStorage, peerLoader, _networkConfig, _ctx.LogManager, _ctx.StaticNodesManager);
            _ctx.PeerManager.Init();
        }
示例#15
0
        private async Task InitPeer()
        {
            /* rlpx */
            var eciesCipher = new EciesCipher(_cryptoRandom);
            var eip8Pad     = new Eip8MessagePad(_cryptoRandom);

            _messageSerializationService.Register(new AuthEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(new AckEip8MessageSerializer(eip8Pad));
            _messageSerializationService.Register(Assembly.GetAssembly(typeof(HelloMessageSerializer)));

            var encryptionHandshakeServiceA = new EncryptionHandshakeService(_messageSerializationService, eciesCipher,
                                                                             _cryptoRandom, new Ecdsa(), _nodeKey, _logManager);

            _messageSerializationService.Register(Assembly.GetAssembly(typeof(HiMessageSerializer)));

            var networkConfig   = _configProvider.GetConfig <INetworkConfig>();
            var discoveryConfig = _configProvider.GetConfig <IDiscoveryConfig>();

            _sessionMonitor = new SessionMonitor(networkConfig, _logManager);
            _rlpxPeer       = new RlpxPeer(
                _nodeKey.PublicKey,
                _initConfig.P2PPort,
                encryptionHandshakeServiceA,
                _logManager,
                _sessionMonitor);

            await _rlpxPeer.Init();

            _staticNodesManager = new StaticNodesManager(_initConfig.StaticNodesPath, _logManager);
            await _staticNodesManager.InitAsync();

            var peersDb     = new SimpleFilePublicKeyDb(Path.Combine(_initConfig.BaseDbPath, PeersDbPath), _logManager);
            var peerStorage = new NetworkStorage(peersDb, _logManager);

            ProtocolValidator protocolValidator = new ProtocolValidator(_nodeStatsManager, _blockTree, _logManager);

            _protocolsManager = new ProtocolsManager(_syncPeerPool, _syncServer, _txPool, _discoveryApp, _messageSerializationService, _rlpxPeer, _nodeStatsManager, protocolValidator, peerStorage, _perfService, _logManager);

            if (!(_ndmInitializer is null))
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Initializing NDM...");
                }
                var capabilityConnector = await _ndmInitializer.InitAsync(_configProvider, _dbProvider,
                                                                          _initConfig.BaseDbPath, _blockProcessor, _blockTree, _txPool, _txPoolInfoProvider, _specProvider,
                                                                          _receiptStorage, _wallet, _timestamp, _ethereumEcdsa, _rpcModuleProvider, _keyStore, _jsonSerializer,
                                                                          _cryptoRandom, _enode, _ndmConsumerChannelManager, _ndmDataPublisher, _grpcService,
                                                                          _nodeStatsManager, _protocolsManager, protocolValidator, _messageSerializationService,
                                                                          _initConfig.EnableUnsecuredDevWallet, _logManager);

                capabilityConnector.Init();
                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM initialized.");
                }
            }

            PeerLoader peerLoader = new PeerLoader(networkConfig, discoveryConfig, _nodeStatsManager, peerStorage, _logManager);

            _peerManager = new PeerManager(_rlpxPeer, _discoveryApp, _nodeStatsManager, peerStorage, peerLoader, networkConfig, _logManager, _staticNodesManager);
            _peerManager.Init();
        }