예제 #1
0
        public Block(byte[] rlp)
        {
            var decoded = RLP.Decode(rlp);

            if (decoded.Count == 7 && decoded[1] != null)
            {
                Height     = (int)(decoded[0] != null ? ByteManipulator.GetUInt32(decoded[0]) : 0);
                Timestamp  = ByteManipulator.GetUInt32(decoded[1]);
                Difficulty = new LargeInteger(decoded[2] ?? new byte[32]);
                Nonce      = decoded[3] != null?ByteManipulator.BigEndianTruncate(decoded[3], 32) : new byte[32];

                MinerAddress = decoded[4] != null?ByteManipulator.BigEndianTruncate(decoded[4], 33) : new byte[33];

                PreviousBlockHash = decoded[5] != null?ByteManipulator.BigEndianTruncate(decoded[5], 32) : new byte[32];

                var decodedTransactions = RLP.Decode(decoded[6]);

                Transactions = new List <Transaction>();

                if (decodedTransactions != null)
                {
                    foreach (var rlpTransaction in decodedTransactions)
                    {
                        var tx = new Transaction(rlpTransaction);
                        Transactions.Add(tx);
                    }
                }
            }
            else
            {
                throw new Exception("Invalid block");
            }
        }
예제 #2
0
        /// <summary>
        /// Parse a whole receipt from stored bytes.
        /// </summary>
        public static Receipt FromStorageBytesRlp(byte[] bytes)
        {
            RLPCollection list      = RLP.Decode(bytes);
            RLPCollection innerList = (RLPCollection)list[0];

            RLPCollection logList      = RLP.Decode(innerList[3].RLPData);
            RLPCollection innerLogList = (RLPCollection)logList[0];

            Log[] logs = innerLogList.Select(x => Log.FromBytesRlp(x.RLPData)).ToArray();

            // Method name is the 15th item to be added. Existing receipts without this data will throw exceptions without this check.
            var hasMethodName = innerList.Count > 14;

            var receipt = new Receipt(
                new uint256(innerList[0].RLPData),
                BitConverter.ToUInt64(innerList[1].RLPData),
                logs,
                new Bloom(innerList[2].RLPData),
                new uint256(innerList[4].RLPData),
                new uint256(innerList[5].RLPData),
                new uint160(innerList[6].RLPData),
                innerList[7].RLPData != null ? new uint160(innerList[7].RLPData) : null,
                innerList[8].RLPData != null ? new uint160(innerList[8].RLPData) : null,
                BitConverter.ToBoolean(innerList[9].RLPData),
                innerList[10].RLPData != null ? Encoding.UTF8.GetString(innerList[10].RLPData) : null,
                innerList[11].RLPData != null ? Encoding.UTF8.GetString(innerList[11].RLPData) : null,
                BitConverter.ToUInt64(innerList[12].RLPData),
                BitConverter.ToUInt64(innerList[13].RLPData),
                hasMethodName && innerList[14].RLPData != null ? Encoding.UTF8.GetString(innerList[14].RLPData) : null);

            return(receipt);
        }
예제 #3
0
        /// <summary>
        /// Deserializes event log data. Uses the supplied type to determine field information and attempts to deserialize these
        /// fields from the supplied data. For <see cref="Address"/> types, an additional conversion to a base58 string is applied.
        /// </summary>
        /// <param name="bytes">The raw event log data.</param>
        /// <param name="type">The type to attempt to deserialize.</param>
        /// <returns>An <see cref="ExpandoObject"/> containing the fields of the Type and its deserialized values.</returns>
        public dynamic DeserializeLogData(byte[] bytes, Type type)
        {
            RLPCollection collection = (RLPCollection)RLP.Decode(bytes);

            var instance = new ExpandoObject() as IDictionary <string, object>;

            FieldInfo[] fields = type.GetFields();

            for (int i = 0; i < fields.Length; i++)
            {
                FieldInfo field      = fields[i];
                byte[]    fieldBytes = collection[i].RLPData;
                Type      fieldType  = field.FieldType;

                if (fieldType == typeof(Address))
                {
                    string base58Address = new uint160(fieldBytes).ToBase58Address(this.network);

                    instance[field.Name] = base58Address;
                }
                else
                {
                    object fieldValue = this.primitiveSerializer.Deserialize(fieldType, fieldBytes);

                    if (fieldType == typeof(UInt128) || fieldType == typeof(UInt256))
                    {
                        fieldValue = fieldValue.ToString();
                    }

                    instance[field.Name] = fieldValue;
                }
            }

            return(instance);
        }
