Exemple #1
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);
        }
Exemple #2
0
        /// <summary>
        /// Serializes a receipt without including the method name. For backwards compatibility testing.
        /// </summary>
        /// <param name="receipt"></param>
        /// <returns></returns>
        public byte[] ToStorageBytesRlp_NoMethodName(Receipt receipt)
        {
            IList <byte[]> encodedLogs = receipt.Logs.Select(x => RLP.EncodeElement(x.ToBytesRlp())).ToList();

            return(RLP.EncodeList(
                       RLP.EncodeElement(receipt.PostState.ToBytes()),
                       RLP.EncodeElement(BitConverter.GetBytes(receipt.GasUsed)),
                       RLP.EncodeElement(receipt.Bloom.ToBytes()),
                       RLP.EncodeElement(RLP.EncodeList(encodedLogs.ToArray())),
                       RLP.EncodeElement(receipt.TransactionHash.ToBytes()),
                       RLP.EncodeElement(receipt.BlockHash.ToBytes()),
                       RLP.EncodeElement(receipt.From.ToBytes()),
                       RLP.EncodeElement(receipt.To?.ToBytes()),
                       RLP.EncodeElement(receipt.NewContractAddress?.ToBytes()),
                       RLP.EncodeElement(BitConverter.GetBytes(receipt.Success)),
                       RLP.EncodeElement(Encoding.UTF8.GetBytes(receipt.Result ?? "")),
                       RLP.EncodeElement(Encoding.UTF8.GetBytes(receipt.ErrorMessage ?? "")),
                       RLP.EncodeElement(BitConverter.GetBytes(receipt.GasPrice)),
                       RLP.EncodeElement(BitConverter.GetBytes(receipt.Amount))
                       ));
        }
Exemple #3
0
        public byte[] ReadStorage(byte[] key)
        {
            // If we already have cached storage data, return it. Otherwise we'll need to cache some.
            if (!StorageCache.TryGetValue(key, out var val))
            {
                // We obtain the value from our storage trie, cache it, and decode it, as it's RLP encoded.
                byte[] value = StorageTrie.Get(key);
                if (value == null)
                {
                    val = null;
                }
                else
                {
                    val = RLP.Decode(value);
                }

                StorageCache[key] = val;
            }

            // Return our storage key.
            return(val);
        }
Exemple #4
0
        /// <summary>
        /// Serializes the transaction into an RLP item for encoding.
        /// </summary>
        /// <returns>Returns a serialized RLP transaction.</returns>
        public static RLPItem Serialize(byte?v, BigInteger?r, BigInteger?s, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, Address?to, BigInteger value, byte[] data)
        {
            // We create a new RLP list that constitute this transaction.
            RLPList rlpTransaction = new RLPList();

            // Add our values
            rlpTransaction.Items.Add(RLP.FromInteger(nonce, 32, true));
            rlpTransaction.Items.Add(RLP.FromInteger(gasPrice, 32, true));
            rlpTransaction.Items.Add(RLP.FromInteger(gasLimit, 32, true));

            if (to != null)
            {
                rlpTransaction.Items.Add(new RLPByteArray(to.Value.GetBytes()));
            }
            else
            {
                rlpTransaction.Items.Add(new RLPByteArray(Array.Empty <byte>()));
            }

            rlpTransaction.Items.Add(RLP.FromInteger(value, 32, true));
            rlpTransaction.Items.Add(data);
            if (v != null)
            {
                rlpTransaction.Items.Add(v);
            }

            if (r != null)
            {
                rlpTransaction.Items.Add(RLP.FromInteger(r.Value, 32, true));
            }

            if (s != null)
            {
                rlpTransaction.Items.Add(RLP.FromInteger(s.Value, 32, true));
            }

            // Return our rlp log item.
            return(rlpTransaction);
        }
Exemple #5
0
        private byte[] SerializeCreateContract(ContractTxData contractTxData)
        {
            var rlpBytes = new List <byte[]>();

            rlpBytes.Add(contractTxData.ContractExecutionCode);

            this.AddMethodParams(rlpBytes, contractTxData.MethodParameters);
            if (contractTxData.Signatures != null)
            {
                this.AddSignatures(rlpBytes, contractTxData.Signatures);
            }

            byte[] encoded = RLP.EncodeList(rlpBytes.Select(RLP.EncodeElement).ToArray());

            var bytes = new byte[PrefixSize + encoded.Length];

            this.SerializePrefix(bytes, contractTxData);

            encoded.CopyTo(bytes, PrefixSize);

            return(bytes);
        }
