Esempio n. 1
0
        public void PingMessageTest()
        {
            var message = new PingMessage
            {
                FarAddress         = _farAddress,
                DestinationAddress = _nearAddress,
                SourceAddress      = _farAddress,
                Version            = _config.PingMessageVersion,
                FarPublicKey       = _privateKey.PublicKey,
                ExpirationTime     = _config.DiscoveryMsgExpiryTime + Timestamp.UnixUtcUntilNowMilisecs
            };

            var data = _messageSerializationService.Serialize(message);
            var deserializedMessage = _messageSerializationService.Deserialize <PingMessage>(data);

            Assert.AreEqual(message.MessageType, deserializedMessage.MessageType);
            Assert.AreEqual(message.FarPublicKey, deserializedMessage.FarPublicKey);
            Assert.AreEqual(message.ExpirationTime, deserializedMessage.ExpirationTime);

            Assert.AreEqual(message.FarAddress, deserializedMessage.SourceAddress);
            Assert.AreEqual(message.DestinationAddress, deserializedMessage.DestinationAddress);
            Assert.AreEqual(message.SourceAddress, deserializedMessage.SourceAddress);
            Assert.AreEqual(message.Version, deserializedMessage.Version);
            Assert.IsNotNull(deserializedMessage.Mdc);
        }
Esempio n. 2
0
        public void handling_hi_message_should_succeed()
        {
            _verifySignature = true;
            InitSubprotocol();
            var hiMessage = new HiMessage(1, TestItem.AddressC, TestItem.AddressD, TestItem.PublicKeyA,
                                          new Signature(1, 1, 27));
            var hiPacket = new Packet(hiMessage.Protocol, hiMessage.PacketType,
                                      _messageSerializationService.Serialize(hiMessage));

            _messageSerializationService.Deserialize <HiMessage>(hiPacket.Data).Returns(hiMessage);
            var hash = Keccak.Compute(hiMessage.NodeId.Bytes);

            _ecdsa.RecoverPublicKey(hiMessage.Signature, hash).Returns(TestItem.PublicKeyA);
            _subprotocol.HandleMessage(hiPacket);
            _ecdsa.Received().RecoverPublicKey(hiMessage.Signature, hash);
            _subprotocol.ProviderAddress.Should().Be(hiMessage.ProviderAddress);
            _subprotocol.ConsumerAddress.Should().Be(hiMessage.ConsumerAddress);
            _consumerService.Received().AddProviderPeer(_subprotocol);
            var getDataAssetsMessage = new GetDataAssetsMessage();

            _messageSerializationService.Serialize(getDataAssetsMessage).Returns(Array.Empty <byte>());
            var getDataAssetsPacket = new Packet(getDataAssetsMessage.Protocol, getDataAssetsMessage.PacketType,
                                                 _messageSerializationService.Serialize(getDataAssetsMessage));

            _messageSerializationService.Deserialize <GetDataAssetsMessage>(getDataAssetsPacket.Data)
            .Returns(getDataAssetsMessage);

            Received.InOrder(() =>
            {
                _session.DeliverMessage(Arg.Any <GetDataAssetsMessage>());
                _session.DeliverMessage(Arg.Any <GetDepositApprovalsMessage>());
            });
        }
Esempio n. 3
0
 protected T Deserialize <T>(byte[] data) where T : P2PMessage
 {
     try
     {
         return(_serializer.Deserialize <T>(data));
     }
     catch (RlpException e)
     {
         if (Logger.IsDebug)
         {
             Logger.Debug($"Failed to deserialize message {typeof(T).Name}, with exception {e}");
         }
         ReportIn($"{typeof(T).Name} - Deserialization exception");
         throw;
     }
 }
        private DiscoveryMessage Deserialize(MessageType type, byte[] msg)
        {
            switch (type)
            {
            case MessageType.Ping:
                return(_messageSerializationService.Deserialize <PingMessage>(msg));

            case MessageType.Pong:
                return(_messageSerializationService.Deserialize <PongMessage>(msg));

            case MessageType.FindNode:
                return(_messageSerializationService.Deserialize <FindNodeMessage>(msg));

            case MessageType.Neighbors:
                return(_messageSerializationService.Deserialize <NeighborsMessage>(msg));

            default:
                throw new Exception($"Unsupported messageType: {type}");
            }
        }