예제 #4
0
        public void DecodeRLPArrayTest()
        {
            try
            {
                byte[]        value = Hex.Decode(TestConstants.BinaryTxDevnet);
                RLPCollection el    = RLP.Decode(value) as RLPCollection;
                if (el == null || el.Count <= 12)
                {
                    Assert.Fail("Collection at least of 12 items required");
                }

                Assert.AreEqual(Constants.SerializationTags.OBJECT_TAG_CONTRACT_CREATE_TRANSACTION, el[0].RLPData.ToIntFromRLPDecoded());
                Assert.AreEqual(Constants.SerializationTags.V_1, el[1].RLPData.ToIntFromRLPDecoded());
                CollectionAssert.AreEqual(el[2].RLPData, Encoding.DecodeCheckAndTag(baseKeyPair.PublicKey, Constants.SerializationTags.ID_TAG_ACCOUNT));
                Assert.AreEqual(1, el[3].RLPData.ToBigIntegerFromRLPDecoded());
                CollectionAssert.AreEqual(el[4].RLPData, Encoding.DecodeCheckWithIdentifier(TestConstants.TestContractByteCode));
                Assert.AreEqual(327683, el[5].RLPData.ToBigIntegerFromRLPDecoded());
                Assert.AreEqual(1098660000000000, el[6].RLPData.ToBigIntegerFromRLPDecoded());
                Assert.AreEqual(2000, el[7].RLPData.ToBigIntegerFromRLPDecoded());
                Assert.AreEqual(0, el[8].RLPData.ToBigIntegerFromRLPDecoded());
                Assert.AreEqual(0, el[9].RLPData.ToBigIntegerFromRLPDecoded());
                Assert.AreEqual(1000, el[10].RLPData.ToBigIntegerFromRLPDecoded());
                Assert.AreEqual(1100000000, el[11].RLPData.ToBigIntegerFromRLPDecoded());
                CollectionAssert.AreEqual(Encoding.DecodeCheckWithIdentifier(TestConstants.TestContractCallData), el[12].RLPData);
            }
            catch (Exception afe)
            {
                logger.LogError("Error decoding RLP array");
                Assert.Fail(afe.Message);
            }
        }
예제 #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="signMessageRequest"></param>
        /// <param name="channelHandlerContext"></param>
        /// <param name="senderPeerIdentifier"></param>
        /// <param name="correlationId"></param>
        protected override void HandleResponse(SignMessageResponse signMessageRequest,
                                               IChannelHandlerContext channelHandlerContext,
                                               PeerId senderPeerIdentifier,
                                               ICorrelationId correlationId)
        {
            Guard.Argument(signMessageRequest, nameof(signMessageRequest)).NotNull();
            Guard.Argument(channelHandlerContext, nameof(channelHandlerContext)).NotNull();
            Guard.Argument(senderPeerIdentifier, nameof(senderPeerIdentifier)).NotNull();
            Logger.Debug(@"sign message response");

            try
            {
                var decodeResult = RLP.Decode(signMessageRequest.OriginalMessage.ToByteArray()).RLPData;

                Guard.Argument(decodeResult, nameof(decodeResult)).NotNull("The sign message response cannot be null.");

                var originalMessage = decodeResult.ToStringFromRLPDecoded();

                Guard.Argument(originalMessage, nameof(originalMessage)).NotNull();

                _output.WriteLine(
                    $@"Signature: {signMessageRequest.Signature.ToByteArray().ToBase32()} " +
                    $@"Public Key: {signMessageRequest.PublicKey.ToByteArray().ToBase32()} Original Message: {originalMessage}");
            }
            catch (Exception ex)
            {
                Logger.Error(ex,
                             "Failed to handle SignMessageResponseHandler after receiving message {0}", signMessageRequest);
                _output.WriteLine(ex.Message);
            }
            finally
            {
                Logger.Information("Press Enter to continue ...");
            }
        }