Exemple #6
0
        static void Configure()
        {
            try
            {
                LoadRLP();

                // Blink board LED
                RLP.Procedure PwmStop  = RLP.GetProcedure(elfImage, "PwmStop");
                RLP.Procedure PWMStart = RLP.GetProcedure(elfImage, "PWMRun");

                PwmStop.Invoke();

                if (currentEnergyMode == ScanEnergyMode.Dual)
                {
                    Reset.Write(true);
                    Preset.Write(true);
                }
                else if (currentEnergyMode == ScanEnergyMode.High)
                {
                    Reset.Write(true);
                    Preset.Write(false);
                }
                else
                {
                    Reset.Write(false);
                    Preset.Write(true);
                }

                RLP.Procedure PWMBlink = RLP.GetProcedure(elfImage, "PWMBlink");

                pc.Initialize(elfImage);

                PWMBlink.Invoke(currentStaticPulseFreq, PulseWidthsDutyCycle[(int)currentPulseWidth - 1], 1);

                PWMStart.Invoke();
            }
            catch { }
            finally { UnloadRLP(); }
        }
Exemple #7
0
        public byte[] ToBytes()
        {
            var a = new List <byte[]>
            {
                _previousAttendance.Count.ToBytes().ToArray(),
                PreviousCycleNum.ToBytes().ToArray()
            };

            foreach (var(publicKey, attendance) in _previousAttendance)
            {
                a.Add(publicKey.HexToBytes());
                a.Add(attendance.ToBytes().ToArray());
            }

            foreach (var(publicKey, attendance) in _nextAttendance)
            {
                a.Add(publicKey.HexToBytes());
                a.Add(attendance.ToBytes().ToArray());
            }

            return(RLP.EncodeList(a.Select(RLP.EncodeElement).ToArray()));
        }
        public virtual void RlpDecode()
        {
            var decodedTxList = RLP.Decode(rlpEncoded);
            var transaction   = (RLPCollection)decodedTxList[0];

            nonce          = transaction[0].RLPData;
            gasPrice       = transaction[1].RLPData;
            gasLimit       = transaction[2].RLPData;
            receiveAddress = transaction[3].RLPData;
            value          = transaction[4].RLPData;
            data           = transaction[5].RLPData;
            // only parse signature in case tx is signed
            if (transaction[6].RLPData != null)
            {
                var v = transaction[6].RLPData[0];
                var r = transaction[7].RLPData;
                var s = transaction[8].RLPData;

                signature = EthECDSASignatureFactory.FromComponents(r, s, v);
            }
            decoded = true;
        }
        public byte[] BuildRLPEncoded(bool raw)
        {
            byte[] nonce = null;
            if (this.nonce == null || this.nonce.Length == 1 && this.nonce[0] == 0)
            {
                nonce = RLP.EncodeElement(null);
            }
            else
            {
                nonce = RLP.EncodeElement(this.nonce);
            }
            var gasPrice       = RLP.EncodeElement(this.gasPrice);
            var gasLimit       = RLP.EncodeElement(this.gasLimit);
            var receiveAddress = RLP.EncodeElement(this.receiveAddress);
            var value          = RLP.EncodeElement(this.value);
            var data           = RLP.EncodeElement(this.data);

            if (raw)
            {
                return(RLP.EncodeList(nonce, gasPrice, gasLimit, receiveAddress, value, data));
            }
            byte[] v, r, s;

            if (signature != null)
            {
                v = RLP.EncodeByte(signature.V);
                r = RLP.EncodeElement(signature.R.ToByteArrayUnsigned());
                s = RLP.EncodeElement(signature.S.ToByteArrayUnsigned());
            }
            else
            {
                v = RLP.EncodeElement(EMPTY_BYTE_ARRAY);
                r = RLP.EncodeElement(EMPTY_BYTE_ARRAY);
                s = RLP.EncodeElement(EMPTY_BYTE_ARRAY);
            }

            return(RLP.EncodeList(nonce, gasPrice, gasLimit, receiveAddress, value, data, v, r, s));
        }
        private void EncodeMessage()
        {
            var code    = RLP.Encode(((int)this.MessageCode).ToBytes());
            var version = RLP.Encode(this.p2pVersion.ToBytes());
            var client  = RLP.Encode(this.clientId.ToBytes());

            //var capabilities = new List<dynamic>(this.supportedCapabilities.Count);
            //capabilities.AddRange(this.supportedCapabilities.Select(capability => new List<string>
            //    {
            //        capability.Name,
            //        capability.Version.ToString(CultureInfo.InvariantCulture)
            //    }));

            //var capabilities = new byte[this.supportedCapabilities.Count][];
            //for (var i = 0; i < this.supportedCapabilities.Count(); i++)
            //{
            //    var capability = this.supportedCapabilities[i];
            //    capabilities[i] = RLP.Encode(new List<dynamic>
            //        {
            //            capability.Name,
            //            capability.Version.ToString(CultureInfo.InvariantCulture)
            //        });
            //}

            //var caps = RLP.Encode(capabilities);
            var port = RLP.Encode(this.defaultPort.ToBytes());
            var peer = RLP.Encode(this.peerId.ToBytes());

            this.encodedMessage = new List <byte[]>
            {
                code,
                version,
                client,
                //caps,
                port,
                peer
            }.SelectMany(x => x).ToArray();
        }
        /// <summary>
        /// Serialize a receipt into bytes to be stored.
        /// </summary>
        public byte[] ToStorageBytesRlp()
        {
            IList <byte[]> encodedLogs = this.Logs.Select(x => RLP.EncodeElement(x.ToBytesRlp())).ToList();

            return(RLP.EncodeList(
                       RLP.EncodeElement(this.PostState.ToBytes()),
                       RLP.EncodeElement(BitConverter.GetBytes(this.GasUsed)),
                       RLP.EncodeElement(this.Bloom.ToBytes()),
                       RLP.EncodeElement(RLP.EncodeList(encodedLogs.ToArray())),
                       RLP.EncodeElement(this.TransactionHash.ToBytes()),
                       RLP.EncodeElement(this.BlockHash.ToBytes()),
                       RLP.EncodeElement(this.From.ToBytes()),
                       RLP.EncodeElement(this.To?.ToBytes()),
                       RLP.EncodeElement(this.NewContractAddress?.ToBytes()),
                       RLP.EncodeElement(BitConverter.GetBytes(this.Success)),
                       RLP.EncodeElement(Encoding.UTF8.GetBytes(this.Result ?? "")),
                       RLP.EncodeElement(Encoding.UTF8.GetBytes(this.ErrorMessage ?? "")),
                       RLP.EncodeElement(BitConverter.GetBytes(this.GasPrice)),
                       RLP.EncodeElement(BitConverter.GetBytes(this.Amount)),
                       RLP.EncodeElement(Encoding.UTF8.GetBytes(this.MethodName ?? "")),
                       RLP.EncodeElement(this.BlockNumber.HasValue ? BitConverter.GetBytes(this.BlockNumber.Value) : null)
                       ));
        }
