示例#1
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);
        }
示例#2
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;
            }
        }
示例#3
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);
            }
        }
示例#4
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);
        }
示例#5
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);
        }
        private static IList <byte[]> RLPDecode(byte[] remaining)
        {
            RLPCollection list = RLP.Decode(remaining);

            RLPCollection innerList = (RLPCollection)list[0];

            return(innerList.Select(x => x.RLPData).ToList());
        }
示例#7
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);
        }
        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;
        }
        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);
        }
示例#10
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
                       ));
        }
        /// <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);
        }
示例#13
0
        /// <summary>
        /// Helper function to convert RLP to byte array
        /// </summary>
        /// <param name="collection">RLP object</param>
        /// <returns></returns>
        public static byte[][] ToBytes(this RLPCollection collection)
        {
            var data = new byte[collection.Count][];

            for (var i = 0; i < collection.Count; ++i)
            {
                if (collection[i].RLPData != null)
                {
                    data[i] = new byte[collection[i].RLPData.Length];
                    collection[i].RLPData.CopyTo(data[i], 0);
                }
            }
            return(data);
        }
示例#14
0
        public void SanityTest()
        {
            // https://github.com/Nethereum/Nethereum/issues/510

            var item1 = new byte[] { 0x01 };
            var item2 = new byte[] { 0x01, 0x02 };

            byte[] encoded = RLP.EncodeList(RLP.EncodeElement(item1), RLP.EncodeElement(item2));

            RLPCollection decoded = (RLPCollection)RLP.Decode(encoded);

            // The actual list used to be at decoded[0]. Previously, these asserts would fail.
            Assert.Equal(item1, decoded[0].RLPData);
            Assert.Equal(item2, decoded[1].RLPData);
        }
示例#15
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)
                       ));
        }
        private object DeserializeStruct(Type type, byte[] bytes)
        {
            RLPCollection collection = (RLPCollection)RLP.Decode(bytes)[0];

            object ret = Activator.CreateInstance(type);

            FieldInfo[] fields = type.GetFields();

            for (int i = 0; i < fields.Length; i++)
            {
                byte[] fieldBytes = collection[i].RLPData;
                fields[i].SetValue(ret, this.Deserialize(fields[i].FieldType, fieldBytes));
            }

            return(ret);
        }
示例#17
0
        public object[] Deserialize(byte[] bytes)
        {
            RLPCollection innerList = (RLPCollection)RLP.Decode(bytes);

            IList <byte[]> encodedParamBytes = innerList.Select(x => x.RLPData).ToList();

            var results = new List <object>();

            foreach (byte[] encodedParam in encodedParamBytes)
            {
                object result = this.Decode(encodedParam);

                results.Add(result);
            }

            return(results.ToArray());
        }
示例#18
0
        public void Local_Call_Should_Produce_Logs_And_Transfers()
        {
            // Demonstrates some potentially unusual behaviour when saving contract state.
            var localExecutor = this.mockChain.Nodes[0].CoreNode.FullNode.NodeService <ILocalExecutor>();

            // Ensure fixture is funded.
            this.mockChain.MineBlocks(1);

            // Deploy contract
            ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/LocalCallTests.cs");

            Assert.True(compilationResult.Success);
            BuildCreateContractTransactionResponse preResponse = this.node1.SendCreateContractTransaction(compilationResult.Compilation, 10);

            this.mockChain.WaitAllMempoolCount(1);
            this.mockChain.MineBlocks(1);
            Assert.NotNull(this.node1.GetCode(preResponse.NewContractAddress));
            Assert.Equal(1000000000UL, this.node1.GetContractBalance(preResponse.NewContractAddress));

            uint256 currentHash = this.node1.GetLastBlock().GetHash();

            NBitcoin.Block lastBlock = this.node1.GetLastBlock();

            ReceiptResponse receipt = this.node1.GetReceipt(preResponse.TransactionId.ToString());

            Assert.True(receipt.Success);

            // Create a log in a local call
            var call            = new ContractTxData(1, 100, (Gas)250000, preResponse.NewContractAddress.ToUint160(this.node1.CoreNode.FullNode.Network), nameof(LocalCallTests.CreateLog));
            var createLogResult = localExecutor.Execute((ulong)this.node1.CoreNode.FullNode.ChainIndexer.Height, this.mockChain.Nodes[0].MinerAddress.Address.ToUint160(this.node1.CoreNode.FullNode.Network), 0, call);

            Assert.NotEmpty(createLogResult.Logs);
            RLPCollection collection = (RLPCollection)RLP.Decode(createLogResult.Logs[0].Data);
            var           loggedData = Encoding.UTF8.GetString(collection[0].RLPData);

            Assert.Equal(nameof(LocalCallTests.CreateLog), loggedData);

            // Create a transfer in a local call
            call = new ContractTxData(1, 100, (Gas)250000, preResponse.NewContractAddress.ToUint160(this.node1.CoreNode.FullNode.Network), nameof(LocalCallTests.CreateTransfer));
            var createTransferResult = localExecutor.Execute((ulong)this.node1.CoreNode.FullNode.ChainIndexer.Height, this.mockChain.Nodes[0].MinerAddress.Address.ToUint160(this.node1.CoreNode.FullNode.Network), 0, call);

            Assert.NotEmpty(createTransferResult.InternalTransfers);
            Assert.Equal(Address.Zero.ToUint160(), createTransferResult.InternalTransfers[0].To);
            Assert.Equal(1UL, createTransferResult.InternalTransfers[0].Value);
        }
        private object DeserializeArray(Type elementType, byte[] bytes)
        {
            // Edge case, serializing nonsensical
            if (elementType == typeof(byte))
            {
                return(bytes);
            }

            RLPCollection collection = (RLPCollection)RLP.Decode(bytes)[0];

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

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

            return(ret);
        }