예제 #6
0
        /// <summary>
        /// Parse a whole receipt from stored bytes.
        /// </summary>
        public static Receipt FromStorageBytesRlp(byte[] bytes)
        {
            RLPCollection list      = RLP.Decode(bytes);
            RLPCollection innerList = (RLPCollection)list[0];

            RLPCollection logList      = RLP.Decode(innerList[3].RLPData);
            RLPCollection innerLogList = (RLPCollection)logList[0];

            Log[] logs = innerLogList.Select(x => Log.FromBytesRlp(x.RLPData)).ToArray();

            var receipt = new Receipt(
                new uint256(innerList[0].RLPData),
                BitConverter.ToUInt64(innerList[1].RLPData),
                logs,
                new Bloom(innerList[2].RLPData),
                new uint256(innerList[4].RLPData),
                new uint256(innerList[5].RLPData),
                new uint160(innerList[6].RLPData),
                innerList[7].RLPData != null ? new uint160(innerList[7].RLPData) : null,
                innerList[8].RLPData != null ? new uint160(innerList[8].RLPData) : null,
                BitConverter.ToBoolean(innerList[9].RLPData),
                innerList[10].RLPData != null ? Encoding.UTF8.GetString(innerList[10].RLPData) : null,
                innerList[11].RLPData != null ? Encoding.UTF8.GetString(innerList[11].RLPData) : null
                );

            return(receipt);
        }
예제 #7
0
        private void Parse()
        {
            if (this.children != null)
            {
                return;
            }
            this.Resolve();

            //RLPCollection list = this.parsedRlp ?? RLP.Decode(this.rlp)[0] as RLPCollection;
            RLPCollection list = this.parsedRlp ?? RLP.Decode(this.rlp) as RLPCollection;

            if (list.Count == 2)
            {
                this.children = new object[2];
                Key key = Key.FromPacked(list[0].RLPData);
                this.children[0] = key;
                if (key.IsTerminal)
                {
                    this.children[1] = list[1].RLPData;
                }
                else
                {
                    this.children[1] = (list[1] is RLPCollection collection)
                        ? new Node(collection, this.trie)
                        : new Node(list[1].RLPData, this.trie);
                }
            }
            else
            {
                this.children  = new object[17];
                this.parsedRlp = list;
            }
        }
예제 #8
0
파일: Trie.cs 프로젝트: zutobg/Meadow
        /// <summary>
        /// Given a trie node directly or by reference, obtains the direct node to operate on.
        /// </summary>
        /// <param name="nodeOrReference">The trie node or trie node reference used to obtain the actual trie node.</param>
        /// <returns>Returns the representing trie node for this value.</returns>
        private RLPList DecodeNode(RLPItem nodeOrReference)
        {
            // If it's an RLP list, it's a direct representation of the node.
            if (nodeOrReference.IsList)
            {
                return((RLPList)nodeOrReference);
            }
            else
            {
                // If it's a RLP byte array/32 byte hash, it's the key used to look up the node (a reference)
                byte[] nodeHash = nodeOrReference;

                // If this matches our blank node hash, return our blank node.
                if (IsBlankNodeHash(nodeHash))
                {
                    return(null);
                }

                // Otherwise we decode our node from RLP after fetching it from our database.
                if (!Database.TryGet(nodeHash, out var nodeData))
                {
                    throw new Exception($"Could not fetch node from database with node hash: {nodeHash.ToHexString(hexPrefix: true)}");
                }

                return((RLPList)RLP.Decode(nodeData));
            }
        }
예제 #9
0
        public ContractUnspentOutput(byte[] bytes)
        {
            RLPCollection innerList = (RLPCollection)RLP.Decode(bytes);

            this.Hash  = new uint256(innerList[0].RLPData);
            this.Nvout = BitConverter.ToUInt32(innerList[1].RLPData, 0);
            this.Value = BitConverter.ToUInt64(innerList[2].RLPData, 0);
        }
예제 #10
0
파일: Account.cs 프로젝트: zutobg/Meadow
        public Account(Configuration.Configuration configuration, byte[] rlpData)
        {
            // Set our configuration
            Configuration = configuration;

            // Deserialize our decoded RLP data.
            Deserialize(RLP.Decode(rlpData));
        }
예제 #11
0
        private static IList <byte[]> RLPDecode(byte[] remaining)
        {
            RLPCollection list = RLP.Decode(remaining);

            RLPCollection innerList = (RLPCollection)list[0];

            return(innerList.Select(x => x.RLPData).ToList());
        }