Exemple #12
0
        /// </summary>
        /// <param name="elfImage">elf image library</param>
        public void Initialize(byte[] elfImage)
        {
            // Load procedures
            initProcedure        = RLP.GetProcedure(elfImage, "Init");
            deinitProcedure      = RLP.GetProcedure(elfImage, "Deinit");
            queryProcedure       = RLP.GetProcedure(elfImage, "Query");
            updateFreqProcedure  = RLP.GetProcedure(elfImage, "PWMUpdateFreq");
            updatePulseProcedure = RLP.GetProcedure(elfImage, "PWMUpdatePulse");
            resetProcedure       = RLP.GetProcedure(elfImage, "WDReset");
            stopProcedure        = RLP.GetProcedure(elfImage, "PwmStop");
            startProcedure       = RLP.GetProcedure(elfImage, "PWMRun");
            PWMStatusProcedure   = RLP.GetProcedure(elfImage, "QueryPWMStatus");

            // Init RLP driver
            if (initProcedure.Invoke() != 0)
            {
                throw new Exception("Driver initialisation failed");
            }

            // Start thread
            thread = new Thread(ThreadProc);
            thread.Start();
        }
Exemple #13
0
        public void CommitStorageChanges()
        {
            // For each storage cache item, we want to flush those changes to the main trie/database.
            foreach (var key in StorageCache.Keys)
            {
                // If the value is null, it means the value is non existent anymore, so we remove the key value pair
                if (StorageCache[key] == null)
                {
                    StorageTrie.Remove(key);
                }
                else
                {
                    // Otherwise we set the new value.
                    StorageTrie.Set(key, RLP.Encode(StorageCache[key]));
                }
            }

            // Now we clear our cache.
            StorageCache.Clear();

            // And update our account's storage root hash.
            StorageRoot = StorageTrie.GetRootNodeHash();
        }
        /// <inheritdoc/>
        public byte[] EncodeSigned(Transaction transaction)
        {
            var rlpcollection = new List <byte[]>();

            var rlpSignatures = new List <byte[]>();

            for (Int32 i = 0; i < transaction.Inputs.Count; ++i)
            {
                if (transaction.Signatures[i] != null)
                {
                    rlpSignatures.Add(RLP.EncodeElement(transaction.Signatures[i]));
                }
                else
                {
                    // missing signature - cannot return valid encoded transaction
                    return(new byte[0]);
                }
            }

            rlpcollection.Add(RLP.EncodeList(rlpSignatures.ToArray()));

            var rlpInputs = new List <byte[]>();

            transaction.Inputs.ForEach(x => rlpInputs.Add(x.GetRLPEncoded()));
            rlpInputs.AddRange(Enumerable.Repeat(new TransactionInputData().GetRLPEncoded(), MAX_INPUTS - transaction.Inputs.Count));
            rlpcollection.Add(RLP.EncodeList(rlpInputs.ToArray()));

            var rlpOutputs = new List <byte[]>();

            transaction.Outputs.ForEach(x => rlpOutputs.Add(x.GetRLPEncoded()));
            rlpOutputs.AddRange(Enumerable.Repeat(new TransactionOutputData().GetRLPEncoded(), MAX_OUTPUTS - transaction.Outputs.Count));
            rlpcollection.Add(RLP.EncodeList(rlpOutputs.ToArray()));

            rlpcollection.Add(RLP.EncodeElement(transaction.Metadata));

            return(RLP.EncodeList(rlpcollection.ToArray()));
        }
