Пример #1
0
        public void Byte_array_of_length_55()
        {
            byte[] input = new byte[55];
            input[0] = 255;
            input[1] = 128;
            input[2] = 1;

            byte[] expectedResultBytes = new byte[1 + input.Length];
            expectedResultBytes[0] = (byte)(128 + input.Length);
            expectedResultBytes[1] = input[0];
            expectedResultBytes[2] = input[1];
            expectedResultBytes[3] = input[2];

            Rlp expectedResult = new Rlp(expectedResultBytes);

            Assert.AreEqual(expectedResult, Rlp.Encode(input), "byte array");
            Assert.AreEqual(expectedResult, Rlp.Encode(input.AsSpan()), "span");
        }
Пример #2
0
        public static Keccak CalculateReceiptRoot(this Block block, ISpecProvider specProvider, TxReceipt[] txReceipts)
        {
            if (txReceipts.Length == 0)
            {
                return(PatriciaTree.EmptyTreeHash);
            }

            PatriciaTree receiptTree = new PatriciaTree();

            for (int i = 0; i < txReceipts.Length; i++)
            {
                byte[] receiptRlp = _receiptDecoder.EncodeNew(txReceipts[i], specProvider.GetSpec(block.Number).IsEip658Enabled ? RlpBehaviors.Eip658Receipts : RlpBehaviors.None);
                receiptTree.Set(Rlp.Encode(i).Bytes, receiptRlp);
            }

            receiptTree.UpdateRootHash();
            return(receiptTree.RootHash);
        }
Пример #3
0
        public static Keccak CalculateTxRoot(this Block block)
        {
            if (block.Transactions.Length == 0)
            {
                return(PatriciaTree.EmptyTreeHash);
            }

            PatriciaTree txTree = new PatriciaTree();

            for (int i = 0; i < block.Transactions.Length; i++)
            {
                Rlp transactionRlp = _txDecoder.Encode(block.Transactions[i]);
                txTree.Set(Rlp.Encode(i).Bytes, transactionRlp.Bytes);
            }

            txTree.UpdateRootHash();
            return(txTree.RootHash);
        }
Пример #4
0
        public void Can_do_roundtrip_none_rlp_stream()
        {
            TxReceipt txReceipt = Build.A.Receipt.TestObject;

            txReceipt.Bloom = new Bloom();
            txReceipt.Bloom.Set(Keccak.EmptyTreeHash.Bytes);
            txReceipt.GasUsedTotal         = 1000;
            txReceipt.PostTransactionState = TestItem.KeccakH;

            ReceiptDecoder decoder = new ReceiptDecoder();

            byte[]    rlpStreamResult = decoder.EncodeNew(txReceipt, RlpBehaviors.None);
            TxReceipt deserialized    = Rlp.Decode <TxReceipt>(rlpStreamResult, RlpBehaviors.None);

            Assert.AreEqual(txReceipt.GasUsedTotal, deserialized.GasUsedTotal, "gas used total");
            Assert.AreEqual(txReceipt.Bloom, deserialized.Bloom, "bloom");
            Assert.AreEqual(txReceipt.PostTransactionState, deserialized.PostTransactionState, "post transaction state");
        }
Пример #5
0
        private Keccak GetTransactionsRoot(List <Transaction> transactions)
        {
            if (transactions.Count == 0)
            {
                return(PatriciaTree.EmptyTreeHash);
            }

            PatriciaTree txTree = new PatriciaTree();

            for (int i = 0; i < transactions.Count; i++)
            {
                Rlp transactionRlp = Rlp.Encode(transactions[i]);
                txTree.Set(Rlp.Encode(i).Bytes, transactionRlp);
            }

            txTree.UpdateRootHash();
            return(txTree.RootHash);
        }