예제 #12
0
        public AccountState(byte[] bytes) : this()
        {
            RLPCollection innerList = (RLPCollection)RLP.Decode(bytes);

            this.CodeHash    = innerList[0].RLPData;
            this.StateRoot   = innerList[1].RLPData;
            this.UnspentHash = innerList[2].RLPData;
            this.TypeName    = innerList[3].RLPData == null ? null : Encoding.UTF8.GetString(innerList[3].RLPData);
        }
예제 #13
0
        public static Contract FromBytes(ReadOnlySpan <byte> bytes)
        {
            var decoded = (RLPCollection)RLP.Decode(bytes.ToArray());

            return(new Contract(
                       decoded[0].RLPData.ToUInt160(),
                       decoded[1].RLPData
                       ));
        }
        public AccountState(byte[] bytes) : this()
        {
            RLPCollection list      = RLP.Decode(bytes);
            RLPCollection innerList = (RLPCollection)list[0];

            this.CodeHash    = innerList[0].RLPData;
            this.StateRoot   = innerList[1].RLPData;
            this.UnspentHash = innerList[2].RLPData;
        }
예제 #15
0
        private static void AssertIntEncoding(int test, string expected)
        {
            byte[] testBytes    = test.ToBytesForRLPEncoding();
            byte[] encoderesult = RLP.EncodeElement(testBytes);
            Assert.Equal(expected, encoderesult.ToHex());

            var decodeResult = RLP.Decode(encoderesult)[0].RLPData;

            Assert.Equal(test, decodeResult.ToBigIntegerFromRLPDecoded());
        }
예제 #16
0
        public static ValidatorCredentials FromBytes(ReadOnlySpan <byte> bytes)
        {
            var decoded   = (RLPCollection)RLP.Decode(bytes.ToArray());
            var publicKey = new ECDSAPublicKey {
                Buffer = ByteString.CopyFrom(decoded[0].RLPData)
            };
            var tsKey = decoded[1].RLPData;

            return(new ValidatorCredentials(publicKey, tsKey));
        }
예제 #17
0
파일: Trie.cs 프로젝트: zutobg/Meadow
        /// <summary>
        /// Given a node, duplicates it such that it is structurally the same, yet is a different object instance.
        /// </summary>
        /// <param name="node">The node to duplicate.</param>
        /// <returns>Returns a duplicate of the provided node.</returns>
        private RLPList NodeDuplicate(RLPList node)
        {
            // If the node is null, we return null.
            if (node == null)
            {
                return(null);
            }

            // Otherwise we serialize and deserialize it to clone it.
            return((RLPList)RLP.Decode(RLP.Encode(node)));
        }
예제 #18
0
파일: RLPTest.cs 프로젝트: lspz/VeChainCore
        public void DecodeStaticString()
        {
            var input =
                "f902d6819a8702288058b9af928202d0f90273e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f800008001830616988088ff9198c817655decc0b841bd61e198f126adddb169eebf5cd3da25ae3a3f07102e574bcd1368440d1e307c4c47884364e2abc66ef6940c4953758dd1c57f8255025639702104ce83e9a3b501";

            var rlpList      = RlpDecoder.Decode(input.HexStringToByteArray());
            var nethereumRLP = RLP.Decode(input.HexStringToByteArray());


            Assert.True(RlpCompare(rlpList, nethereumRLP));
        }
예제 #19
0
        public static ConsensusState FromBytes(ReadOnlySpan <byte> bytes)
        {
            var decoded     = (RLPCollection)RLP.Decode(bytes.ToArray());
            var tpkePubKey  = decoded[0].RLPData;
            var credentials = decoded.Skip(1)
                              .Select(x => x.RLPData)
                              .Select(x => ValidatorCredentials.FromBytes(x))
                              .ToArray();

            return(new ConsensusState(tpkePubKey, credentials));
        }
예제 #20
0
        private void Deserialize(byte[] rlp)
        {
            var data = RLP.Decode(rlp);

            Nonce       = ByteManipulator.GetUInt32(data[0] ?? new byte[] { 0 });
            Ammount     = new LargeInteger(data[1] ?? new byte[] { 0 });
            Fee         = new LargeInteger(data[2] ?? new byte[] { 0 });
            Source      = ByteManipulator.BigEndianTruncate(data[3], 33) ?? new byte[33];
            Destination = ByteManipulator.BigEndianTruncate(data[4], 33) ?? new byte[33];
            Signature   = ByteManipulator.BigEndianTruncate(data[5], 64) ?? new byte[64];
            Network     = data[6] ?? new byte[] { 0 };
        }