Exemple #15
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>;

            instance["Event"] = type.Name;

            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);
        }
Exemple #16
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-ack packet's first item (ephemeral public key) was not a byte array.");
            }
            else if (((byte[])rlpList.Items[0]).Length != EthereumEcdsa.PUBLIC_KEY_SIZE)
            {
                throw new ArgumentException("RLPx EIP8 auth-ack packet's first item (ephemeral public key) was not the correct size.");
            }
            else if (!rlpList.Items[1].IsByteArray)
            {
                throw new ArgumentException("RLPx EIP8 auth-ack packet's second item (nonce) was not a byte array.");
            }
            else if (((byte[])rlpList.Items[1]).Length != RLPxSession.NONCE_SIZE)
            {
                throw new ArgumentException("RLPx EIP8 auth-ack packet's second item (nonce) was not the correct size.");
            }
            else if (rlpList.Items.Count >= 3 && !rlpList.Items[2].IsByteArray)
            {
                throw new ArgumentException("RLPx EIP8 auth-ack packet's third item (version) was not a byte array.");
            }

            // Obtain all components.
            EphemeralPublicKey = rlpList.Items[0];
            Nonce = rlpList.Items[1];

            // Decode version if it's available.
            if (rlpList.Items.Count >= 3)
            {
                Version = RLP.ToInteger((RLPByteArray)rlpList.Items[2], 32, false);
            }
        }
        public static void Main()
        {
            RLP.Enable();
            // Unlock RLP
            RLP.Unlock("[email protected]", new byte[] { 0x60, 0xEE, 0xDB, 0x53, 0x8A, 0x31, 0x71, 0x34, 0xAE, 0xB5, 0x6A, 0x4A, 0xA8, 0x54, 0x10, 0xA4, 0x67, 0x24, 0xFA, 0x0B, 0x8A, 0x4C, 0x8A, 0x78, 0x27, 0x1F, 0xBF, 0x59, 0xC3, 0x21, 0x54, 0x1A });
            Debug.EnableGCMessages(false);

            Debug.GC(true);
            byte[] elf_file = Resources.GetBytes(Resources.BinaryResources.RLP_test);
            RLP.LoadELF(elf_file);

            RLP.InitializeBSSRegion(elf_file);

            rlpInit  = RLP.GetProcedure(elf_file, "Init");
            rlpStop  = RLP.GetProcedure(elf_file, "Stop");
            rlpStart = RLP.GetProcedure(elf_file, "Start");
            elf_file = null;
            Debug.GC(true);

            //sets up all analog pins as reading, and pwm pins as pwms
            for (int i = 0; i < 6; i++)
            {
                new AnalogIn((AnalogIn.Pin)i);
                new PWM((PWM.Pin)i + 1);
            }

            dataPort = new SerialPort("COM2", 57600, System.IO.Ports.Parity.None, 8, StopBits.One);
            dataPort.Open();
            dataPort.DataReceived += new SerialDataReceivedEventHandler(dataPort_DataReceived); //open before attaching the event - due to bug in framework
            //found at http://tinyclr.com/forum/2/4426/

            Thread.Sleep(2000); //this makes it easier to install new stuff if anything crashes

            rlpInit.Invoke();
            Thread.Sleep(Timeout.Infinite);
        }