Esempio n. 5
0
        public void PingFormatTest()
        {
            var encodedPing = "e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663a" +
                              "aa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a" +
                              "4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000" +
                              "000000000000000000018208ae820d058443b9a3550102";
            var ping = _messageSerializationService.Deserialize <PingMessage>(Bytes.FromHexString(encodedPing));

            Assert.AreEqual(4, ping.Version);

            encodedPing = "577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e" +
                          "7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3" +
                          "d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef" +
                          "12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203" +
                          "040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba7602" +
                          "3fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee191" +
                          "7084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c7" +
                          "6d922dc3";
            ping = _messageSerializationService.Deserialize <PingMessage>(Bytes.FromHexString(encodedPing));
            Assert.AreEqual(555, ping.Version);
        }
Esempio n. 6
0
        public void Can_decrypt_auth_eip8_message_with_additional_elements()
        {
            Hex hex = "01b8044c6c312173685d1edd268aa95e1d495474c6959bcdd10067ba4c9013df9e40ff45f5bfd6f7" +
                      "2471f93a91b493f8e00abc4b80f682973de715d77ba3a005a242eb859f9a211d93a347fa64b597bf" +
                      "280a6b88e26299cf263b01b8dfdb712278464fd1c25840b995e84d367d743f66c0e54a586725b7bb" +
                      "f12acca27170ae3283c1073adda4b6d79f27656993aefccf16e0d0409fe07db2dc398a1b7e8ee93b" +
                      "cd181485fd332f381d6a050fba4c7641a5112ac1b0b61168d20f01b479e19adf7fdbfa0905f63352" +
                      "bfc7e23cf3357657455119d879c78d3cf8c8c06375f3f7d4861aa02a122467e069acaf513025ff19" +
                      "6641f6d2810ce493f51bee9c966b15c5043505350392b57645385a18c78f14669cc4d960446c1757" +
                      "1b7c5d725021babbcd786957f3d17089c084907bda22c2b2675b4378b114c601d858802a55345a15" +
                      "116bc61da4193996187ed70d16730e9ae6b3bb8787ebcaea1871d850997ddc08b4f4ea668fbf3740" +
                      "7ac044b55be0908ecb94d4ed172ece66fd31bfdadf2b97a8bc690163ee11f5b575a4b44e36e2bfb2" +
                      "f0fce91676fd64c7773bac6a003f481fddd0bae0a1f31aa27504e2a533af4cef3b623f4791b2cca6" +
                      "d490";

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

            byte[] deciphered = _eciesCipher.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);
        }
Esempio n. 7
0
        public void PingMessageTest()
        {
            var message = new PingMessage
            {
                FarAddress         = _farAddress,
                DestinationAddress = _nearAddress,
                SourceAddress      = _farAddress,
                Version            = _config.PingMessageVersion,
                FarPublicKey       = _privateKey.PublicKey,
                ExpirationTime     = 60 + (long)_timestamper.EpochMilliseconds
            };

            var data = _messageSerializationService.Serialize(message);
            var deserializedMessage = _messageSerializationService.Deserialize <PingMessage>(data);

            Assert.AreEqual(message.MessageType, deserializedMessage.MessageType);
            Assert.AreEqual(message.FarPublicKey, deserializedMessage.FarPublicKey);
            Assert.AreEqual(message.ExpirationTime, deserializedMessage.ExpirationTime);

            Assert.AreEqual(message.FarAddress, deserializedMessage.SourceAddress);
            Assert.AreEqual(message.DestinationAddress, deserializedMessage.DestinationAddress);
            Assert.AreEqual(message.SourceAddress, deserializedMessage.SourceAddress);
            Assert.AreEqual(message.Version, deserializedMessage.Version);
            Assert.IsNotNull(deserializedMessage.Mdc);
        }
