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"); } }
/// <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); }
/// <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); }
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); } }
/// <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 ..."); } }
/// <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); }
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; } }
/// <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)); } }
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 Account(Configuration.Configuration configuration, byte[] rlpData) { // Set our configuration Configuration = configuration; // Deserialize our decoded RLP data. Deserialize(RLP.Decode(rlpData)); }
private static IList <byte[]> RLPDecode(byte[] remaining) { RLPCollection list = RLP.Decode(remaining); RLPCollection innerList = (RLPCollection)list[0]; return(innerList.Select(x => x.RLPData).ToList()); }
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); }
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; }
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()); }
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)); }
/// <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))); }
public void DecodeStaticString() { var input = "f902d6819a8702288058b9af928202d0f90273e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f8000080e094d3ef28df6b553ed2fc47259e8134319cb1121a2a89364200111c48f800008001830616988088ff9198c817655decc0b841bd61e198f126adddb169eebf5cd3da25ae3a3f07102e574bcd1368440d1e307c4c47884364e2abc66ef6940c4953758dd1c57f8255025639702104ce83e9a3b501"; var rlpList = RlpDecoder.Decode(input.HexStringToByteArray()); var nethereumRLP = RLP.Decode(input.HexStringToByteArray()); Assert.True(RlpCompare(rlpList, nethereumRLP)); }
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)); }
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 }; }
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 )); }
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()); } }
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)); }
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); }
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()); }
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); } }
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); }
/// <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) )); }