示例#20
0
        public IRlpItem Decode(byte[] bytes)
        {
            RlpArray      rlpArray      = new RlpArray();
            RLPCollection rlpCollection = new RLPCollection();

            rlpCollection = RLP.Decode(bytes) as RLPCollection;
            this.RlpData  = rlpCollection.RLPData;
            foreach (IRLPElement item in rlpCollection)
            {
                if (item.RLPData == null || item.RLPData[0] == 0x0)
                {
                    rlpArray.Add(new RlpItem());
                    continue;
                }

                var rlpItem = new RlpItem(item.RLPData);
                rlpArray.Add(rlpItem);
            }
            return(rlpArray);
        }
示例#21
0
        public static EthECDSASignature DecodeSignature(RLPCollection decodedElements, int numberOfEncodingElements)
        {
            EthECDSASignature signature = null;

            if (decodedElements.Count > numberOfEncodingElements && decodedElements[numberOfEncodingElements + 1].RLPData != null)
            {
                var v = new byte[] { 0 };
                //Decode Signature
                if (decodedElements[numberOfEncodingElements].RLPData != null)
                {
                    v = decodedElements[numberOfEncodingElements].RLPData;
                }

                var r = decodedElements[numberOfEncodingElements + 1].RLPData;
                var s = decodedElements[numberOfEncodingElements + 2].RLPData;
                signature = EthECDSASignatureFactory.FromComponents(r, s, v);
            }

            return(signature);
        }
示例#22
0
        private T DeserializeStruct <T>(byte[] bytes) where T : struct
        {
            RLPCollection collection = (RLPCollection)RLP.Decode(bytes)[0];

            Type type = typeof(T);

            // This needs to be a boxed struct or we won't be able to set the fields with reflection.
            object instance = Activator.CreateInstance(type);

            FieldInfo[] fields = type.GetFields();

            for (int i = 0; i < fields.Length; i++)
            {
                byte[] fieldBytes = collection[i].RLPData;
                Type   fieldType  = fields[i].FieldType;
                object fieldValue = this.primitiveSerializer.Deserialize(fieldType, fieldBytes);
                fields[i].SetValue(instance, fieldValue);
            }

            return((T)instance);
        }
示例#23
0
 public static IRLPElement DecodeFirstElement(byte[] msgData, int startPos)
 {
     var rlpCollection = new RLPCollection();
     Decode(msgData, 0, startPos, startPos + 1, 1, rlpCollection);
     return rlpCollection[0];
 }