Esempio n. 8
0
        public void PingMessageTest()
        {
            var message = new PingMessage
            {
                FarAddress         = _farAddress,
                DestinationAddress = _nearAddress,
                SourceAddress      = _farAddress,
                FarPublicKey       = _privateKey.PublicKey,
                ExpirationTime     = 60 + (long)_timestamper.EpochMilliseconds
            };

            var data = _messageSerializationService.Serialize(message);
            var deserializedMessage = _messageSerializationService.Deserialize <PingMessage>(data);

            Assert.AreEqual(message.MessageType, deserializedMessage.MessageType);
            Assert.AreEqual(message.FarPublicKey, deserializedMessage.FarPublicKey);
            Assert.AreEqual(message.ExpirationTime, deserializedMessage.ExpirationTime);

            Assert.AreEqual(message.FarAddress, deserializedMessage.SourceAddress);
            Assert.AreEqual(message.DestinationAddress, deserializedMessage.DestinationAddress);
            Assert.AreEqual(message.SourceAddress, deserializedMessage.SourceAddress);
            Assert.AreEqual(message.Version, deserializedMessage.Version);

            byte[] expectedPingMdc = Bytes.FromHexString("0xf8c61953f3b94a91aefe611e61dd74fe26aa5c969d9f29b7e063e6169171a772");
            Assert.IsNotNull(expectedPingMdc);
        }
Esempio n. 9
0
        private void Test <T>(T message) where T : P2PMessage
        {
            message.Protocol.Should().Be("ndm");

            FieldInfo fieldInfo = typeof(NdmMessageCode).GetField(message.GetType().Name.Replace("Message", string.Empty), BindingFlags.Static | BindingFlags.Public);

            message.PacketType.Should().Be((int)fieldInfo.GetValue(null));

            byte[] firstSer  = _service.Serialize(message);
            byte[] secondSer = _service.Serialize(_service.Deserialize <T>(firstSer));

            firstSer.Should().BeEquivalentTo(secondSer, typeof(T).Name + " -> " + firstSer.ToHexString());
        }
Esempio n. 10
0
        public Packet Ack(EncryptionHandshake handshake, Packet auth)
        {
            handshake.AuthPacket = auth;

            AuthMessageBase authMessage;
            bool            preEip8Format = false;

            byte[] plainText = null;
            try
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Trying to decrypt an old version of {nameof(AuthMessage)}");
                }
                (preEip8Format, plainText) = _eciesCipher.Decrypt(_privateKey, auth.Data);
            }
            catch (Exception ex)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Exception when decrypting ack {ex.Message}");
                }
            }

            if (preEip8Format)
            {
                authMessage = _messageSerializationService.Deserialize <AuthMessage>(plainText);
            }
            else
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Trying to decrypt version 4 of {nameof(AuthEip8Message)}");
                }
                byte[] sizeData = auth.Data.Slice(0, 2);
                (_, plainText) = _eciesCipher.Decrypt(_privateKey, auth.Data.Slice(2), sizeData);
                authMessage    = _messageSerializationService.Deserialize <AuthEip8Message>(plainText);
            }

            var nodeId = authMessage.PublicKey;

            if (_logger.IsTrace)
            {
                _logger.Trace($"Received AUTH v{authMessage.Version} from {nodeId}");
            }

            handshake.RemoteNodeId        = nodeId;
            handshake.RecipientNonce      = _cryptoRandom.GenerateRandomBytes(32);
            handshake.EphemeralPrivateKey = _ephemeralGenerator.Generate();

            handshake.InitiatorNonce = authMessage.Nonce;
            byte[] staticSharedSecret = Proxy.EcdhSerialized(handshake.RemoteNodeId.Bytes, _privateKey.KeyBytes);
            byte[] forSigning         = staticSharedSecret.Xor(handshake.InitiatorNonce);

            handshake.RemoteEphemeralPublicKey = _ecdsa.RecoverPublicKey(authMessage.Signature, new Keccak(forSigning));

            byte[] data;
            if (preEip8Format)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Building an {nameof(AckMessage)}");
                }
                AckMessage ackMessage = new AckMessage();
                ackMessage.EphemeralPublicKey = handshake.EphemeralPrivateKey.PublicKey;
                ackMessage.Nonce = handshake.RecipientNonce;
                var ackData = _messageSerializationService.Serialize(ackMessage);

                data = _eciesCipher.Encrypt(handshake.RemoteNodeId, ackData, Array.Empty <byte>());
            }
            else
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"Building an {nameof(AckEip8Message)}");
                }
                AckEip8Message ackMessage = new AckEip8Message();
                ackMessage.EphemeralPublicKey = handshake.EphemeralPrivateKey.PublicKey;
                ackMessage.Nonce = handshake.RecipientNonce;
                var ackData = _messageSerializationService.Serialize(ackMessage);

                int    size      = ackData.Length + 32 + 16 + 65; // data + MAC + IV + pub
                byte[] sizeBytes = size.ToBigEndianByteArray().Slice(2, 2);
                data = Bytes.Concat(sizeBytes, _eciesCipher.Encrypt(handshake.RemoteNodeId, ackData, sizeBytes));
            }

            handshake.AckPacket = new Packet(data);
            SetSecrets(handshake, HandshakeRole.Recipient);
            return(handshake.AckPacket);
        }