예제 #21
0
        public static Log FromBytesRlp(byte[] bytes)
        {
            RLPCollection  innerList      = (RLPCollection)RLP.Decode(bytes);
            RLPCollection  innerTopicList = (RLPCollection)RLP.Decode(innerList[1].RLPData);
            IList <byte[]> topics         = innerTopicList.Select(x => x.RLPData).ToList();

            return(new Log(
                       new uint160(innerList[0].RLPData),
                       topics,
                       innerList[2].RLPData
                       ));
        }
예제 #22
0
        private static void AssertStringCollection(string[] test, string expected)
        {
            byte[] encoderesult = RLP.EncodeList(EncodeElementsBytes(test.ToBytesForRLPEncoding()));
            Assert.Equal(expected, encoderesult.ToHex());

            var decodeResult = RLP.Decode(encoderesult)[0] as RLPCollection;

            for (int i = 0; i < test.Length; i++)
            {
                Assert.Equal(test[i], decodeResult[i].RLPData.ToStringFromRLPDecoded());
            }
        }
예제 #23
0
        public void TransactionRLPAndVerify()
        {
            // Verifies our RLP decoding works, and we can recover the public key/sender from the transaction.
            byte[]      rlpEncodedTransaction = "f86a15850430e23400830186a094a593094cebb06bf34df7311845c2a34996b5232485e8d4a510008026a0a003ddf704feb0c62aba5459ad0af698eab974b0fe9c3685426bde2f31669252a05625a814b54f7f994faf5747eae956dbf5c85e4649022b22b9512a74c41e92f4".HexToBytes();
            Transaction transaction           = new Transaction(RLP.Decode(rlpEncodedTransaction));

            Assert.Equal("0x82bd8ead9cfbf50d35f9c3ab75f994a59e6c3317", transaction.GetSenderAddress().ToString());

            // Verifies our rlp reencoded exactly as intended.
            byte[] rlpReencodedTransaction = RLP.Encode(transaction.Serialize());
            Assert.True(rlpEncodedTransaction.ValuesEqual(rlpReencodedTransaction));
        }
예제 #24
0
        public void ShouldEncodeEmptyList()
        {
            byte[][] test     = new byte[0][];
            string   expected = "c0";

            byte[] encoderesult = RLP.EncodeList(test);
            Assert.Equal(expected, encoderesult.ToHex());

            var decodeResult = RLP.Decode(encoderesult)[0] as RLPCollection;

            Assert.True(decodeResult.Count == 0);
        }
        /// <inheritdoc/>
        public Transaction CreateTransaction(byte[] rlpEncodedTrasaction)
        {
            Transaction transaction = new Transaction();

            RLPCollection decodedList = (RLPCollection)RLP.Decode(rlpEncodedTrasaction)[0];

            bool isSigned    = (decodedList.Count == 4);
            int  inputIdx    = isSigned ? 1 : 0;
            int  outputIdx   = isSigned ? 2 : 1;
            int  metadataIdx = isSigned ? 3 : 2;

            RLPCollection inputData = (RLPCollection)decodedList[inputIdx];

            foreach (RLPCollection input in inputData)
            {
                if (input.Count == 3)
                {
                    transaction.AddInput(Transaction.ToUInt64FromRLPDecoded(input[0].RLPData),
                                         Transaction.ToUInt16FromRLPDecoded(input[1].RLPData),
                                         Transaction.ToUInt16FromRLPDecoded(input[2].RLPData));
                }
            }

            RLPCollection outputData = (RLPCollection)decodedList[outputIdx];

            foreach (RLPCollection output in outputData)
            {
                if (output.Count == 3)
                {
                    transaction.AddOutput(output[0].RLPData.ToHex().PadLeft(32, '0').EnsureHexPrefix(),
                                          output[1].RLPData.ToHex().PadLeft(32, '0').EnsureHexPrefix(),
                                          output[2].RLPData.ToBigIntegerFromRLPDecoded());
                }
            }

            if (metadataIdx < decodedList.Count)
            {
                RLPItem metadata = (RLPItem)decodedList[metadataIdx];
                transaction.SetMetadata(metadata.RLPData.ToHex().HexToByteArray());
            }

            if (isSigned)
            {
                RLPCollection signatureData = (RLPCollection)decodedList[0];
                for (Int32 i = 0; i < signatureData.Count; ++i)
                {
                    transaction.SetSignature(i, signatureData[i].RLPData);
                }
            }

            return(transaction);
        }
        private object DeserializeArray(Type elementType, byte[] bytes)
        {
            RLPCollection collection = (RLPCollection)RLP.Decode(bytes)[0];

            var ret = Array.CreateInstance(elementType, collection.Count);

            for (int i = 0; i < collection.Count; i++)
            {
                ret.SetValue(Deserialize(elementType, collection[i].RLPData), i);
            }

            return(ret);
        }