示例#24
0
        /// <summary>
        ///     Decodes a message from a starting point to an end point
        /// </summary>
        public static void Decode(byte[] msgData, int level, int startPosition,
            int endPosition, int levelToIndex, RLPCollection rlpCollection)
        {
            if ((msgData == null) || (msgData.Length == 0))
                return;

            var currentData = new byte[endPosition - startPosition];
            Array.Copy(msgData, startPosition, currentData, 0, currentData.Length);

            try
            {
                var currentPosition = startPosition;

                while (currentPosition < endPosition)
                {
                    // It's a list with a payload more than 55 bytes
                    // data[0] - 0xF7 = how many next bytes allocated
                    // for the length of the list
                    if (msgData[currentPosition] > OFFSET_LONG_LIST)
                    {
                        var lengthOfLength = (byte) (msgData[currentPosition] - OFFSET_LONG_LIST);
                        var length = CalculateLength(lengthOfLength, msgData, currentPosition);

                        var rlpDataLength = lengthOfLength + length + 1;
                        var rlpData = new byte[rlpDataLength];

                        Array.Copy(msgData, currentPosition, rlpData, 0, rlpDataLength);
                        var newLevelCollection = new RLPCollection {RLPData = rlpData};

                        Decode(msgData, level + 1, currentPosition + lengthOfLength + 1,
                            currentPosition + rlpDataLength, levelToIndex,
                            newLevelCollection);
                        rlpCollection.Add(newLevelCollection);

                        currentPosition += rlpDataLength;
                        continue;
                    }

                    // It's a list with a payload less than 55 bytes
                    if ((msgData[currentPosition] >= OFFSET_SHORT_LIST)
                        && (msgData[currentPosition] <= OFFSET_LONG_LIST))
                    {
                        var length = msgData[currentPosition] - OFFSET_SHORT_LIST;
                        var rlpDataLength = length + 1;
                        var rlpData = new byte[length + 1];

                        Array.Copy(msgData, currentPosition, rlpData, 0, rlpDataLength);

                        var newLevelCollection = new RLPCollection {RLPData = rlpData};

                        if (length > 0)
                            Decode(msgData, level + 1, currentPosition + 1, currentPosition + rlpDataLength,
                                levelToIndex,
                                newLevelCollection);

                        rlpCollection.Add(newLevelCollection);

                        currentPosition += rlpDataLength;
                        continue;
                    }
                    // It's an item with a payload more than 55 bytes
                    // data[0] - 0xB7 = how much next bytes allocated for
                    // the length of the string
                    if ((msgData[currentPosition] > OFFSET_LONG_ITEM)
                        && (msgData[currentPosition] < OFFSET_SHORT_LIST))
                    {
                        var lengthOfLength = (byte) (msgData[currentPosition] - OFFSET_LONG_ITEM);
                        var length = CalculateLength(lengthOfLength, msgData, currentPosition);

                        // now we can parse an item for data[1]..data[length]
                        var item = new byte[length];
                        Array.Copy(msgData, currentPosition + lengthOfLength + 1, item,
                            0, length);

                        var rlpPrefix = new byte[lengthOfLength + 1];
                        Array.Copy(msgData, currentPosition, rlpPrefix, 0,
                            lengthOfLength + 1);

                        var rlpItem = new RLPItem(item);
                        rlpCollection.Add(rlpItem);
                        currentPosition += lengthOfLength + length + 1;

                        continue;
                    }
                    // It's an item less than 55 bytes long,
                    // data[0] - 0x80 == length of the item
                    if ((msgData[currentPosition] > OFFSET_SHORT_ITEM)
                        && (msgData[currentPosition] <= OFFSET_LONG_ITEM))
                    {
                        var length = (byte) (msgData[currentPosition] - OFFSET_SHORT_ITEM);

                        var item = new byte[length];
                        Array.Copy(msgData, currentPosition + 1, item, 0, length);

                        var rlpPrefix = new byte[2];
                        Array.Copy(msgData, currentPosition, rlpPrefix, 0, 2);

                        var rlpItem = new RLPItem(item);
                        rlpCollection.Add(rlpItem);
                        currentPosition += 1 + length;

                        continue;
                    }
                    // null item
                    if (msgData[currentPosition] == OFFSET_SHORT_ITEM)
                    {
                        var item = EMPTY_BYTE_ARRAY;
                        var rlpItem = new RLPItem(item);
                        rlpCollection.Add(rlpItem);
                        currentPosition += 1;
                        continue;
                    }
                    // single byte item
                    if (msgData[currentPosition] < OFFSET_SHORT_ITEM)
                    {
                        byte[] item = {msgData[currentPosition]};

                        var rlpItem = new RLPItem(item);
                        rlpCollection.Add(rlpItem);
                        currentPosition += 1;
                    }
                }
            }
            catch (OutOfMemoryException ex)
            {
                throw new Exception(
                    "Invalid RLP (excessive mem allocation while parsing) " + currentData.ToHex(), ex);
            }
            catch (Exception ex)
            {
                throw new Exception(
                    "Invalid RLP " + currentData.ToHex(), ex);
            }
        }
示例#25
0
        protected static IList <byte[]> RLPDecode(byte[] remaining)
        {
            RLPCollection innerList = (RLPCollection)RLP.Decode(remaining);

            return(innerList.Select(x => x.RLPData).ToList());
        }