Esempio n. 11
0
 protected T Deserialize <T>(byte[] data) where T : P2PMessage
 {
     return(_serializer.Deserialize <T>(data));
 }
        public Packet Ack(EncryptionHandshake handshake, Packet auth)
        {
            handshake.AuthPacket = auth;

            AuthMessageBase authMessage;
            bool            isOld = false;

            try
            {
                _logger.Info($"Trying to decrypt an old version of {nameof(AuthMessage)}");
                byte[] plaintextOld = _eciesCipher.Decrypt(_privateKey, auth.Data);
                authMessage = _messageSerializationService.Deserialize <AuthMessage>(plaintextOld);
                isOld       = true;
            }
            catch (Exception)
            {
                _logger.Info($"Trying to decrypt version 4 of {nameof(AuthEip8Message)}");
                byte[] sizeData  = auth.Data.Slice(0, 2);
                byte[] plaintext = _eciesCipher.Decrypt(_privateKey, auth.Data.Slice(2), sizeData);
                authMessage = _messageSerializationService.Deserialize <AuthEip8Message>(plaintext);
            }

            var nodeId = new NodeId(authMessage.PublicKey);

            _logger.Debug($"Received AUTH v{authMessage.Version} from {nodeId}");

            handshake.RemoteNodeId        = nodeId;
            handshake.RecipientNonce      = _cryptoRandom.GenerateRandomBytes(32);
            handshake.EphemeralPrivateKey = new PrivateKey(_cryptoRandom.GenerateRandomBytes(32));

            handshake.InitiatorNonce = authMessage.Nonce;
            byte[] staticSharedSecret = BouncyCrypto.Agree(_privateKey, handshake.RemoteNodeId.PublicKey);
            byte[] forSigning         = staticSharedSecret.Xor(handshake.InitiatorNonce);

            handshake.RemoteEphemeralPublicKey = _signer.RecoverPublicKey(authMessage.Signature, new Keccak(forSigning));

            byte[] ackData;
            if (isOld) // what was the difference? shall I really include ephemeral public key in v4?
            {
                _logger.Debug($"Building an {nameof(AckMessage)}");
                AckMessage ackMessage = new AckMessage();
                ackMessage.EphemeralPublicKey = handshake.EphemeralPrivateKey.PublicKey;
                ackMessage.Nonce = handshake.RecipientNonce;
                ackData          = _messageSerializationService.Serialize(ackMessage);
            }
            else
            {
                _logger.Debug($"Building an {nameof(AckEip8Message)}");
                AckEip8Message ackMessage = new AckEip8Message();
                ackMessage.EphemeralPublicKey = handshake.EphemeralPrivateKey.PublicKey;
                ackMessage.Nonce = handshake.RecipientNonce;
                ackData          = _messageSerializationService.Serialize(ackMessage);
            }

            int size = ackData.Length + 32 + 16 + 65; // data + MAC + IV + pub

            byte[] sizeBytes  = size.ToBigEndianByteArray().Slice(2, 2);
            byte[] packetData = _eciesCipher.Encrypt(handshake.RemoteNodeId.PublicKey, ackData, sizeBytes);
            handshake.AckPacket = new Packet(Bytes.Concat(sizeBytes, packetData));
            SetSecrets(handshake, EncryptionHandshakeRole.Recipient);
            return(handshake.AckPacket);
        }