예제 #27
0
        public void ShouldEncodeBigInteger()
        {
            BigInteger test     = "100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f".HexToByteArray().ToBigIntegerFromRLPDecoded();
            string     expected = "a0100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";

            byte[] testBytes    = test.ToBytesForRLPEncoding();
            byte[] encoderesult = RLP.EncodeElement(testBytes);
            Assert.Equal(expected, encoderesult.ToHex());

            var decodeResult = RLP.Decode(encoderesult)[0].RLPData;

            Assert.Equal(test, decodeResult.ToBigIntegerFromRLPDecoded());
        }
예제 #28
0
        public override void Deserialize(byte[] data)
        {
            // Decode our RLP item from data.
            RLPList rlpList = (RLPList)RLP.Decode(data);

            // Verify the sizes of all components.
            if (!rlpList.Items[0].IsByteArray)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's first item (signature) was not a byte array.");
            }
            else if (((byte[])rlpList.Items[0]).Length != EthereumEcdsa.SIGNATURE_RSV_SIZE)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's first item (signature) was the incorrect size.");
            }
            else if (!rlpList.Items[1].IsByteArray)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's second item (public key) was not a byte array.");
            }
            else if (((byte[])rlpList.Items[1]).Length != EthereumEcdsa.PUBLIC_KEY_SIZE)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's second item (public key) was the incorrect size.");
            }
            else if (!rlpList.Items[2].IsByteArray)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's third item (nonce) was not a byte array.");
            }
            else if (((byte[])rlpList.Items[2]).Length != RLPxSession.NONCE_SIZE)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's third item (nonce) was the incorrect size.");
            }
            else if (rlpList.Items.Count >= 4 && !rlpList.Items[3].IsByteArray)
            {
                throw new ArgumentException("RLPx EIP8 auth packet's fourth item (version) was not a byte array.");
            }

            // Obtain all components.
            Memory <byte> signature = rlpList.Items[0];

            R         = signature.Slice(0, 32).ToArray();
            S         = signature.Slice(32, 32).ToArray();
            V         = signature.Span[64];
            PublicKey = rlpList.Items[1];
            Nonce     = rlpList.Items[2];

            // Decode version if it's available.
            if (rlpList.Items.Count >= 4)
            {
                Version = RLP.ToInteger((RLPByteArray)rlpList.Items[3], 32, false);
            }
        }
예제 #29
0
        public void ShouldEncodeEmptyString()
        {
            string test = "";

            byte[] testBytes = Encoding.UTF8.GetBytes(test);
            string expected  = "80";

            byte[] encoderesult = RLP.EncodeElement(testBytes);
            Assert.Equal(expected, encoderesult.ToHex());

            var decodeResult = RLP.Decode(encoderesult)[0].RLPData;

            Assert.Equal(null, decodeResult);
        }
예제 #30
0
        /// <summary>
        /// Parse a Receipt from the stored consensus data.
        /// </summary>
        public static Receipt FromConsensusBytesRlp(byte[] bytes)
        {
            RLPCollection innerList = (RLPCollection)RLP.Decode(bytes);

            RLPCollection innerLogList = (RLPCollection)RLP.Decode(innerList[3].RLPData);

            Log[] logs = innerLogList.Select(x => Log.FromBytesRlp(x.RLPData)).ToArray();

            return(new Receipt(
                       new uint256(innerList[0].RLPData),
                       BitConverter.ToUInt64(innerList[1].RLPData),
                       logs,
                       new Bloom(innerList[2].RLPData)
                       ));
        }