示例#26
0
        public static string ParseEthereumTransaction(EthereumTransactionInfo info, byte[] input)
        {
            string htmlOutput = "";
            string details    = "";

            Dictionary <int, string> chainIDDict = new Dictionary <int, string>()
            {
                { 1, "Ethereum mainnet" },
                { 2, "Morden(disused), Expanse mainnet" },
                { 3, "Ropsten" },
                { 4, "Rinkeby" },
                { 30, "Rootstock mainnet" },
                { 31, "Rootstock testnet" },
                { 42, "Kovan" },
                { 61, "Ethereum Classic mainnet" },
                { 62, "Ethereum Classic testnet" },
                { 1337, "Geth private chains (default)" },
            };

            if (info.transactionTooBigToDisplay == true)
            {
                throw new EthParserException("Transaction too big to display.");
            }

            if (info.type == 0x6666)
            {
                throw new EthParserException("A message is being signed. Cannot display.");
            }
            else
            {
                RLPCollection collection = RLP.Decode(input);

                if (collection.Count != 1)
                {
                    throw new EthParserException("Invalid transaction.");
                }

                collection = (RLPCollection)collection[0];

                if (collection.Count != 9)
                {
                    throw new EthParserException("Invalid transaction.");
                }

                string fromAddress = "0x" + string.Join(string.Empty, Array.ConvertAll(info.address, b => b.ToString("x2")));

                string nonce = new BigInteger(collection[0].RLPData).ToString(10);

                string gasPrice                = "";
                var    gasPriceInGwei          = new BigInteger(collection[1].RLPData).DivideAndRemainder(new BigInteger("1000000000"));
                var    gasPriceInGweiRemainder = gasPriceInGwei[1].ToString(10).PadLeft(9, '0').TrimEnd('0');

                if (gasPriceInGweiRemainder == "")
                {
                    gasPrice = gasPriceInGwei[0].ToString(10) + " GWEI";
                }
                else
                {
                    gasPrice = gasPriceInGwei[0].ToString(10) + "." + gasPriceInGweiRemainder + " GWEI";
                }

                string gasLimit  = new BigInteger(collection[2].RLPData).ToString(10);
                string toAddress = "0x" + string.Join(string.Empty, Array.ConvertAll(collection[3].RLPData, b => b.ToString("x2")));

                string value               = "";
                var    valueInEth          = new BigInteger(collection[4].RLPData).DivideAndRemainder(new BigInteger("1000000000000000000"));
                var    valueInEthRemainder = valueInEth[1].ToString(10).PadLeft(18, '0').TrimEnd('0');

                if (valueInEthRemainder == "")
                {
                    value = valueInEth[0].ToString(10) + " ETH";
                }
                else
                {
                    value = valueInEth[0].ToString(10) + "." + valueInEthRemainder + " ETH";
                }



                string data = "None";
                if (collection[5].RLPData != null)
                {
                    data = "0x" + string.Join(string.Empty, Array.ConvertAll(collection[5].RLPData, b => b.ToString("x2")));
                }

                int v = collection[6].RLPData.ToIntFromRLPDecoded();

                string chainID = "";

                if (chainIDDict.ContainsKey(v))
                {
                    chainID = chainIDDict[v];
                }
                else
                {
                    chainID = v.ToString();
                }

                if ((collection[7].RLPData != null) || (collection[8].RLPData != null))
                {
                    throw new EthParserException("Invalid transaction.");
                }

                details += "<b>Send to: </b>" + toAddress + "<br>";
                details += "<b>Send from: </b>" + fromAddress + "<br>";
                details += "<b>Value: </b>" + value + "<br>";
                details += "<b>ChainID: </b>" + chainID + "<br>";
                details += "<b>Gas limit: </b>" + gasLimit + "<br>";
                details += "<b>Gas price: </b>" + gasPrice + "<br>";
                details += "<b>Nonce: </b>" + nonce + "<br>";
                details += "<b>Data: </b>" + data + "<br><br>";
            }

            htmlOutput += details;

            htmlOutput += "Time remaining to confirm: <b>" + (info.remainingTime / 1000).ToString() + "</b> seconds. <br><br>";

            return(htmlOutput);
        }
示例#27
0
 /// <summary>
 /// Get a node from a parsed RLP object
 /// </summary>
 public Node(RLPCollection parsedRlp, PatriciaTrie trie)
 {
     this.parsedRlp = parsedRlp;
     this.rlp       = parsedRlp.RLPData;
     this.trie      = trie;
 }
示例#28
0
 /// <summary>
 ///     Parses byte[] message into RLP items
 /// </summary>
 /// <param name="msgData">raw RLP data </param>
 /// <returns> RlpList: outcome of recursive RLP structure </returns>
 public static RLPCollection Decode(byte[] msgData)
 {
     var rlpCollection = new RLPCollection();
     Decode(msgData, 0, 0, msgData.Length, 1, rlpCollection);
     return rlpCollection;
 }