Пример #6
0
        public ParityLikeTxTrace ParityTrace(Keccak txHash, ParityTraceTypes traceTypes)
        {
            byte[] traceBytes = _traceDb.Get(txHash);
            if (traceBytes != null)
            {
                return(Rlp.Decode <ParityLikeTxTrace>(traceBytes));
            }

            TxReceipt txReceipt = _receiptStorage.Find(txHash);
            Block     block     = _blockTree.FindBlock(txReceipt.BlockNumber, BlockTreeLookupOptions.RequireCanonical);

            if (block == null)
            {
                throw new InvalidOperationException("Only historical blocks");
            }

            return(ParityTrace(block, txHash, traceTypes));
        }
Пример #7
0
        public Rlp Encode(ParityLikeTxTrace item, RlpBehaviors rlpBehaviors = RlpBehaviors.None)
        {
            Rlp[] traceElements = new Rlp[7];
            traceElements[0] = Rlp.Encode(item.BlockHash);
            traceElements[1] = Rlp.Encode(item.BlockNumber);
            traceElements[2] = Rlp.Encode(item.TransactionHash);
            traceElements[3] = item.TransactionPosition == null ? Rlp.OfEmptyByteArray : Rlp.Encode(item.TransactionPosition.Value);

            ParityTraceAction action = item.Action;
            List <Rlp>        calls  = new List <Rlp>();

            EncodeAction(calls, action);                        // trace
            traceElements[4] = Rlp.Encode(calls.ToArray());
            traceElements[5] = EncodeChange(item.StateChanges); // stateDiff
            traceElements[6] = Rlp.OfEmptySequence;             // vmTrace placeholder

            return(Rlp.Encode(traceElements));
        }
        public void Storage_proofs_when_values_are_missing_setup()
        {
            byte[] a = Bytes.FromHexString("0x000000000000000000000000000000000000000000aaaaaaaaaaaaaaaaaaaaaa");
            byte[] b = Bytes.FromHexString("0x0000000000000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
            byte[] c = Bytes.FromHexString("0x00000000001ccccccccccccccccccccccccccccccccccccccccccccccccccccc");
            byte[] d = Bytes.FromHexString("0x00000000001ddddddddddddddddddddddddddddddddddddddddddddddddddddd");
            byte[] e = Bytes.FromHexString("0x00000000001eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");

            IDb         memDb       = new MemDb();
            StateTree   tree        = new StateTree(memDb);
            StorageTree storageTree = new StorageTree(memDb);

            storageTree.Set(Keccak.Compute(a).Bytes, Rlp.Encode(Bytes.FromHexString("0xab12000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Set(Keccak.Compute(c).Bytes, Rlp.Encode(Bytes.FromHexString("0xab56000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Set(Keccak.Compute(e).Bytes, Rlp.Encode(Bytes.FromHexString("0xab9a000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Commit();

            byte[]  code     = new byte[] { 1, 2, 3 };
            Account account1 = Build.An.Account.WithBalance(1).WithStorageRoot(storageTree.RootHash).TestObject;
            Account account2 = Build.An.Account.WithBalance(2).TestObject;

            tree.Set(TestItem.AddressA, account1);
            tree.Set(TestItem.AddressB, account2);
            tree.Commit();

            TreeDumper dumper = new TreeDumper();

            tree.Accept(dumper, tree.RootHash, true);
            Console.WriteLine(dumper.ToString());

            AccountProofCollector accountProofCollector = new AccountProofCollector(TestItem.AddressA, new byte[][] { a, b, c, d, e });

            tree.Accept(accountProofCollector, tree.RootHash, true);
            AccountProof proof = accountProofCollector.BuildResult();

            Assert.AreEqual("0xab12000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[0].Value?.ToHexString(true) ?? "0x");
            Assert.AreEqual("0x00", proof.StorageProofs[1].Value?.ToHexString(true) ?? "0x");
            Assert.AreEqual("0xab56000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[2].Value?.ToHexString(true) ?? "0x");
            Assert.AreEqual("0x00", proof.StorageProofs[3].Value?.ToHexString(true) ?? "0x");
            Assert.AreEqual("0xab9a000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[4].Value?.ToHexString(true) ?? "0x");

            proof.StorageProofs[1].Proof.Should().HaveCount(3);
            proof.StorageProofs[3].Proof.Should().HaveCount(2);
        }
Пример #9
0
        public void Test(EthashTest test)
        {
            BlockHeader blockHeader = Rlp.Decode <BlockHeader>(new Rlp(test.Header));

            Assert.AreEqual(test.Nonce, blockHeader.Nonce, "header nonce vs test nonce");
            Assert.AreEqual(test.MixHash.Bytes, blockHeader.MixHash.Bytes, "header mix hash vs test mix hash");

            Keccak headerHash = Keccak.Compute(Rlp.Encode(blockHeader, RlpBehaviors.ExcludeBlockMixHashAndNonce));

            Assert.AreEqual(test.HeaderHash, headerHash, "header hash");

            // seed is correct
            Ethash ethash = new Ethash(NullLogManager.Instance);
            uint   epoch  = Ethash.GetEpoch(blockHeader.Number);

            Assert.AreEqual(test.Seed, Ethash.GetSeedHash(epoch), "seed");

            uint cacheSize = Ethash.GetCacheSize(Ethash.GetEpoch(blockHeader.Number));

            Assert.AreEqual((ulong)test.CacheSize, cacheSize, "cache size requested");

            IEthashDataSet cache = new EthashCache(cacheSize, test.Seed.Bytes);

            Assert.AreEqual((ulong)test.CacheSize, (ulong)cache.Size, "cache size returned");

            // below we confirm that headerAndNonceHashed is calculated correctly
            // & that the method for calculating the result from mix hash is correct
            byte[] headerAndNonceHashed = Keccak512.Compute(Bytes.Concat(headerHash.Bytes, test.Nonce.ToByteArray(Bytes.Endianness.Little))).Bytes;
            byte[] resultHalfTest       = Keccak.Compute(Bytes.Concat(headerAndNonceHashed, test.MixHash.Bytes)).Bytes;
            Assert.AreEqual(resultHalfTest, test.Result.Bytes, "half test");

            // here we confirm that the whole mix hash calculation is fine
            (byte[] mixHash, byte[] result) = ethash.Hashimoto((ulong)test.FullSize, cache, headerHash, blockHeader.MixHash, test.Nonce);
            Assert.AreEqual(test.MixHash.Bytes, mixHash, "mix hash");
            Assert.AreEqual(test.Result.Bytes, result, "result");

            // not that the test's result value suggests that the result of the PoW operation is not below difficulty / block is invalid...
            // Assert.True(ethash.Validate(blockHeader), "validation");
            // seems it is just testing the nonce and mix hash but not difficulty

            ulong dataSetSize = Ethash.GetDataSize(epoch);

            Assert.AreEqual((ulong)test.FullSize, dataSetSize, "data size requested");
        }
Пример #10
0
        public async Task Can_load_blocks_from_db_odd()
        {
            for (int chainLength = 2; chainLength <= 32; chainLength++)
            {
                Block genesisBlock = Build.A.Block.Genesis.TestObject;

                MemDb blocksDb     = new MemDb();
                MemDb blockInfosDb = new MemDb();
                MemDb headersDb    = new MemDb();

                BlockTree testTree = Build.A.BlockTree(genesisBlock).OfChainLength(chainLength).TestObject;
                for (int i = 0; i < testTree.Head.Number + 1; i++)
                {
                    Block ithBlock = testTree.FindBlock(i, BlockTreeLookupOptions.None);
                    blocksDb.Set(ithBlock.Hash, Rlp.Encode(ithBlock).Bytes);

                    headersDb.Set(ithBlock.Hash, Rlp.Encode(ithBlock.Header).Bytes);

                    ChainLevelInfo ithLevel = new ChainLevelInfo(true, new BlockInfo[1]
                    {
                        new BlockInfo(ithBlock.Hash, ithBlock.TotalDifficulty.Value)
                    });

                    blockInfosDb.Set(i, Rlp.Encode(ithLevel).Bytes);
                }

                blockInfosDb.Set(Keccak.Zero, genesisBlock.Header.Hash.Bytes);
                headersDb.Set(genesisBlock.Header.Hash, Rlp.Encode(genesisBlock.Header).Bytes);

                BlockTree blockTree = new BlockTree(
                    blocksDb,
                    headersDb,
                    blockInfosDb,
                    new ChainLevelInfoRepository(blockInfosDb),
                    OlympicSpecProvider.Instance,
                    NullBloomStorage.Instance,
                    LimboLogs.Instance);

                DbBlocksLoader loader = new DbBlocksLoader(blockTree, LimboNoErrorLogger.Instance);
                await blockTree.Accept(loader, CancellationToken.None);

                Assert.AreEqual(testTree.Head.Hash, blockTree.BestSuggestedHeader.Hash, $"head {chainLength}");
            }
        }
Пример #11
0
        public void Storage_proofs_have_values_set_complex_3_setup()
        {
            Keccak a = new Keccak("0x000000000000000000000000000000000000000000aaaaaaaaaaaaaaaaaaaaaa");
            Keccak b = new Keccak("0x0000000000000000000000000bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
            Keccak c = new Keccak("0x00000000001ccccccccccccccccccccccccccccccccccccccccccccccccccccc");
            Keccak d = new Keccak("0x00000000001ddddddddddddddddddddddddddddddddddddddddddddddddddddd");
            Keccak e = new Keccak("0x00000000001eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");

            IDb         memDb       = new MemDb();
            StateTree   tree        = new StateTree(memDb);
            StorageTree storageTree = new StorageTree(memDb);

            storageTree.Set(a.Bytes, Rlp.Encode(Bytes.FromHexString("0xab12000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Set(b.Bytes, Rlp.Encode(Bytes.FromHexString("0xab34000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Set(c.Bytes, Rlp.Encode(Bytes.FromHexString("0xab56000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Set(d.Bytes, Rlp.Encode(Bytes.FromHexString("0xab78000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Set(e.Bytes, Rlp.Encode(Bytes.FromHexString("0xab9a000000000000000000000000000000000000000000000000000000000000000000000000000000")));
            storageTree.Commit();

            byte[]  code     = new byte[] { 1, 2, 3 };
            Account account1 = Build.An.Account.WithBalance(1).WithStorageRoot(storageTree.RootHash).TestObject;
            Account account2 = Build.An.Account.WithBalance(2).TestObject;

            tree.Set(TestItem.AddressA, account1);
            tree.Set(TestItem.AddressB, account2);
            tree.Commit();

            TreeDumper dumper = new TreeDumper();

            tree.Accept(dumper, memDb, tree.RootHash);
            Console.WriteLine(dumper.ToString());

            ProofCollector proofCollector = new ProofCollector(TestItem.AddressA, new Keccak[] { a, b, c, d, e });

            tree.Accept(proofCollector, memDb, tree.RootHash);
            AccountProof proof = proofCollector.BuildResult();

            Assert.AreEqual("0xab12000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[0].Value.ToHexString(true));
            Assert.AreEqual("0xab34000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[1].Value.ToHexString(true));
            Assert.AreEqual("0xab56000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[2].Value.ToHexString(true));
            Assert.AreEqual("0xab78000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[3].Value.ToHexString(true));
            Assert.AreEqual("0xab9a000000000000000000000000000000000000000000000000000000000000000000000000000000", proof.StorageProofs[4].Value.ToHexString(true));
        }
        public static Rlp BlockInfoEncodeDeprecated(BlockInfo?item, bool chainWithFinalization)
        {
            if (item == null)
            {
                return(Rlp.OfEmptySequence);
            }

            Rlp[] elements = new Rlp[chainWithFinalization ? 4 : 3];
            elements[0] = Rlp.Encode(item.BlockHash);
            elements[1] = Rlp.Encode(item.WasProcessed);
            elements[2] = Rlp.Encode(item.TotalDifficulty);

            if (chainWithFinalization)
            {
                elements[3] = Rlp.Encode(item.IsFinalized);
            }

            return(Rlp.Encode(elements));
        }
Пример #13
0
        public byte[] Serialize(PingMessage message)
        {
            byte typeByte    = (byte)message.MessageType;
            Rlp  source      = Encode(message.SourceAddress);
            Rlp  destination = Encode(message.DestinationAddress);

            byte[] data = Rlp.Encode(
                Rlp.Encode(message.Version),
                source,
                destination,
                //verify if encoding is correct
                Rlp.Encode(message.ExpirationTime)
                ).Bytes;

            byte[] serializedMsg = Serialize(typeByte, data);
            message.Mdc = serializedMsg.Slice(0, 32);

            return(serializedMsg);
        }
Пример #14
0
        public void Can_decode_aura()
        {
            var auRaSignature = new byte[64];

            new Random().NextBytes(auRaSignature);
            BlockHeader header = Build.A.BlockHeader
                                 .WithAura(100000000, auRaSignature)
                                 .TestObject;

            HeaderDecoder decoder = new();
            Rlp           rlp     = decoder.Encode(header);

            Rlp.ValueDecoderContext decoderContext = new(rlp.Bytes);
            BlockHeader             decoded        = decoder.Decode(ref decoderContext);

            decoded.Hash = decoded.CalculateHash();

            Assert.AreEqual(header.Hash, decoded.Hash, "hash");
        }
Пример #15
0
        public void initializes_pendingValidators_from_db()
        {
            var blockNumber       = 10;
            var validators        = TestItem.Addresses.Take(10).ToArray();
            var blockHash         = Keccak.Compute("Test");
            var pendingValidators = new ContractValidator.PendingValidators(blockNumber, blockHash, validators);
            var rlp = Rlp.Encode(pendingValidators);

            _db[ContractValidator.PendingValidatorsKey.Bytes].Returns(rlp.Bytes);

            IAuRaValidatorProcessor validator = new ContractValidator(_validator, _db, _stateProvider, _abiEncoder, _transactionProcessor, _blockTree, _receiptsStorage, _logManager, 1);

            validator.SetFinalizationManager(_blockFinalizationManager);
            _blockFinalizationManager.BlocksFinalized +=
                Raise.EventWith(new FinalizeEventArgs(_block.Header,
                                                      Build.A.BlockHeader.WithNumber(blockNumber).WithHash(blockHash).TestObject));

            validators.Select((v, i) => validator.IsValidSealer(v, i)).Should().AllBeEquivalentTo(true);
        }
Пример #16
0
        private static int GetContentLength(UserOperationWithEntryPoint opWithEntryPoint)
        {
            UserOperation op         = opWithEntryPoint.UserOperation;
            Address       entryPoint = opWithEntryPoint.EntryPoint;

            return(Rlp.LengthOf(op.Sender)
                   + Rlp.LengthOf(op.Nonce)
                   + Rlp.LengthOf(op.InitCode)
                   + Rlp.LengthOf(op.CallData)
                   + Rlp.LengthOf(op.CallGas)
                   + Rlp.LengthOf(op.VerificationGas)
                   + Rlp.LengthOf(op.PreVerificationGas)
                   + Rlp.LengthOf(op.MaxFeePerGas)
                   + Rlp.LengthOf(op.MaxPriorityFeePerGas)
                   + Rlp.LengthOf(op.Paymaster)
                   + Rlp.LengthOf(op.PaymasterData)
                   + Rlp.LengthOf(op.Signature)
                   + Rlp.LengthOf(entryPoint));
        }
Пример #17
0
        private static BlockBodiesMessage Deserialize(RlpStream rlpStream)
        {
            BlockBodiesMessage message = new BlockBodiesMessage();

            message.Bodies = rlpStream.DecodeArray(ctx =>
            {
                int sequenceLength = rlpStream.ReadSequenceLength();
                if (sequenceLength == 0)
                {
                    return(null);
                }

                Transaction[] transactions = rlpStream.DecodeArray(txCtx => Rlp.Decode <Transaction>(ctx));
                BlockHeader[] ommers       = rlpStream.DecodeArray(txCtx => Rlp.Decode <BlockHeader>(ctx));
                return(new BlockBody(transactions, ommers));
            }, false);

            return(message);
        }
Пример #18
0
        public void MarkAsProcessed(Keccak blockHash, TransactionReceipt[] receipts = null)
        {
            BigInteger number = LoadNumberOnly(blockHash);

            (BlockInfo info, ChainLevelInfo level) = LoadInfo(number, blockHash);

            if (info.WasProcessed)
            {
                throw new InvalidOperationException($"Marking already processed block {blockHash} as processed");
            }

            info.WasProcessed = true;
            UpdateLevel(number, level);
            if (receipts != null)
            {
                IReleaseSpec spec = _specProvider.GetSpec(number);
                _receiptsDb.Set(blockHash, Rlp.Encode(receipts.Select(r => Rlp.Encode(r, spec.IsEip658Enabled ? RlpBehaviors.Eip658Receipts : RlpBehaviors.None)).ToArray()).Bytes);
            }
        }
Пример #19
0
        //[TestCase(256L * 256L * 256L * 256L, (byte)(1 + 4 + 183), (byte)1)]
        public void Serialized_form_is_input_prefixed_with_big_endian_length_and_prefixed_with_length_of_it_plus_183(
            long inputLength, byte expectedFirstByte, byte expectedSecondByte)
        {
            byte[] input = new byte[inputLength];
            input[0] = 255;
            input[1] = 128;
            input[2] = 1;

            Assert.AreEqual(expectedFirstByte, Rlp.Encode(input)[0]);
            Assert.AreEqual(expectedSecondByte, Rlp.Encode(input)[1]);

            if (inputLength < 256)
            {
                for (int i = 0; i < 128; i++)
                {
                    Assert.AreEqual(input[i], Rlp.Encode(input)[i + 1 + expectedFirstByte - 183]);
                }
            }
        }
Пример #20
0
        public void Sign(PrivateKey privateKey, Transaction tx, bool isEip155Enabled)
        {
            if (_logger.IsDebug)
            {
                _logger.Debug($"Signing transaction {tx.SenderAddress} -> {tx.To} ({tx.Value}) with data {tx.Data}");
            }
            Keccak hash = Keccak.Compute(Rlp.Encode(tx, true, isEip155Enabled, _chainIdValue).Bytes);

            tx.Signature = Sign(privateKey, hash);
            if (isEip155Enabled)
            {
                tx.Signature.V = tx.Signature.V + 8 + 2 * _chainIdValue;
            }

            if (_logger.IsDebug)
            {
                _logger.Debug($"Transaction {tx.SenderAddress} -> {tx.To} ({tx.Value}) signed");
            }
        }
        public DataAssetMessage Deserialize(byte[] bytes)
        {
            var context = bytes.AsRlpStream();

            context.ReadSequenceLength();

            DataAsset dataAsset;

            try
            {
                dataAsset = Rlp.Decode <DataAsset>(context);
            }
            catch (RlpException)
            {
                throw new InvalidDataException("DataAssset cannot be null");
            }

            return(new DataAssetMessage(dataAsset));
        }
Пример #22
0
        public void Can_do_roundtrip_ref_struct()
        {
            LogEntry logEntry = new LogEntry(TestItem.AddressA, new byte[] { 1, 2, 3 }, new[] { TestItem.KeccakA, TestItem.KeccakB });
            Rlp      rlp      = Rlp.Encode(logEntry);

            Rlp.ValueDecoderContext valueDecoderContext = new Rlp.ValueDecoderContext(rlp.Bytes);
            LogEntryDecoder.DecodeStructRef(ref valueDecoderContext, RlpBehaviors.None, out var decoded);

            Assert.That(Bytes.AreEqual(logEntry.Data, decoded.Data), "data");
            Assert.That(logEntry.LoggersAddress == decoded.LoggersAddress, "address");

            KeccaksIterator iterator = new KeccaksIterator(decoded.TopicsRlp);

            for (int i = 0; i < logEntry.Topics.Length; i++)
            {
                iterator.TryGetNext(out var keccak);
                Assert.That(logEntry.Topics[i] == keccak, $"topics[{i}]");
            }
        }
Пример #23
0
        public void Can_encode_decode_tiny_extension()
        {
            TrieNode trieNode = new TrieNode(NodeType.Extension);

            trieNode.Key = new HexPrefix(false, 5);
            trieNode.SetChild(0, _tiniestLeaf);

            Rlp rlp = trieNode.RlpEncode();

            TrieNode decoded = new TrieNode(NodeType.Unknown, rlp);

            decoded.ResolveNode(null);
            TrieNode decodedTiniest = decoded.GetChild(0);

            decodedTiniest.ResolveNode(null);

            Assert.AreEqual(_tiniestLeaf.Value, decodedTiniest.Value, "value");
            Assert.AreEqual(_tiniestLeaf.Key.ToBytes(), decodedTiniest.Key.ToBytes(), "key");
        }
Пример #24
0
        public void Setup_chain()
        {
            // Import blocks
            _blockTree = Build.A.BlockTree().TestObject;
            Block block1       = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block1Rlp)));
            Block block2       = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block2Rlp)));
            Block block3       = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block3Rlp)));
            Block block4       = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block4Rlp)));
            Block block5       = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block5Rlp)));
            Block genesisBlock = CliqueTests.GetRinkebyGenesis();

            // Add blocks
            MineBlock(_blockTree, genesisBlock);
            MineBlock(_blockTree, block1);
            MineBlock(_blockTree, block2);
            MineBlock(_blockTree, block3);
            MineBlock(_blockTree, block4);
            MineBlock(_blockTree, block5);
        }
Пример #25
0
        public void Long_byte_array()
        {
            byte[] input = new byte[1025];
            input[0] = 255;
            input[1] = 128;
            input[2] = 1;

            byte[] expectedResultBytes = new byte[1 + 2 + input.Length];
            expectedResultBytes[0] = 183 + 2;
            expectedResultBytes[1] = (byte)(input.Length / (16 * 16));
            expectedResultBytes[2] = (byte)(input.Length % (16 * 16));
            expectedResultBytes[3] = input[0];
            expectedResultBytes[4] = input[1];
            expectedResultBytes[5] = input[2];

            Rlp expectedResult = new(expectedResultBytes);

            Assert.AreEqual(expectedResult, Rlp.Encode(input), "byte array");
            Assert.AreEqual(expectedResult, Rlp.Encode(input.AsSpan()), "span");
        }
Пример #26
0
        public void Serialize(IByteBuffer byteBuffer, StatusMessage message)
        {
            NettyRlpStream rlpStream     = new NettyRlpStream(byteBuffer);
            int            contentLength =
                Rlp.LengthOf(message.ProtocolVersion) +
                Rlp.LengthOf(message.ChainId) +
                Rlp.LengthOf(message.TotalDifficulty) +
                Rlp.LengthOf(message.BestHash) +
                Rlp.LengthOf(message.GenesisHash);

            int totalLength = Rlp.LengthOfSequence(contentLength);

            byteBuffer.EnsureWritable(totalLength);
            rlpStream.StartSequence(contentLength);
            rlpStream.Encode(message.ProtocolVersion);
            rlpStream.Encode(message.ChainId);
            rlpStream.Encode(message.TotalDifficulty);
            rlpStream.Encode(message.BestHash);
            rlpStream.Encode(message.GenesisHash);
        }
Пример #27
0
        public void Serialize(IByteBuffer byteBuffer, T message)
        {
            int contentLength = 0;

            for (int i = 0; i < message.Hashes.Count; i++)
            {
                contentLength += Rlp.LengthOf(message.Hashes[i]);
            }

            int totalLength = Rlp.LengthOfSequence(contentLength);

            RlpStream rlpStream = new NettyRlpStream(byteBuffer);

            byteBuffer.EnsureWritable(totalLength, true);
            rlpStream.StartSequence(contentLength);
            for (int i = 0; i < message.Hashes.Count; i++)
            {
                rlpStream.Encode(message.Hashes[i]);
            }
        }
        public void Serialize(IByteBuffer byteBuffer, BlockHeadersMessage message)
        {
            Eth.V62.BlockHeadersMessageSerializer ethSerializer = new Eth.V62.BlockHeadersMessageSerializer();
            Rlp ethMessage    = new Rlp(ethSerializer.Serialize(message.EthMessage));
            int contentLength =
                Rlp.LengthOf(message.RequestId) +
                Rlp.LengthOf(message.BufferValue) +
                ethMessage.Length;

            int totalLength = Rlp.GetSequenceRlpLength(contentLength);

            RlpStream rlpStream = new NettyRlpStream(byteBuffer);

            byteBuffer.EnsureWritable(totalLength, true);

            rlpStream.StartSequence(contentLength);
            rlpStream.Encode(message.RequestId);
            rlpStream.Encode(message.BufferValue);
            rlpStream.Encode(ethMessage);
        }
Пример #29
0
        private void UpdateHeadBlock(Block block)
        {
            if (block.IsGenesis)
            {
                Genesis = block.Header;
            }

            Head = block.Header;
            _blockInfoDb.Set(HeadAddressInDb, Rlp.Encode(Head).Bytes);
            NewHeadBlock?.Invoke(this, new BlockEventArgs(block));
            if (_dbBatchProcessed != null)
            {
                if (block.Number == _currentDbLoadBatchEnd)
                {
                    TaskCompletionSource <object> completionSource = _dbBatchProcessed;
                    _dbBatchProcessed = null;
                    completionSource.SetResult(null);
                }
            }
        }
Пример #30
0
        public void When_moving_to_main_one_of_the_two_blocks_at_given_level_the_was_processed_check_is_executed_on_the_correct_block_index_regression()
        {
            MemDb blocksDb     = new MemDb();
            MemDb blockInfosDb = new MemDb();

            BlockTree blockTree = new BlockTree(blocksDb, blockInfosDb, OlympicSpecProvider.Instance, Substitute.For <ITransactionPool>(), LimboLogs.Instance);
            Block     block0    = Build.A.Block.WithNumber(0).WithDifficulty(1).TestObject;
            Block     block1    = Build.A.Block.WithNumber(1).WithDifficulty(2).WithParent(block0).TestObject;
            Block     block2    = Build.A.Block.WithNumber(1).WithDifficulty(3).WithParent(block0).TestObject;

            AddToMain(blockTree, block0);

            blockTree.SuggestBlock(block2);
            blockTree.SuggestBlock(block1);
            blockTree.UpdateMainChain(block1);

            BlockHeader storedInDb = Rlp.Decode <BlockHeader>(new Rlp(blockInfosDb.Get(Keccak.Zero)));

            Assert.AreEqual(block1.Hash, storedInDb.Hash);
        }