public void Can_sync_on_split_of_length_1() { BlockTree miner1Tree = Build.A.BlockTree(_genesisBlock).OfChainLength(6).TestObject; ISyncPeer miner1 = new SyncPeerMock(miner1Tree); ManualResetEvent resetEvent = new ManualResetEvent(false); _synchronizer.SyncEvent += (sender, args) => { TestContext.WriteLine(args.SyncEvent); if (args.SyncEvent == SyncEvent.Completed || args.SyncEvent == SyncEvent.Failed) { resetEvent.Set(); } }; _pool.Start(); _synchronizer.Start(); _pool.AddPeer(miner1); resetEvent.WaitOne(_standardTimeoutUnit); miner1Tree.BestSuggestedHeader.Should().BeEquivalentTo(_blockTree.BestSuggestedHeader, "client agrees with miner before split"); Block splitBlock = Build.A.Block.WithParent(miner1Tree.FindParent(miner1Tree.Head, BlockTreeLookupOptions.TotalDifficultyNotNeeded)).WithDifficulty(miner1Tree.Head.Difficulty - 1).TestObject; Block splitBlockChild = Build.A.Block.WithParent(splitBlock).TestObject; miner1Tree.SuggestBlock(splitBlock); miner1Tree.UpdateMainChain(splitBlock); miner1Tree.SuggestBlock(splitBlockChild); miner1Tree.UpdateMainChain(splitBlockChild); splitBlockChild.Header.Should().BeEquivalentTo(miner1Tree.BestSuggestedHeader, "split as expected"); resetEvent.Reset(); _syncServer.AddNewBlock(splitBlockChild, miner1); resetEvent.WaitOne(_standardTimeoutUnit); Assert.AreEqual(miner1Tree.BestSuggestedHeader.Hash, _blockTree.BestSuggestedHeader.Hash, "client agrees with miner after split"); }
public void Terminal_block_with_lower_td_should_not_change_best_suggested_but_should_be_added_to_block_tree() { Context ctx = new(); BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(10).TestObject; BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; TestSpecProvider testSpecProvider = new(London.Instance); testSpecProvider.TerminalTotalDifficulty = 10_000_000; Block newBestLocalBlock = Build.A.Block.WithNumber(localBlockTree.Head !.Number + 1).WithParent(localBlockTree.Head !).WithDifficulty(10_000_002L).TestObject; localBlockTree.SuggestBlock(newBestLocalBlock); PoSSwitcher poSSwitcher = new(new MergeConfig() { Enabled = true }, new SyncConfig(), new MemDb(), localBlockTree, testSpecProvider, LimboLogs.Instance); HeaderValidator headerValidator = new( localBlockTree, Always.Valid, testSpecProvider, LimboLogs.Instance); MergeHeaderValidator mergeHeaderValidator = new(poSSwitcher, headerValidator, localBlockTree, testSpecProvider, Always.Valid, LimboLogs.Instance); BlockValidator blockValidator = new( Always.Valid, mergeHeaderValidator, Always.Valid, MainnetSpecProvider.Instance, LimboLogs.Instance); ctx.SyncServer = new SyncServer( new MemDb(), new MemDb(), localBlockTree, NullReceiptStorage.Instance, blockValidator, Always.Valid, ctx.PeerPool, StaticSelector.Full, new SyncConfig(), NullWitnessCollector.Instance, Policy.FullGossip, testSpecProvider, LimboLogs.Instance); Block remoteBestBlock = remoteBlockTree.FindBlock(9, BlockTreeLookupOptions.None); ctx.SyncServer.AddNewBlock(remoteBestBlock, ctx.NodeWhoSentTheBlock); Assert.AreEqual(newBestLocalBlock.Header.Hash, localBlockTree.BestSuggestedHeader !.Hash); Assert.AreEqual(remoteBestBlock.Hash, localBlockTree.FindBlock(remoteBestBlock.Hash, BlockTreeLookupOptions.None) !.Hash); }
public void Post_merge_blocks_wont_be_accepted_by_gossip(long ttd, bool sendFakeTd) { BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; Block postMergeBlock = Build.A.Block.WithDifficulty(0).WithParent(remoteBlockTree.Head).WithTotalDifficulty(remoteBlockTree.Head.TotalDifficulty).WithNonce(0u).TestObject; remoteBlockTree.SuggestBlock(postMergeBlock); BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; Context ctx = CreateMergeContext(localBlockTree, (UInt256)ttd); Block block = remoteBlockTree.FindBlock(9, BlockTreeLookupOptions.None); if (sendFakeTd) { block.Header.TotalDifficulty *= 2; } ctx.SyncServer.AddNewBlock(block, ctx.NodeWhoSentTheBlock); Assert.AreEqual(localBlockTree.BestSuggestedHeader !.Number, 8); localBlockTree.FindBlock(postMergeBlock.Hash !, BlockTreeLookupOptions.None).Should().BeNull(); }
public async Task Does_not_do_full_sync_when_not_needed_with_split() { BlockTree minerTree = Build.A.BlockTree(_genesisBlock).OfChainLength(6).TestObject; ISyncPeer miner1 = new SyncPeerMock(minerTree); AutoResetEvent resetEvent = new AutoResetEvent(false); _synchronizer.SyncEvent += (sender, args) => { if (args.SyncEvent == SyncEvent.Completed || args.SyncEvent == SyncEvent.Failed) { resetEvent.Set(); } }; _pool.Start(); _synchronizer.Start(); _pool.AddPeer(miner1); resetEvent.WaitOne(_standardTimeoutUnit); Assert.AreEqual(minerTree.BestSuggestedHeader.Hash, _blockTree.BestSuggestedHeader.Hash, "client agrees with miner before split"); Block newBlock = Build.A.Block.WithParent(minerTree.Head).TestObject; minerTree.SuggestBlock(newBlock); minerTree.UpdateMainChain(newBlock); ISyncPeer miner2 = Substitute.For <ISyncPeer>(); miner2.GetHeadBlockHeader(Arg.Any <Keccak>(), Arg.Any <CancellationToken>()).Returns(miner1.GetHeadBlockHeader(null, CancellationToken.None)); miner2.Node.Id.Returns(TestItem.PublicKeyB); Assert.AreEqual(newBlock.Number, await miner2.GetHeadBlockHeader(null, Arg.Any <CancellationToken>()), "number as expected"); _pool.Start(); _synchronizer.Start(); _pool.AddPeer(miner2); resetEvent.WaitOne(_standardTimeoutUnit); await miner2.Received().GetBlockHeaders(6, 1, 0, default(CancellationToken)); }
public void Can_inject_terminal_block_with_higher_td_than_head(long ttd, bool sendFakeTd) { BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; Block terminalBlockWithHigherTotalDifficulty = Build.A.Block.WithDifficulty(1000010).WithParent(remoteBlockTree.Head).WithTotalDifficulty(remoteBlockTree.Head.TotalDifficulty + 1000010).TestObject; remoteBlockTree.SuggestBlock(terminalBlockWithHigherTotalDifficulty); BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(10).TestObject; Context ctx = CreateMergeContext(localBlockTree, (UInt256)ttd); Assert.True(terminalBlockWithHigherTotalDifficulty.IsTerminalBlock(ctx.SpecProvider)); Block block = remoteBlockTree.FindBlock(9, BlockTreeLookupOptions.None); if (sendFakeTd) { block.Header.TotalDifficulty *= 2; } ctx.SyncServer.AddNewBlock(block, ctx.NodeWhoSentTheBlock); Assert.AreEqual(localBlockTree.BestSuggestedHeader !.Number, 9); localBlockTree.FindBlock(terminalBlockWithHigherTotalDifficulty.Hash !, BlockTreeLookupOptions.None).Should().NotBeNull(); localBlockTree.BestSuggestedHeader !.Hash.Should().Be(terminalBlockWithHigherTotalDifficulty.Hash !); }
private void MineBlock(BlockTree tree, Block block) { tree.SuggestBlock(block); tree.UpdateMainChain(block); }
private SyncTestContext CreateSyncManager(int index) { var logManager = NoErrorLimboLogs.Instance; ConsoleAsyncLogger logger = new ConsoleAsyncLogger(LogLevel.Debug, "PEER " + index + " "); // var logManager = new OneLoggerLogManager(logger); var specProvider = new SingleReleaseSpecProvider(ConstantinopleFix.Instance, MainnetSpecProvider.Instance.ChainId); var dbProvider = TestMemDbProvider.Init(); IDb blockDb = dbProvider.BlocksDb; IDb headerDb = dbProvider.HeadersDb; IDb blockInfoDb = dbProvider.BlockInfosDb; ISnapshotableDb codeDb = dbProvider.CodeDb; ISnapshotableDb stateDb = dbProvider.StateDb; var stateReader = new StateReader(stateDb, codeDb, logManager); var stateProvider = new StateProvider(stateDb, codeDb, logManager); stateProvider.CreateAccount(TestItem.AddressA, 10000.Ether()); stateProvider.Commit(specProvider.GenesisSpec); stateProvider.CommitTree(); stateProvider.RecalculateStateRoot(); stateDb.Commit(); var storageProvider = new StorageProvider(stateDb, stateProvider, logManager); var receiptStorage = new InMemoryReceiptStorage(); var ecdsa = new EthereumEcdsa(specProvider.ChainId, logManager); var txPool = new TxPool.TxPool(new InMemoryTxStorage(), ecdsa, specProvider, new TxPoolConfig(), stateProvider, logManager); var tree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, NullBloomStorage.Instance, logManager); var blockhashProvider = new BlockhashProvider(tree, LimboLogs.Instance); var virtualMachine = new VirtualMachine(stateProvider, storageProvider, blockhashProvider, specProvider, logManager); var sealValidator = Always.Valid; var headerValidator = new HeaderValidator(tree, sealValidator, specProvider, logManager); var txValidator = Always.Valid; var ommersValidator = new OmmersValidator(tree, headerValidator, logManager); var blockValidator = new BlockValidator(txValidator, headerValidator, ommersValidator, specProvider, logManager); ISyncConfig syncConfig = _synchronizerType == SynchronizerType.Fast ? SyncConfig.WithFastSync : SyncConfig.WithFullSyncOnly; var rewardCalculator = new RewardCalculator(specProvider); var txProcessor = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, logManager); var blockProcessor = new BlockProcessor(specProvider, blockValidator, rewardCalculator, txProcessor, stateDb, codeDb, stateProvider, storageProvider, txPool, receiptStorage, logManager); var step = new RecoverSignatures(ecdsa, txPool, specProvider, logManager); var processor = new BlockchainProcessor(tree, blockProcessor, step, logManager, BlockchainProcessor.Options.Default); var nodeStatsManager = new NodeStatsManager(logManager); var syncPeerPool = new SyncPeerPool(tree, nodeStatsManager, 25, logManager); StateProvider devState = new StateProvider(stateDb, codeDb, logManager); StorageProvider devStorage = new StorageProvider(stateDb, devState, logManager); var devEvm = new VirtualMachine(devState, devStorage, blockhashProvider, specProvider, logManager); var devTxProcessor = new TransactionProcessor(specProvider, devState, devStorage, devEvm, logManager); var devBlockProcessor = new BlockProcessor(specProvider, blockValidator, rewardCalculator, devTxProcessor, stateDb, codeDb, devState, devStorage, txPool, receiptStorage, logManager); var devChainProcessor = new BlockchainProcessor(tree, devBlockProcessor, step, logManager, BlockchainProcessor.Options.NoReceipts); var transactionSelector = new TxPoolTxSource(txPool, stateReader, logManager); var producer = new DevBlockProducer( transactionSelector, devChainProcessor, stateProvider, tree, processor, txPool, Timestamper.Default, logManager); SyncProgressResolver resolver = new SyncProgressResolver(tree, receiptStorage, stateDb, new MemDb(), syncConfig, logManager); MultiSyncModeSelector selector = new MultiSyncModeSelector(resolver, syncPeerPool, syncConfig, logManager); Synchronizer synchronizer = new Synchronizer( dbProvider, MainnetSpecProvider.Instance, tree, NullReceiptStorage.Instance, blockValidator, sealValidator, syncPeerPool, nodeStatsManager, StaticSelector.Full, syncConfig, logManager); var syncServer = new SyncServer(stateDb, codeDb, tree, receiptStorage, Always.Valid, Always.Valid, syncPeerPool, selector, syncConfig, logManager); ManualResetEventSlim waitEvent = new ManualResetEventSlim(); tree.NewHeadBlock += (s, e) => waitEvent.Set(); if (index == 0) { _genesis = Build.A.Block.Genesis.WithStateRoot(stateProvider.StateRoot).TestObject; producer.Start(); } syncPeerPool.Start(); synchronizer.Start(); processor.Start(); tree.SuggestBlock(_genesis); if (!waitEvent.Wait(1000)) { throw new Exception("No genesis"); } SyncTestContext context = new SyncTestContext(); context.Ecdsa = ecdsa; context.BlockchainProcessor = processor; context.PeerPool = syncPeerPool; context.StateProvider = stateProvider; context.Synchronizer = synchronizer; context.SyncServer = syncServer; context.Tree = tree; context.BlockProducer = producer; context.TxPool = txPool; context.Logger = logger; return(context); }
private void Initialize(bool auRa = false) { ISpecProvider specProvider = MainnetSpecProvider.Instance; IEthereumEcdsa ethereumEcdsa = new EthereumEcdsa(specProvider, LimboLogs.Instance); ITxStorage txStorage = new InMemoryTxStorage(); _stateDb = new StateDb(); ISnapshotableDb codeDb = new StateDb(); IStateReader stateReader = new StateReader(_stateDb, codeDb, LimboLogs.Instance); _stateProvider = new StateProvider(_stateDb, codeDb, LimboLogs.Instance); _stateProvider.CreateAccount(TestItem.AddressA, 1000.Ether()); _stateProvider.CreateAccount(TestItem.AddressB, 1000.Ether()); _stateProvider.CreateAccount(TestItem.AddressC, 1000.Ether()); byte[] code = Bytes.FromHexString("0xabcd"); Keccak codeHash = Keccak.Compute(code); _stateProvider.UpdateCode(code); _stateProvider.UpdateCodeHash(TestItem.AddressA, codeHash, specProvider.GenesisSpec); IStorageProvider storageProvider = new StorageProvider(_stateDb, _stateProvider, LimboLogs.Instance); storageProvider.Set(new StorageCell(TestItem.AddressA, UInt256.One), Bytes.FromHexString("0xabcdef")); storageProvider.Commit(); _stateProvider.Commit(specProvider.GenesisSpec); _stateProvider.CommitTree(); ITxPool txPool = new TxPool.TxPool(txStorage, Timestamper.Default, ethereumEcdsa, specProvider, new TxPoolConfig(), _stateProvider, LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockDb), specProvider, txPool, NullBloomStorage.Instance, LimboLogs.Instance); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); VirtualMachine virtualMachine = new VirtualMachine(_stateProvider, storageProvider, new BlockhashProvider(blockTree, LimboLogs.Instance), specProvider, LimboLogs.Instance); TransactionProcessor txProcessor = new TransactionProcessor(specProvider, _stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); IBlockProcessor blockProcessor = new BlockProcessor(specProvider, Always.Valid, new RewardCalculator(specProvider), txProcessor, _stateDb, codeDb, _stateProvider, storageProvider, txPool, receiptStorage, LimboLogs.Instance); IFilterStore filterStore = new FilterStore(); IFilterManager filterManager = new FilterManager(filterStore, blockProcessor, txPool, LimboLogs.Instance); _blockchainBridge = new BlockchainBridge(stateReader, _stateProvider, storageProvider, blockTree, txPool, receiptStorage, filterStore, filterManager, NullWallet.Instance, txProcessor, ethereumEcdsa, NullBloomStorage.Instance, LimboLogs.Instance, false); BlockchainProcessor blockchainProcessor = new BlockchainProcessor(blockTree, blockProcessor, new TxSignaturesRecoveryStep(ethereumEcdsa, txPool, LimboLogs.Instance), LimboLogs.Instance, true); blockchainProcessor.Start(); ManualResetEventSlim resetEvent = new ManualResetEventSlim(false); blockTree.NewHeadBlock += (s, e) => { Console.WriteLine(e.Block.Header.Hash); if (e.Block.Number == 9) { resetEvent.Set(); } }; var genesisBlockBuilder = Build.A.Block.Genesis.WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")); if (auRa) { genesisBlockBuilder.WithAura(0, new byte[65]); } Block genesis = genesisBlockBuilder.TestObject; blockTree.SuggestBlock(genesis); Block previousBlock = genesis; for (int i = 1; i < 10; i++) { List <Transaction> transactions = new List <Transaction>(); for (int j = 0; j < i; j++) { transactions.Add(Build.A.Transaction.WithNonce((UInt256)j).SignedAndResolved().TestObject); } BlockBuilder builder = Build.A.Block.WithNumber(i).WithParent(previousBlock).WithTransactions(transactions.ToArray()).WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")); if (auRa) { builder.WithAura(i, i.ToByteArray()); } Block block = builder.TestObject; blockTree.SuggestBlock(block); previousBlock = block; } IReceiptsRecovery receiptsRecovery = new ReceiptsRecovery(); IReceiptFinder receiptFinder = new FullInfoReceiptFinder(receiptStorage, receiptsRecovery, blockTree); resetEvent.Wait(2000); _traceModule = new TraceModule(receiptFinder, new Tracer(_stateProvider, blockchainProcessor), _blockchainBridge); _blockTree = blockTree; }
public void Initialize() { var logger = LimboLogs.Instance; var specProvider = MainnetSpecProvider.Instance; var ethereumEcdsa = new EthereumEcdsa(specProvider.ChainId, logger); var txStorage = new InMemoryTxStorage(); var txPool = new TxPool.TxPool(txStorage, Timestamper.Default, ethereumEcdsa, specProvider, new TxPoolConfig(), new StateProvider(new StateDb(), new MemDb(), LimboLogs.Instance), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, txPool, NullBloomStorage.Instance, LimboLogs.Instance); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); _parityModule = new ParityModule(ethereumEcdsa, txPool, blockTree, receiptStorage, logger); var blockNumber = 2; var pendingTransaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)).TestObject; pendingTransaction.Signature.V = 37; txPool.AddTransaction(pendingTransaction, TxHandlingOptions.None); blockNumber = 1; var transaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)) .WithNonce(100).TestObject; transaction.Signature.V = 37; txPool.AddTransaction(transaction, TxHandlingOptions.None); Block genesis = Build.A.Block.Genesis .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .TestObject; blockTree.SuggestBlock(genesis); blockTree.UpdateMainChain(new[] { genesis }, true); Block previousBlock = genesis; Block block = Build.A.Block.WithNumber(blockNumber).WithParent(previousBlock) .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .WithTransactions(transaction) .TestObject; blockTree.SuggestBlock(block); blockTree.UpdateMainChain(new[] { block }, true); var logEntries = new[] { Build.A.LogEntry.TestObject }; receiptStorage.Insert(block, false, new TxReceipt() { Bloom = new Bloom(logEntries), Index = 1, Recipient = TestItem.AddressA, Sender = TestItem.AddressB, BlockHash = TestItem.KeccakA, BlockNumber = 1, ContractAddress = TestItem.AddressC, GasUsed = 1000, TxHash = transaction.Hash, StatusCode = 0, GasUsedTotal = 2000, Logs = logEntries }); }
public void Initialize() { LimboLogs logger = LimboLogs.Instance; MainnetSpecProvider specProvider = MainnetSpecProvider.Instance; EthereumEcdsa ethereumEcdsa = new(specProvider.ChainId, logger); Peer peerA = SetUpPeerA(); //standard case Peer peerB = SetUpPeerB(); //Session is null Peer peerC = SetUpPeerC(); //Node is null, Caps are empty IPeerManager peerManager = Substitute.For <IPeerManager>(); peerManager.ActivePeers.Returns(new List <Peer> { peerA, peerB, peerC }); peerManager.ConnectedPeers.Returns(new List <Peer> { peerA, peerB, peerA, peerC, peerB }); peerManager.MaxActivePeers.Returns(15); StateProvider stateProvider = new(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); StateReader stateReader = new(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, NullBloomStorage.Instance, LimboLogs.Instance); ITransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(specProvider, blockTree); TxPool.TxPool txPool = new(ethereumEcdsa, new ChainHeadInfoProvider(new FixedBlockChainHeadSpecProvider(specProvider), blockTree, stateProvider), new TxPoolConfig(), new TxValidator(specProvider.ChainId), LimboLogs.Instance, transactionComparerProvider.GetDefaultComparer()); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); _signerStore = new Signer(specProvider.ChainId, TestItem.PrivateKeyB, logger); _parityRpcModule = new ParityRpcModule(ethereumEcdsa, txPool, blockTree, receiptStorage, new Enode(TestItem.PublicKeyA, IPAddress.Loopback, 8545), _signerStore, new MemKeyStore(new[] { TestItem.PrivateKeyA }), MainnetSpecProvider.Instance, peerManager); int blockNumber = 2; Transaction pendingTransaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)).TestObject; pendingTransaction.Signature.V = 37; stateProvider.CreateAccount(pendingTransaction.SenderAddress, UInt256.UInt128MaxValue); txPool.SubmitTx(pendingTransaction, TxHandlingOptions.None); blockNumber = 1; Transaction transaction1 = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)) .WithNonce(100).TestObject; transaction1.Signature.V = 37; stateProvider.CreateAccount(transaction1.SenderAddress, UInt256.UInt128MaxValue); var transaction2 = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)) .WithNonce(120).TestObject; transaction2.Signature.V = 37; var transaction3 = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)) .WithNonce(110).TestObject; transaction2.Signature.V = 37; Block genesis = Build.A.Block.Genesis .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .TestObject; blockTree.SuggestBlock(genesis); blockTree.UpdateMainChain(new[] { genesis }, true); Block previousBlock = genesis; Block block = Build.A.Block.WithNumber(blockNumber).WithParent(previousBlock) .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .WithTransactions(transaction1, transaction2, transaction3) .TestObject; blockTree.SuggestBlock(block); blockTree.UpdateMainChain(new[] { block }, true); LogEntry[] logEntries = new[] { Build.A.LogEntry.TestObject }; TxReceipt receipt1 = new() { Bloom = new Bloom(logEntries), Index = 0, Recipient = TestItem.AddressA, Sender = TestItem.AddressB, BlockHash = TestItem.KeccakA, BlockNumber = 1, ContractAddress = TestItem.AddressC, GasUsed = 1000, TxHash = transaction1.Hash, StatusCode = 0, GasUsedTotal = 2000, Logs = logEntries }; TxReceipt receipt2 = new() { Bloom = new Bloom(logEntries), Index = 1, Recipient = TestItem.AddressA, Sender = TestItem.AddressB, BlockHash = TestItem.KeccakA, BlockNumber = 1, ContractAddress = TestItem.AddressC, GasUsed = 1000, TxHash = transaction2.Hash, StatusCode = 0, GasUsedTotal = 2000, Logs = logEntries }; TxReceipt receipt3 = new() { Bloom = new Bloom(logEntries), Index = 2, Recipient = TestItem.AddressA, Sender = TestItem.AddressB, BlockHash = TestItem.KeccakA, BlockNumber = 1, ContractAddress = TestItem.AddressC, GasUsed = 1000, TxHash = transaction3.Hash, StatusCode = 0, GasUsedTotal = 2000, Logs = logEntries }; receiptStorage.Insert(block, receipt1, receipt2, receipt3); } private static Peer SetUpPeerA() { Node node = new(TestItem.PublicKeyA, "127.0.0.1", 30303, true); node.ClientId = "Geth/v1.9.21-stable/linux-amd64/go1.15.2"; Peer peer = new(node); peer.InSession = null; peer.OutSession = Substitute.For <ISession>(); peer.OutSession.RemoteNodeId.Returns(TestItem.PublicKeyA); IProtocolHandler protocolHandler = Substitute.For <IProtocolHandler, ISyncPeer>(); peer.OutSession.TryGetProtocolHandler(Protocol.Eth, out Arg.Any <IProtocolHandler>()).Returns(x => { x[1] = protocolHandler; return(true); }); byte version = 65; protocolHandler.ProtocolVersion.Returns(version); if (protocolHandler is ISyncPeer syncPeer) { UInt256 difficulty = 0x5ea4ed; syncPeer.TotalDifficulty.Returns(difficulty); syncPeer.HeadHash.Returns(TestItem.KeccakA); } IProtocolHandler p2PProtocolHandler = Substitute.For <IProtocolHandler, IP2PProtocolHandler>(); peer.OutSession.TryGetProtocolHandler(Protocol.P2P, out Arg.Any <IProtocolHandler>()).Returns(x => { x[1] = p2PProtocolHandler; return(true); }); if (p2PProtocolHandler is IP2PProtocolHandler p2PHandler) { p2PHandler.AgreedCapabilities.Returns(new List <Capability> { new("eth", 65), new("eth", 64) }); }
public void GlobalSetup() { ISnapshotableDb codeDb = new StateDb(); ISnapshotableDb stateDb = new StateDb(); IDb blockInfoDb = new MemDb(10, 5); ISpecProvider specProvider = MainnetSpecProvider.Instance; IReleaseSpec spec = MainnetSpecProvider.Instance.GenesisSpec; StateProvider stateProvider = new StateProvider(stateDb, codeDb, LimboLogs.Instance); stateProvider.CreateAccount(Address.Zero, 1000.Ether()); stateProvider.Commit(spec); StorageProvider storageProvider = new StorageProvider(stateDb, stateProvider, LimboLogs.Instance); StateReader stateReader = new StateReader(stateDb, codeDb, LimboLogs.Instance); ChainLevelInfoRepository chainLevelInfoRepository = new ChainLevelInfoRepository(blockInfoDb); BlockTree blockTree = new BlockTree(new MemDb(), new MemDb(), blockInfoDb, chainLevelInfoRepository, specProvider, NullTxPool.Instance, NullBloomStorage.Instance, LimboLogs.Instance); _blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance); _virtualMachine = new VirtualMachine(stateProvider, storageProvider, _blockhashProvider, specProvider, LimboLogs.Instance); Block genesisBlock = Build.A.Block.Genesis.TestObject; blockTree.SuggestBlock(genesisBlock); Block block1 = Build.A.Block.WithParent(genesisBlock).WithNumber(1).TestObject; blockTree.SuggestBlock(block1); TransactionProcessor transactionProcessor = new TransactionProcessor(MainnetSpecProvider.Instance, stateProvider, storageProvider, _virtualMachine, LimboLogs.Instance); BlockProcessor blockProcessor = new BlockProcessor(specProvider, Always.Valid, new RewardCalculator(specProvider), transactionProcessor, stateDb, codeDb, stateProvider, storageProvider, NullTxPool.Instance, NullReceiptStorage.Instance, LimboLogs.Instance); BlockchainProcessor blockchainProcessor = new BlockchainProcessor( blockTree, blockProcessor, new TxSignaturesRecoveryStep(new EthereumEcdsa(specProvider, LimboLogs.Instance), NullTxPool.Instance, LimboLogs.Instance), LimboLogs.Instance, false); blockchainProcessor.Process(genesisBlock, ProcessingOptions.None, NullBlockTracer.Instance); blockchainProcessor.Process(block1, ProcessingOptions.None, NullBlockTracer.Instance); IBloomStorage bloomStorage = new BloomStorage(new BloomConfig(), new MemDb(), new InMemoryDictionaryFileStoreFactory()); BlockchainBridge bridge = new BlockchainBridge( stateReader, stateProvider, storageProvider, blockTree, NullTxPool.Instance, NullReceiptStorage.Instance, NullFilterStore.Instance, NullFilterManager.Instance, new DevWallet(new WalletConfig(), LimboLogs.Instance), transactionProcessor, new EthereumEcdsa(MainnetSpecProvider.Instance, LimboLogs.Instance), bloomStorage, LimboLogs.Instance, false); _ethModule = new EthModule(new JsonRpcConfig(), bridge, LimboLogs.Instance); }
public void Valid_block_makes_it_all_the_way() { SetupBeamProcessor(); Block newBlock = Build.A.Block.WithParent(_blockTree.Head).WithTotalDifficulty(_blockTree.Head.TotalDifficulty + 1).TestObject; _blockTree.SuggestBlock(newBlock); Thread.Sleep(1000); // _blockchainProcessor.Received().Process(newBlock, ProcessingOptions.Beam, NullBlockTracer.Instance); }
public void GlobalSetup() { var dbProvider = TestMemDbProvider.Init(); IDb codeDb = dbProvider.CodeDb; IDb stateDb = dbProvider.StateDb; IDb blockInfoDb = new MemDb(10, 5); ISpecProvider specProvider = MainnetSpecProvider.Instance; IReleaseSpec spec = MainnetSpecProvider.Instance.GenesisSpec; var trieStore = new TrieStore(stateDb, LimboLogs.Instance); StateProvider stateProvider = new StateProvider(trieStore, codeDb, LimboLogs.Instance); stateProvider.CreateAccount(Address.Zero, 1000.Ether()); stateProvider.Commit(spec); StorageProvider storageProvider = new StorageProvider(trieStore, stateProvider, LimboLogs.Instance); StateReader stateReader = new StateReader(trieStore, codeDb, LimboLogs.Instance); ChainLevelInfoRepository chainLevelInfoRepository = new ChainLevelInfoRepository(blockInfoDb); BlockTree blockTree = new BlockTree(dbProvider, chainLevelInfoRepository, specProvider, NullBloomStorage.Instance, LimboLogs.Instance); _blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance); _virtualMachine = new VirtualMachine(stateProvider, storageProvider, _blockhashProvider, specProvider, LimboLogs.Instance); Block genesisBlock = Build.A.Block.Genesis.TestObject; blockTree.SuggestBlock(genesisBlock); Block block1 = Build.A.Block.WithParent(genesisBlock).WithNumber(1).TestObject; blockTree.SuggestBlock(block1); TransactionProcessor transactionProcessor = new TransactionProcessor(MainnetSpecProvider.Instance, stateProvider, storageProvider, _virtualMachine, LimboLogs.Instance); BlockProcessor blockProcessor = new BlockProcessor(specProvider, Always.Valid, new RewardCalculator(specProvider), transactionProcessor, stateProvider, storageProvider, NullTxPool.Instance, NullReceiptStorage.Instance, NullWitnessCollector.Instance, LimboLogs.Instance); EthereumEcdsa ecdsa = new EthereumEcdsa(specProvider.ChainId, LimboLogs.Instance); BlockchainProcessor blockchainProcessor = new BlockchainProcessor( blockTree, blockProcessor, new RecoverSignatures( ecdsa, NullTxPool.Instance, specProvider, LimboLogs.Instance), LimboLogs.Instance, BlockchainProcessor.Options.NoReceipts); blockchainProcessor.Process(genesisBlock, ProcessingOptions.None, NullBlockTracer.Instance); blockchainProcessor.Process(block1, ProcessingOptions.None, NullBlockTracer.Instance); IBloomStorage bloomStorage = new BloomStorage(new BloomConfig(), new MemDb(), new InMemoryDictionaryFileStoreFactory()); LogFinder logFinder = new LogFinder( blockTree, new InMemoryReceiptStorage(), bloomStorage, LimboLogs.Instance, new ReceiptsRecovery(ecdsa, specProvider)); BlockchainBridge bridge = new BlockchainBridge( new ReadOnlyTxProcessingEnv( new ReadOnlyDbProvider(dbProvider, false), trieStore.AsReadOnly(), new ReadOnlyBlockTree(blockTree), specProvider, LimboLogs.Instance), NullTxPool.Instance, NullReceiptStorage.Instance, NullFilterStore.Instance, NullFilterManager.Instance, ecdsa, Timestamper.Default, logFinder, false, false); _ethModule = new EthModule( new JsonRpcConfig(), bridge, blockTree, stateReader, NullTxPool.Instance, NullTxSender.Instance, NullWallet.Instance, LimboLogs.Instance); }
protected virtual async Task <TestBlockchain> Build(ISpecProvider specProvider = null) { Timestamper = new ManualTimestamper(new DateTime(2020, 2, 15, 12, 50, 30, DateTimeKind.Utc)); JsonSerializer = new EthereumJsonSerializer(); SpecProvider = specProvider ?? MainnetSpecProvider.Instance; EthereumEcdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); ITxStorage txStorage = new InMemoryTxStorage(); DbProvider = new MemDbProvider(); State = new StateProvider(StateDb, CodeDb, LimboLogs.Instance); State.CreateAccount(TestItem.AddressA, 1000.Ether()); State.CreateAccount(TestItem.AddressB, 1000.Ether()); State.CreateAccount(TestItem.AddressC, 1000.Ether()); byte[] code = Bytes.FromHexString("0xabcd"); Keccak codeHash = Keccak.Compute(code); State.UpdateCode(code); State.UpdateCodeHash(TestItem.AddressA, codeHash, SpecProvider.GenesisSpec); Storage = new StorageProvider(StateDb, State, LimboLogs.Instance); Storage.Set(new StorageCell(TestItem.AddressA, UInt256.One), Bytes.FromHexString("0xabcdef")); Storage.Commit(); State.Commit(SpecProvider.GenesisSpec); State.CommitTree(); TxPool = new TxPool.TxPool(txStorage, Timestamper, EthereumEcdsa, SpecProvider, new TxPoolConfig(), State, LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); BlockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockDb), SpecProvider, TxPool, NullBloomStorage.Instance, LimboLogs.Instance); ReceiptStorage = new InMemoryReceiptStorage(); VirtualMachine virtualMachine = new VirtualMachine(State, Storage, new BlockhashProvider(BlockTree, LimboLogs.Instance), SpecProvider, LimboLogs.Instance); TxProcessor = new TransactionProcessor(SpecProvider, State, Storage, virtualMachine, LimboLogs.Instance); BlockProcessor = CreateBlockProcessor(); BlockchainProcessor chainProcessor = new BlockchainProcessor(BlockTree, BlockProcessor, new TxSignaturesRecoveryStep(EthereumEcdsa, TxPool, LimboLogs.Instance), LimboLogs.Instance, BlockchainProcessor.Options.Default); chainProcessor.Start(); StateReader = new StateReader(StateDb, CodeDb, LimboLogs.Instance); TxPoolTxSource txPoolTxSource = new TxPoolTxSource(TxPool, StateReader, LimboLogs.Instance); ISealer sealer = new FakeSealer(TimeSpan.Zero); BlockProducer = new TestBlockProducer(txPoolTxSource, chainProcessor, State, sealer, BlockTree, chainProcessor, Timestamper, LimboLogs.Instance); BlockProducer.Start(); _resetEvent = new AutoResetEvent(false); BlockTree.NewHeadBlock += (s, e) => { Console.WriteLine(e.Block.Header.Hash); _resetEvent.Set(); }; var genesis = GetGenesisBlock(); BlockTree.SuggestBlock(genesis); await _resetEvent.WaitOneAsync(CancellationToken.None); await AddBlocksOnStart(); return(this); }
public void Initialize() { var logger = LimboLogs.Instance; var specProvider = MainnetSpecProvider.Instance; var ethereumEcdsa = new EthereumEcdsa(specProvider.ChainId, logger); var txStorage = new InMemoryTxStorage(); Peer peerA = SetUpPeerA(); //standard case Peer peerB = SetUpPeerB(); //Session is null Peer peerC = SetUpPeerC(); //Node is null, Caps are empty IPeerManager peerManager = Substitute.For <IPeerManager>(); peerManager.ActivePeers.Returns(new List <Peer> { peerA, peerB, peerC }); peerManager.ConnectedPeers.Returns(new List <Peer> { peerA, peerB, peerA, peerC, peerB }); peerManager.MaxActivePeers.Returns(15); StateProvider stateProvider = new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance); var txPool = new TxPool.TxPool(txStorage, ethereumEcdsa, new FixedBlockChainHeadSpecProvider(specProvider), new TxPoolConfig(), stateProvider, new TxValidator(specProvider.ChainId), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); IBlockTree blockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), specProvider, NullBloomStorage.Instance, LimboLogs.Instance); new OnChainTxWatcher(blockTree, txPool, specProvider, LimboLogs.Instance); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); _signerStore = new Signer(specProvider.ChainId, TestItem.PrivateKeyB, logger); _parityModule = new ParityModule(ethereumEcdsa, txPool, blockTree, receiptStorage, new Enode(TestItem.PublicKeyA, IPAddress.Loopback, 8545), _signerStore, new MemKeyStore(new[] { TestItem.PrivateKeyA }), logger, peerManager); var blockNumber = 2; var pendingTransaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)).TestObject; pendingTransaction.Signature.V = 37; stateProvider.CreateAccount(pendingTransaction.SenderAddress, UInt256.UInt128MaxValue); txPool.AddTransaction(pendingTransaction, TxHandlingOptions.None); blockNumber = 1; var transaction = Build.A.Transaction.Signed(ethereumEcdsa, TestItem.PrivateKeyD, false) .WithSenderAddress(Address.FromNumber((UInt256)blockNumber)) .WithNonce(100).TestObject; transaction.Signature.V = 37; stateProvider.CreateAccount(transaction.SenderAddress, UInt256.UInt128MaxValue); txPool.AddTransaction(transaction, TxHandlingOptions.None); Block genesis = Build.A.Block.Genesis .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .TestObject; blockTree.SuggestBlock(genesis); blockTree.UpdateMainChain(new[] { genesis }, true); Block previousBlock = genesis; Block block = Build.A.Block.WithNumber(blockNumber).WithParent(previousBlock) .WithStateRoot(new Keccak("0x1ef7300d8961797263939a3d29bbba4ccf1702fabf02d8ad7a20b454edb6fd2f")) .WithTransactions(MuirGlacier.Instance, transaction) .TestObject; blockTree.SuggestBlock(block); blockTree.UpdateMainChain(new[] { block }, true); var logEntries = new[] { Build.A.LogEntry.TestObject }; receiptStorage.Insert(block, new TxReceipt() { Bloom = new Bloom(logEntries), Index = 1, Recipient = TestItem.AddressA, Sender = TestItem.AddressB, BlockHash = TestItem.KeccakA, BlockNumber = 1, ContractAddress = TestItem.AddressC, GasUsed = 1000, TxHash = transaction.Hash, StatusCode = 0, GasUsedTotal = 2000, Logs = logEntries }); }
protected virtual async Task <TestBlockchain> Build(ISpecProvider specProvider = null, UInt256?initialValues = null) { Timestamper = new ManualTimestamper(new DateTime(2020, 2, 15, 12, 50, 30, DateTimeKind.Utc)); JsonSerializer = new EthereumJsonSerializer(); SpecProvider = specProvider ?? MainnetSpecProvider.Instance; EthereumEcdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); ITxStorage txStorage = new InMemoryTxStorage(); DbProvider = await TestMemDbProvider.InitAsync(); State = new StateProvider(StateDb, CodeDb, LimboLogs.Instance); State.CreateAccount(TestItem.AddressA, (initialValues ?? 1000.Ether())); State.CreateAccount(TestItem.AddressB, (initialValues ?? 1000.Ether())); State.CreateAccount(TestItem.AddressC, (initialValues ?? 1000.Ether())); byte[] code = Bytes.FromHexString("0xabcd"); Keccak codeHash = Keccak.Compute(code); State.UpdateCode(code); State.UpdateCodeHash(TestItem.AddressA, codeHash, SpecProvider.GenesisSpec); Storage = new StorageProvider(StateDb, State, LimboLogs.Instance); Storage.Set(new StorageCell(TestItem.AddressA, UInt256.One), Bytes.FromHexString("0xabcdef")); Storage.Commit(); State.Commit(SpecProvider.GenesisSpec); State.CommitTree(); TxPool = new TxPool.TxPool( txStorage, EthereumEcdsa, SpecProvider, new TxPoolConfig(), new StateProvider(StateDb, CodeDb, LimboLogs.Instance), LimboLogs.Instance); IDb blockDb = new MemDb(); IDb headerDb = new MemDb(); IDb blockInfoDb = new MemDb(); BlockTree = new BlockTree(blockDb, headerDb, blockInfoDb, new ChainLevelInfoRepository(blockDb), SpecProvider, NullBloomStorage.Instance, LimboLogs.Instance); new OnChainTxWatcher(BlockTree, TxPool, SpecProvider, LimboLogs.Instance); ReceiptStorage = new InMemoryReceiptStorage(); VirtualMachine virtualMachine = new VirtualMachine(State, Storage, new BlockhashProvider(BlockTree, LimboLogs.Instance), SpecProvider, LimboLogs.Instance); TxProcessor = new TransactionProcessor(SpecProvider, State, Storage, virtualMachine, LimboLogs.Instance); BlockProcessor = CreateBlockProcessor(); BlockchainProcessor chainProcessor = new BlockchainProcessor(BlockTree, BlockProcessor, new RecoverSignatures(EthereumEcdsa, TxPool, SpecProvider, LimboLogs.Instance), LimboLogs.Instance, Nethermind.Blockchain.Processing.BlockchainProcessor.Options.Default); BlockchainProcessor = chainProcessor; chainProcessor.Start(); StateReader = new StateReader(StateDb, CodeDb, LimboLogs.Instance); TxPoolTxSource txPoolTxSource = CreateTxPoolTxSource(); ISealer sealer = new NethDevSealEngine(TestItem.AddressD); BlockProducer = new TestBlockProducer(txPoolTxSource, chainProcessor, State, sealer, BlockTree, chainProcessor, Timestamper, LimboLogs.Instance); BlockProducer.Start(); _resetEvent = new SemaphoreSlim(0); _suggestedBlockResetEvent = new ManualResetEvent(true); BlockTree.NewHeadBlock += (s, e) => { _resetEvent.Release(1); }; BlockProducer.LastProducedBlockChanged += (s, e) => { _suggestedBlockResetEvent.Set(); }; var genesis = GetGenesisBlock(); BlockTree.SuggestBlock(genesis); await _resetEvent.WaitAsync(); //if (!await _resetEvent.WaitAsync(1000)) // { // throw new InvalidOperationException("Failed to process genesis in 1s."); // } await AddBlocksOnStart(); return(this); }
private static void MineBlock(BlockTree tree, Block block) { tree.SuggestBlock(block); }