Exemple #18
0
        private byte[] SerializeCallContract(ContractTxData contractTxData)
        {
            var rlpBytes = new List <byte[]>();

            rlpBytes.Add(this.primitiveSerializer.Serialize(contractTxData.MethodName));

            this.AddMethodParams(rlpBytes, contractTxData.MethodParameters);
            if (contractTxData.Signatures != null)
            {
                this.AddSignatures(rlpBytes, contractTxData.Signatures);
            }

            byte[] encoded = RLP.EncodeList(rlpBytes.Select(RLP.EncodeElement).ToArray());

            var bytes = new byte[CallContractPrefixSize + encoded.Length];

            this.SerializePrefix(bytes, contractTxData);

            contractTxData.ContractAddress.ToBytes().CopyTo(bytes, PrefixSize);

            encoded.CopyTo(bytes, CallContractPrefixSize);

            return(bytes);
        }
Exemple #19
0
        public byte[] Serialize()
        {
            var transactionByteList = new List <byte[]>();

            foreach (var transaction in Transactions)
            {
                transactionByteList.Add(transaction.Serialize());
            }

            var serializedTransactions = RLP.Encode(transactionByteList);

            var block = new byte[][]
            {
                ByteManipulator.GetBytes((uint)Height),
                ByteManipulator.GetBytes(Timestamp),
                Difficulty.GetBytes(),
                Nonce,
                MinerAddress,
                PreviousBlockHash,
                serializedTransactions
            };

            return(RLP.Encode(block));
        }
Exemple #20
0
        /// <summary>
        /// Serializes the log into an RLP item for encoding.
        /// </summary>
        /// <returns>Returns a serialized RLP log.</returns>
        public RLPItem Serialize()
        {
            // We create a new RLP list that constitute this log.
            RLPList rlpLog = new RLPList();

            // Add our address
            rlpLog.Items.Add(RLP.FromInteger(Address, Address.ADDRESS_SIZE));

            // Add our topics, a list of 32-bit integers.
            RLPList rlpTopicsList = new RLPList();

            foreach (BigInteger topic in Topics)
            {
                rlpTopicsList.Items.Add(RLP.FromInteger(topic, EVMDefinitions.WORD_SIZE));
            }

            rlpLog.Items.Add(rlpTopicsList);

            // Add our data
            rlpLog.Items.Add(Data);

            // Return our rlp log item.
            return(rlpLog);
        }
Exemple #21
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;

            // Block number is the 16th item to be added.
            var hasBlockNumber = innerList.Count > 15;

            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,
                hasBlockNumber && innerList[15].RLPData != null ? BitConverter.ToUInt64(innerList[15].RLPData) : (ulong?)null);

            return(receipt);
        }
Exemple #22
0
        private void RLPListEncodeDecodeTest(int items)
        {
            RLPList list = new RLPList();

            for (int i = 0; i < items; i++)
            {
                if (i % 2 == 0)
                {
                    list.Items.Add(new byte[] { (byte)(i % 256) });
                }
                else
                {
                    list.Items.Add(new RLPList());
                }
            }

            byte[]  encoded = RLP.Encode(list);
            RLPList list2   = (RLPList)RLP.Decode(encoded);

            Assert.Equal(list.Items.Count, list2.Items.Count);

            for (int i = 0; i < list.Items.Count; i++)
            {
                if (i % 2 == 0)
                {
                    Assert.IsType <RLPByteArray>(list2.Items[i]);
                    RLPByteArray b1 = ((RLPByteArray)list.Items[i]);
                    RLPByteArray b2 = ((RLPByteArray)list2.Items[i]);
                    Assert.True(MemoryExtensions.SequenceEqual(b1.Data.Span, b2.Data.Span));
                }
                else
                {
                    Assert.IsType <RLPList>(list2.Items[i]);
                }
            }
        }
