public void DecodeSingleHighBytes() { for (var k = 128; k < 256; k++) { var result = Rlp.Decode(new byte[] { 0x81, (byte)k }); Assert.IsNotNull(result); Assert.AreEqual(1, result.Length); Assert.AreEqual(k, result[0]); } }
public void DecodeSingleLowBytes() { for (var k = 0; k < 128; k++) { var result = Rlp.Decode(new byte[] { (byte)k }); Assert.IsNotNull(result); Assert.AreEqual(1, result.Length); Assert.AreEqual(k, result[0]); } }
private static Block GetBlockToTrace(Rlp blockRlp) { Block block = Rlp.Decode <Block>(blockRlp); if (block.TotalDifficulty == null) { block.TotalDifficulty = 1; } return(block); }
public Consumer Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { _ = rlpStream.ReadSequenceLength(); var depositId = rlpStream.DecodeKeccak(); var verificationTimestamp = rlpStream.DecodeUInt(); var dataRequest = Rlp.Decode <DataRequest>(rlpStream); var dataAsset = Rlp.Decode <DataAsset>(rlpStream); var hasAvailableUnits = rlpStream.DecodeBool(); return(new Consumer(depositId, verificationTimestamp, dataRequest, dataAsset, hasAvailableUnits)); }
public GethLikeTxTrace[] TraceBlock(Rlp blockRlp) { Block block = Rlp.Decode <Block>(blockRlp); if (block.TotalDifficulty == null) { block.TotalDifficulty = 1; } return(TraceBlock(block)); }
private Block DecodeBlock(string file) { byte[] fileContent = File.ReadAllBytes(file); if (_logger.IsInfo) { _logger.Info(fileContent.ToHexString()); } Rlp blockRlp = new(fileContent); return(Rlp.Decode <Block>(blockRlp)); }
private void RunTest(TransactionTest test, IReleaseSpec spec) { //TestContext.CurrentContext.Test.Properties.Set("Category", test.Network); // no longer public ValidTransactionTest validTest = test as ValidTransactionTest; Nethermind.Core.Transaction transaction; try { Rlp rlp = new Rlp(Bytes.FromHexString(test.Rlp)); transaction = Rlp.Decode <Nethermind.Core.Transaction>(rlp); } catch (Exception) { if (validTest == null) { return; } throw; } bool useChainId = transaction.Signature.V > 28; SignatureValidator signatureValidator = new SignatureValidator(useChainId ? ChainId.MainNet : 0); TransactionValidator validator = new TransactionValidator(signatureValidator); if (validTest != null) { Assert.AreEqual(validTest.Value, transaction.Value, "value"); Assert.AreEqual(validTest.Data, transaction.Data ?? transaction.Init, "data"); Assert.AreEqual(validTest.GasLimit, transaction.GasLimit, "gasLimit"); Assert.AreEqual(validTest.GasPrice, transaction.GasPrice, "gasPrice"); Assert.AreEqual(validTest.Nonce, transaction.Nonce, "nonce"); Assert.AreEqual(validTest.To, transaction.To, "to"); Assert.True(validator.IsWellFormed(transaction, spec)); Signature expectedSignature = new Signature(validTest.R, validTest.S, validTest.V); Assert.AreEqual(expectedSignature, transaction.Signature, "signature"); // if(useChainId && spec.IsEip155Enabled) // IEthereumEcdsa ecdsa = new EthereumEcdsa(new SingleReleaseSpecProvider(spec, useChainId ? (int)ChainId.MainNet : 0), NullLogManager.Instance); bool verified = ecdsa.Verify( validTest.Sender, transaction, 0); Assert.True(verified); } else { Assert.False(validator.IsWellFormed(transaction, spec)); } }
public void Setup_chain() { IDb db = new MemDb(); // Import blocks _blockTree = Build.A.BlockTree().TestObject; Block genesisBlock = GetRinkebyGenesis(); MineBlock(_blockTree, genesisBlock); Block block1 = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block1Rlp))); block1.Header.ParentHash = genesisBlock.Hash; BuildSealer(1, db).SealBlock(block1, CancellationToken.None).Wait(); block1.Header.Hash = block1.CalculateHash(); MineBlock(_blockTree, block1); Block block2 = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block2Rlp))); block2.Header.ParentHash = block1.Hash; BuildSealer(2, db).SealBlock(block2, CancellationToken.None).Wait(); block2.Header.Hash = block2.CalculateHash(); MineBlock(_blockTree, block2); Block block3 = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block3Rlp))); block3.Header.ParentHash = block2.Hash; BuildSealer(3, db).SealBlock(block3, CancellationToken.None).Wait(); block3.Header.Hash = block3.CalculateHash(); MineBlock(_blockTree, block3); Block block4 = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block4Rlp))); block4.Header.ParentHash = block3.Hash; BuildSealer(4, db).SealBlock(block4, CancellationToken.None).Wait(); block4.Header.Hash = block4.CalculateHash(); MineBlock(_blockTree, block4); Block block5 = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(Block5Rlp))); block5.Header.ParentHash = block4.Hash; BuildSealer(5, db).SealBlock(block5, CancellationToken.None).Wait(); block5.Header.Hash = block5.CalculateHash(); MineBlock(_blockTree, block5); _lastBlock = block5; // Init snapshot db // Select in-turn signer int currentBlock = 6; BuildSealer(currentBlock, db); }
public async Task <ResultWrapper <Keccak> > eth_sendRawTransaction(byte[] transaction) { try { Transaction tx = Rlp.Decode <Transaction>(transaction, RlpBehaviors.AllowUnsigned | RlpBehaviors.SkipTypedWrapping); return(await SendTx(tx)); } catch (RlpException) { return(ResultWrapper <Keccak> .Fail("Invalid RLP.", ErrorCodes.TransactionRejected)); } }
public GethLikeTxTrace[] TraceBlock(Rlp blockRlp) { Block block = Rlp.Decode <Block>(blockRlp); if (block.TotalDifficulty == null) { block.TotalDifficulty = 1; block.TotalTransactions = new UInt256(block.Transactions.Length); } return(TraceBlock(block)); }
public void Test_no_signer_data_at_epoch_fails(string blockRlp) { CliqueConfig config = new() { Epoch = 4 }; _clique = new CliqueSealer(NullSigner.Instance, config, _snapshotManager, LimboLogs.Instance); _sealValidator = new CliqueSealValidator(config, _snapshotManager, LimboLogs.Instance); Block block = Rlp.Decode <Block>(new Rlp(Bytes.FromHexString(blockRlp))); bool validHeader = _sealValidator.ValidateParams(_blockTree.FindHeader(block.ParentHash, BlockTreeLookupOptions.None), block.Header); bool validSeal = _sealValidator.ValidateSeal(block.Header, true); Assert.False(validHeader); Assert.True(validSeal); }
private static void Roundtrip(bool valueDecode) { BlockInfo blockInfo = new(TestItem.KeccakA, 1); blockInfo.WasProcessed = true; Rlp rlp = Rlp.Encode(blockInfo); BlockInfo decoded = valueDecode ? Rlp.Decode <BlockInfo>(rlp.Bytes.AsSpan()) : Rlp.Decode <BlockInfo>(rlp); Assert.True(decoded.WasProcessed, "0 processed"); Assert.AreEqual(TestItem.KeccakA, decoded.BlockHash, "block hash"); Assert.AreEqual(UInt256.One, decoded.TotalDifficulty, "difficulty"); }
public TxReceipt Find(Keccak hash) { var receiptData = _database.Get(hash); if (receiptData == null) { receiptData = _headersFixDb.Get(hash); } return(receiptData == null ? null : Rlp.Decode <TxReceipt>(new Rlp(receiptData), RlpBehaviors.Storage)); }
public TxReceipt Find(Keccak hash) { var receiptData = _database.Get(hash); if (receiptData != null) { var receipt = Rlp.Decode <TxReceipt>(new Rlp(receiptData), RlpBehaviors.Storage); receipt.TxHash = hash; return(receipt); } return(null); }
public void Can_encode_decode_sample1() { System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(ParityTraceDecoder).TypeHandle); ParityTraceAction subtrace = new ParityTraceAction(); subtrace.Value = 67890; subtrace.CallType = "call"; subtrace.From = TestItem.AddressC; subtrace.To = TestItem.AddressD; subtrace.Input = Bytes.Empty; subtrace.Gas = 10000; subtrace.TraceAddress = new int[] { 0, 0 }; subtrace.Result.Output = Bytes.Empty; subtrace.Result.GasUsed = 15000; ParityLikeTxTrace txTrace = new ParityLikeTxTrace(); txTrace.Action = new ParityTraceAction(); txTrace.Action.Value = 12345; txTrace.Action.CallType = "init"; txTrace.Action.From = TestItem.AddressA; txTrace.Action.To = TestItem.AddressB; txTrace.Action.Input = new byte[] { 1, 2, 3, 4, 5, 6 }; txTrace.Action.Gas = 40000; txTrace.Action.TraceAddress = new int[] { 0 }; txTrace.Action.Subtraces.Add(subtrace); txTrace.Action.Result.Output = Bytes.Empty; txTrace.Action.Result.GasUsed = 30000; txTrace.BlockHash = TestItem.KeccakB; txTrace.BlockNumber = 123456; txTrace.TransactionHash = TestItem.KeccakC; txTrace.TransactionPosition = 5; txTrace.Action.TraceAddress = new int[] { 1, 2, 3 }; ParityAccountStateChange stateChange = new ParityAccountStateChange(); stateChange.Balance = new ParityStateChange <UInt256>(1, 2); stateChange.Nonce = new ParityStateChange <UInt256>(0, 1); stateChange.Storage = new Dictionary <UInt256, ParityStateChange <byte[]> >(); stateChange.Storage[1] = new ParityStateChange <byte[]>(new byte[] { 1 }, new byte[] { 2 }); txTrace.StateChanges = new Dictionary <Address, ParityAccountStateChange>(); txTrace.StateChanges.Add(TestItem.AddressC, stateChange); Rlp rlp = Rlp.Encode(txTrace); ParityLikeTxTrace deserialized = Rlp.Decode <ParityLikeTxTrace>(rlp); deserialized.Should().BeEquivalentTo(txTrace); }
public ResultWrapper <Keccak> eth_sendRawTransaction(byte[] transaction) { try { _readerWriterLockSlim.EnterWriteLock(); Transaction tx = Rlp.Decode <Transaction>(transaction); Keccak txHash = _blockchainBridge.SendTransaction(tx); return(ResultWrapper <Keccak> .Success(txHash)); } finally { _readerWriterLockSlim.ExitWriteLock(); } }
private void RunTest(TransactionTest test, IReleaseSpec spec) { //TestContext.CurrentContext.Test.Properties.Set("Category", test.Network); // no longer public ValidTransactionTest validTest = test as ValidTransactionTest; Nethermind.Core.Transaction transaction; try { Rlp rlp = new(Bytes.FromHexString(test.Rlp)); transaction = Rlp.Decode <Nethermind.Core.Transaction>(rlp); } catch (Exception) { if (validTest == null) { return; } throw; } bool useChainId = transaction.Signature.V > 28UL; TxValidator validator = new(useChainId ? ChainId.Mainnet : 0UL); if (validTest != null) { Assert.AreEqual(validTest.Value, transaction.Value, "value"); Assert.AreEqual(validTest.Data, transaction.Data, "data"); Assert.AreEqual(validTest.GasLimit, transaction.GasLimit, "gasLimit"); Assert.AreEqual(validTest.GasPrice, transaction.GasPrice, "gasPrice"); Assert.AreEqual(validTest.Nonce, transaction.Nonce, "nonce"); Assert.AreEqual(validTest.To, transaction.To, "to"); Assert.True(validator.IsWellFormed(transaction, spec)); Signature expectedSignature = new(validTest.R, validTest.S, validTest.V); Assert.AreEqual(expectedSignature, transaction.Signature, "signature"); IEthereumEcdsa ecdsa = new EthereumEcdsa(useChainId ? ChainId.Mainnet : 0UL, LimboLogs.Instance); bool verified = ecdsa.Verify( validTest.Sender, transaction); Assert.True(verified); } else { Assert.False(validator.IsWellFormed(transaction, spec)); } }
public void Can_encode_decode_with_negative_long_when_using_span(long negativeLong) { BlockHeader header = Build.A.BlockHeader. WithNumber(negativeLong). WithGasUsed(negativeLong). WithGasLimit(negativeLong).TestObject; Rlp rlp = Rlp.Encode(header); BlockHeader blockHeader = Rlp.Decode <BlockHeader>(rlp.Bytes.AsSpan()); blockHeader.GasUsed.Should().Be(negativeLong); blockHeader.Number.Should().Be(negativeLong); blockHeader.GasLimit.Should().Be(negativeLong); }
public void Can_encode_decode_with_base_fee() { try { HeaderDecoder.Eip1559TransitionBlock = 0; BlockHeader header = Build.A.BlockHeader.WithBaseFee(123).TestObject; Rlp rlp = Rlp.Encode(header); BlockHeader blockHeader = Rlp.Decode <BlockHeader>(rlp); blockHeader.BaseFeePerGas.Should().Be(123); } finally { HeaderDecoder.Eip1559TransitionBlock = long.MaxValue; } }
public BlockBodiesMessage Deserialize(byte[] bytes) { Rlp.DecoderContext decoderContext = bytes.AsRlpContext(); BlockBodiesMessage message = new BlockBodiesMessage(); message.Bodies = decoderContext.DecodeArray(ctx => { decoderContext.ReadSequenceLength(); Transaction[] transactions = decoderContext.DecodeArray(txCtx => Rlp.Decode <Transaction>(ctx)); BlockHeader[] ommers = decoderContext.DecodeArray(txCtx => Rlp.Decode <BlockHeader>(ctx)); return(transactions, ommers); }); return(message); }
public void Can_do_roundtrip() { BlockInfo blockInfo = new BlockInfo(); blockInfo.BlockHash = TestItem.KeccakA; blockInfo.TotalDifficulty = 1; blockInfo.WasProcessed = true; Rlp rlp = Rlp.Encode(blockInfo); BlockInfo decoded = Rlp.Decode <BlockInfo>(rlp); Assert.True(decoded.WasProcessed, "0 processed"); Assert.AreEqual(TestItem.KeccakA, decoded.BlockHash, "block hash"); Assert.AreEqual(UInt256.One, decoded.TotalDifficulty, "difficulty"); }
private static void RoundtripBackwardsCompatible(bool valueDecode, bool chainWithFinalization, bool isFinalized) { BlockInfo blockInfo = new(TestItem.KeccakA, 1); blockInfo.WasProcessed = true; blockInfo.IsFinalized = isFinalized; Rlp rlp = BlockInfoEncodeDeprecated(blockInfo, chainWithFinalization); BlockInfo decoded = valueDecode ? Rlp.Decode <BlockInfo>(rlp.Bytes.AsSpan()) : Rlp.Decode <BlockInfo>(rlp); Assert.True(decoded.WasProcessed, "0 processed"); Assert.AreEqual(chainWithFinalization && isFinalized, decoded.IsFinalized, "finalized"); Assert.AreEqual(TestItem.KeccakA, decoded.BlockHash, "block hash"); Assert.AreEqual(UInt256.One, decoded.TotalDifficulty, "difficulty"); }
public ChainLevelInfo LoadLevel(long number) { ChainLevelInfo chainLevelInfo = _blockInfoCache.Get(number); if (chainLevelInfo == null) { byte[] levelBytes = _blockInfoDb.Get(number); if (levelBytes != null) { chainLevelInfo = Rlp.Decode <ChainLevelInfo>(new Rlp(levelBytes)); _blockInfoCache.Set(number, chainLevelInfo); } } return(chainLevelInfo); }
public void Sets_head_block_info_in_db_on_new_head_block() { 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; AddToMain(blockTree, block0); AddToMain(blockTree, block1); BlockHeader storedInDb = Rlp.Decode <BlockHeader>(new Rlp(blockInfosDb.Get(Keccak.Zero))); Assert.AreEqual(block1.Hash, storedInDb.Hash); }
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; ReceiptMessageDecoder decoder = new ReceiptMessageDecoder(); byte[] rlpStreamResult = decoder.EncodeNew(txReceipt, RlpBehaviors.None); TxReceipt deserialized = Rlp.Decode <TxReceipt>(rlpStreamResult, RlpBehaviors.None); AssertMessageReceipt(txReceipt, deserialized); }
public void Can_do_roundtrip() { BlockInfo blockInfo = new BlockInfo(); blockInfo.BlockHash = TestObject.KeccakA; blockInfo.TotalDifficulty = 1; blockInfo.TotalTransactions = 1; blockInfo.WasProcessed = true; Rlp rlp = Rlp.Encode(blockInfo); BlockInfo decoded = Rlp.Decode <BlockInfo>(rlp); Assert.True(decoded.WasProcessed, "0 processed"); Assert.AreEqual(TestObject.KeccakA, decoded.BlockHash, "block hash"); Assert.AreEqual(BigInteger.One, decoded.TotalDifficulty, "difficulty"); Assert.AreEqual(BigInteger.One, decoded.TotalTransactions, "txs"); }
private ChainLevelInfo LoadLevel(BigInteger number) { ChainLevelInfo chainLevelInfo = _blockInfoCache.Get(number); if (chainLevelInfo == null) { byte[] levelBytes = _blockInfoDb.Get(number); if (levelBytes == null) { return(null); } chainLevelInfo = Rlp.Decode <ChainLevelInfo>(new Rlp(levelBytes)); } return(chainLevelInfo); }
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.ForSealing).Bytes); 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[] nonceBytes = new byte[8]; BinaryPrimitives.WriteUInt64LittleEndian(nonceBytes, test.Nonce); byte[] headerAndNonceHashed = Keccak512.Compute(Bytes.Concat(headerHash.Bytes, nonceBytes)).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, bool success) = 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"); }
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"); }
private void InitializeChain(string chainFile) { if (!File.Exists(chainFile)) { _logger.Info($"Chain file does not exist: {chainFile}, skipping"); return; } var chainFileContent = File.ReadAllBytes(chainFile); var blocksRlps = OldRlp.ExtractRlpList(new Rlp(chainFileContent)); foreach (var blockRlp in blocksRlps) { Block block = Rlp.Decode <Block>(blockRlp); ProcessBlock(block); } }