Exemple #23
0
        public IRlpItem Decode(byte[] bytes)
        {
            IRLPElement rLPElement = RLP.Decode(bytes);

            return(new RlpItem(rLPElement.RLPData));
        }
Exemple #24
0
 public void ImplicitEncoding_NegativeInt()
 {
     Assert.ThrowsAny <Exception>(() => RLP.Encode(-1234));
 }
Exemple #25
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);
        }
Exemple #26
0
        private byte[] Encode(int depth, bool forceHash)
        {
            if (!dirty)
            {
                return(hash != null?RLP.EncodeElement(hash) : rlp);
            }
            else
            {
                TrieNodeType type = this.node_type;
                byte[]       ret;
                if (type == TrieNodeType.BranchNode)
                {
                    if (depth == 1 && this.reference.Async)
                    {
                        // parallelize encode() on the first trie level only and if there are at least
                        // MIN_BRANCHES_CONCURRENTLY branches are modified
                        object[] encoded      = new object[17];
                        int      encode_count = 0;
                        for (int i = 0; i < 16; i++)
                        {
                            TrieNode child = BranchNodeGetChild(i);
                            if (child == null)
                            {
                                encoded[i] = RLP.EMPTY_ELEMENT_RLP;
                            }
                            else if (!child.dirty)
                            {
                                encoded[i] = child.Encode(depth + 1, false);
                            }
                            else
                            {
                                encode_count++;
                            }
                        }
                        for (int i = 0; i < 16; i++)
                        {
                            if (encoded[i] == null)
                            {
                                TrieNode child = BranchNodeGetChild(i);
                                if (child == null)
                                {
                                    continue;
                                }
                                if (encode_count >= MIN_BRANCHES_CONCURRENTLY)
                                {
                                    encoded[i] = Task.Run <byte[]>(() =>
                                    {
                                        return(child.Encode(depth + 1, false));
                                    });
                                }
                                else
                                {
                                    encoded[i] = child.Encode(depth + 1, false);
                                }
                            }
                        }
                        byte[] value = BranchNodeGetValue();
                        encoded[16] = RLP.EncodeElement(value);
                        try
                        {
                            ret = EncodeRlpListTaskResult(encoded);
                        }
                        catch (System.Exception e)
                        {
                            throw new System.Exception(e.Message);
                        }
                    }
                    else
                    {
                        byte[][] encoded = new byte[17][];
                        for (int i = 0; i < 16; i++)
                        {
                            TrieNode child = BranchNodeGetChild(i);
                            encoded[i] = child == null ? RLP.EMPTY_ELEMENT_RLP : child.Encode(depth + 1, false);
                        }
                        byte[] value = BranchNodeGetValue();
                        encoded[16] = RLP.EncodeElement(value);
                        ret         = RLP.EncodeList(encoded);
                    }
                }
                else if (type == TrieNodeType.KVNodeNode)
                {
                    ret = RLP.EncodeList(RLP.EncodeElement(KVNodeGetKey().ToPacked()),
                                         KVNodeGetChildNode().Encode(depth + 1, false));
                }
                else
                {
                    byte[] value = KVNodeGetValue();
                    ret = RLP.EncodeList(RLP.EncodeElement(KVNodeGetKey().ToPacked()),
                                         RLP.EncodeElement(value == null ? new byte[0] : value));
                }
                if (this.hash != null)
                {
                    this.reference.DeleteHash(this.hash);
                }

                this.dirty = false;
                if (ret.Length < 32 && !forceHash)
                {
                    this.rlp = ret;
                    return(ret);
                }
                else
                {
                    this.hash = ret.SHA3();
                    this.reference.AddHash(this.hash, ret);
                    return(RLP.EncodeElement(hash));
                }
            }
        }
Exemple #27
0
 public byte[] Encode()
 {
     return(RLP.EncodeElement(this.RlpData));
 }
Exemple #28
0
        public string ToSignedHex(string _private)
        {
            byte[] _basicRaw = RLP.EncodeList(new byte[][] {
                RLP.EncodeUInt(this.Nonce),
                RLP.EncodeBigInteger(this.GasPrice.ToGWei()),
                RLP.EncodeUInt(this.GasLimit),
                RLP.EncodeHex(this.Address),
                RLP.EncodeBigInteger(this.Value.Integer),
                RLP.EncodeString(this.DataHex),
                RLP.EncodeInt((int)this.ChainId),
                RLP.EncodeString(""),
                RLP.EncodeString("")
            });

            byte[] _basicHashedRaw = new Keccak256().Compute(_basicRaw);

            BigInteger _limit = BigInteger.Pow(BigInteger.Parse("2"), 256),
                       _r     = BigInteger.Zero,
                       _e     = BigInteger.Zero,
                       _s     = BigInteger.Zero,
                       _k     = BigInteger.Zero,
                       _recid = BigInteger.Zero;

            while (true)
            {
                _k = BigInteger.Zero;
                if (_k == BigInteger.Zero)
                {
                    byte[] kBytes = new byte[33];
                    rngCsp.GetBytes(kBytes);
                    kBytes[32] = 0;
                    _k         = new BigInteger(kBytes);
                }
                if (_k.IsZero || _k >= Secp256k1.N)
                {
                    continue;
                }

                var _gk = Secp256k1.G.Multiply(_k);
                _r     = _gk.X % Secp256k1.N;
                _recid = _gk.Y & 1;
                if (_r == BigInteger.Zero)
                {
                    throw new Exception("Sign failed because R is Zero.");
                }
                if (_r >= _limit || _r.Sign == 0)
                {
                    Thread.Sleep(100); continue;
                }
                _e = Lion.BigNumberPlus.HexToBigInt(BitConverter.ToString(_basicHashedRaw).Replace("-", ""));
                _s = ((_e + (_r * Lion.BigNumberPlus.HexToBigInt(_private))) * BigInteger.ModPow(_k, Secp256k1.N - 2, Secp256k1.N)) % Secp256k1.N;
                if (_s == BigInteger.Zero)
                {
                    throw new Exception("Sign failed because S is Zero.");
                }
                if (_s > Secp256k1.HalfN)
                {
                    _recid = _recid ^ 1;
                }
                if (_s.CompareTo(Secp256k1.HalfN) > 0)
                {
                    _s = Secp256k1.N - _s;
                }
                if (_s >= _limit || _s.Sign == 0 || _r.ToString("X").StartsWith("0") || _s.ToString("X").StartsWith("0"))
                {
                    Thread.Sleep(100); continue;
                }
                break;
            }
            BigInteger _v = BigInteger.Parse(((int)this.ChainId).ToString()) * 2 + _recid + 35;

            byte[] _signed = RLP.EncodeList(new byte[][] {
                RLP.EncodeUInt(this.Nonce),
                RLP.EncodeBigInteger(this.GasPrice.ToGWei()),
                RLP.EncodeUInt(this.GasLimit),
                RLP.EncodeHex(this.Address),
                RLP.EncodeBigInteger(this.Value.Integer),
                RLP.EncodeString(this.DataHex),
                RLP.EncodeBigInteger(_v),
                RLP.EncodeBytes(HexPlus.HexStringToByteArray(_r.ToString("X"))),
                RLP.EncodeBytes(HexPlus.HexStringToByteArray(_s.ToString("X")))
            });

            return(HexPlus.ByteArrayToHexString(_signed).ToLower());
        }
Exemple #29
0
        public static void Init(out RLP.Procedure lcdInit, out RLP.Procedure lcdSet, byte[] loadPlugin = null)
        {
            if (initialized)
            {
                throw new Exception("Already initialized");
            }

            //NOTE: use your own unlock code
            RLP.Unlock("[email protected]", new byte[]
            {
                0xFB, 0xCC, 0x7D, 0xDA, 0x8E, 0x87, 0x58, 0xAB,
                0x95, 0x8E, 0x68, 0x02, 0x1F, 0xE6, 0xD6, 0x14,
                0x3C, 0xBD, 0x3E, 0xD1, 0xBE, 0xF0, 0xCE, 0xFB,
                0x1D, 0xD9, 0xC4, 0xEC, 0xE2, 0x2A, 0xFD, 0xCD
            });

            byte[] elf_file = Extension.GetBytes(Extension.BinaryResources.Extension);
            RLP.LoadELF(elf_file);
            RLP.InitializeBSSRegion(elf_file);
            RLP.Procedure VsInit = RLP.GetProcedure(elf_file, "VsInit");
            vsStreamData       = RLP.GetProcedure(elf_file, "VsStreamData");
            vsNoMoreData       = RLP.GetProcedure(elf_file, "VsNoMoreData");
            vsLoadPlugin       = RLP.GetProcedure(elf_file, "VsLoadPluginFromArray");
            vsSetVolume        = RLP.GetProcedure(elf_file, "VsSetVolume");
            vsSetBassAndTreble = RLP.GetProcedure(elf_file, "VsSetBassAndTreble");

            lcdInit = RLP.GetProcedure(elf_file, "LcdInit");
            lcdSet  = RLP.GetProcedure(elf_file, "LcdSetLevel");

            elf_file = null;

            int result;

            if ((result = loadPlugin == null ? VsInit.Invoke() : VsInit.InvokeEx(loadPlugin, loadPlugin.Length)) != 0)
            {
                throw new Exception("Could not init VS Driver. Reason " + result.ToString());
            }
            loadedPlugin = loadPlugin;

            RLP.RLPEvent += (data, time) =>
            {
                switch (data)
                {
                case 0x01:
                    //data was streamed
                    wait.Set();     //notify any waiter
                    break;

                case 0x02:
                    //error when closing stream
                    //this means the VS was reseted,
                    //reload plugin, set volume, bass and treble
                    if (loadedPlugin != null)
                    {
                        vsLoadPlugin.InvokeEx(loadedPlugin, loadedPlugin.Length);
                    }
                    RaiseException("Error closing stream!");
                    break;
                }
            };
            initialized = true;

            balanceGeneral = 0;
            Volume         = 255; //max volume
            trebleGeneral  = 0;
            bassGeneral    = 0;
        }
Exemple #30
0
        protected static IList <byte[]> RLPDecode(byte[] remaining)
        {
            RLPCollection innerList = (RLPCollection)RLP.Decode(remaining);

            return(innerList.Select(x => x.RLPData).ToList());
        }
        public static void Init(out RLP.Procedure lcdInit, out RLP.Procedure lcdSet, byte[] loadPlugin = null)
        {
            if (initialized) throw new Exception("Already initialized");

            //NOTE: use your own unlock code
            RLP.Unlock("[email protected]", new byte[] 
            { 
                0xFB, 0xCC, 0x7D, 0xDA, 0x8E, 0x87, 0x58, 0xAB,
                0x95, 0x8E, 0x68, 0x02, 0x1F, 0xE6, 0xD6, 0x14, 
                0x3C, 0xBD, 0x3E, 0xD1, 0xBE, 0xF0, 0xCE, 0xFB, 
                0x1D, 0xD9, 0xC4, 0xEC, 0xE2, 0x2A, 0xFD, 0xCD
            });

            byte[] elf_file = Extension.GetBytes(Extension.BinaryResources.Extension);
            RLP.LoadELF(elf_file);
            RLP.InitializeBSSRegion(elf_file);
            RLP.Procedure VsInit = RLP.GetProcedure(elf_file, "VsInit");
            vsStreamData = RLP.GetProcedure(elf_file, "VsStreamData");
            vsNoMoreData = RLP.GetProcedure(elf_file, "VsNoMoreData");
            vsLoadPlugin = RLP.GetProcedure(elf_file, "VsLoadPluginFromArray");
            vsSetVolume = RLP.GetProcedure(elf_file, "VsSetVolume");
            vsSetBassAndTreble = RLP.GetProcedure(elf_file, "VsSetBassAndTreble");

            lcdInit = RLP.GetProcedure(elf_file, "LcdInit");
            lcdSet = RLP.GetProcedure(elf_file, "LcdSetLevel");

            elf_file = null;

            int result;
            if ((result = loadPlugin == null ? VsInit.Invoke() : VsInit.InvokeEx(loadPlugin, loadPlugin.Length)) != 0)
                throw new Exception("Could not init VS Driver. Reason " + result.ToString());
            loadedPlugin = loadPlugin;

            RLP.RLPEvent += (data, time) =>
            {
                switch (data)
                {
                    case 0x01:
                        //data was streamed 
                        wait.Set(); //notify any waiter
                        break;

                    case 0x02:
                        //error when closing stream
                        //this means the VS was reseted, 
                        //reload plugin, set volume, bass and treble
                        if (loadedPlugin != null) vsLoadPlugin.InvokeEx(loadedPlugin, loadedPlugin.Length);
                        RaiseException("Error closing stream!");
                        break;
                }
            };
            initialized = true;

            balanceGeneral = 0;
            Volume = 255; //max volume
            trebleGeneral = 0;
            bassGeneral = 0;
        }