public void Can_accept_new_valid_blocks(bool sealOk, bool validationOk, bool accepted) { Context ctx = new(); BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(10).TestObject; BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; ISealValidator sealValidator = sealOk ? Always.Valid : Always.Invalid; IBlockValidator blockValidator = validationOk ? Always.Valid : Always.Invalid; ctx.SyncServer = new SyncServer( new MemDb(), new MemDb(), localBlockTree, NullReceiptStorage.Instance, blockValidator, sealValidator, ctx.PeerPool, StaticSelector.Full, new SyncConfig(), NullWitnessCollector.Instance, Policy.FullGossip, MainnetSpecProvider.Instance, LimboLogs.Instance); Block block = remoteBlockTree.FindBlock(9, BlockTreeLookupOptions.None); if (!accepted) { Assert.Throws <EthSyncException>(() => ctx.SyncServer.AddNewBlock(block, ctx.NodeWhoSentTheBlock)); } else { ctx.SyncServer.AddNewBlock(block, ctx.NodeWhoSentTheBlock); } if (accepted) { Assert.AreEqual(localBlockTree.BestSuggestedHeader, block.Header); } else { Assert.AreNotEqual(localBlockTree.BestSuggestedHeader, block.Header); } }
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); }
public void Will_not_reject_block_with_bad_total_diff_but_will_reset_diff_to_null() { Context ctx = new Context(); BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(10).TestObject; BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; HeaderValidator headerValidator = new HeaderValidator( localBlockTree, Always.Valid, MainnetSpecProvider.Instance, LimboLogs.Instance); BlockValidator blockValidator = new BlockValidator( Always.Valid, headerValidator, 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, LimboLogs.Instance); Block block = remoteBlockTree.FindBlock(9, BlockTreeLookupOptions.None); block.Header.TotalDifficulty *= 2; ctx.SyncServer.AddNewBlock(block, ctx.NodeWhoSentTheBlock); Assert.AreEqual(localBlockTree.BestSuggestedHeader.Hash, block.Header.Hash); Block parentBlock = remoteBlockTree.FindBlock(8, BlockTreeLookupOptions.None); Assert.AreEqual(parentBlock.TotalDifficulty + block.Difficulty, localBlockTree.BestSuggestedHeader.TotalDifficulty); }
public async Task Initialize() { ISpecProvider specProvider = MainnetSpecProvider.Instance; ITxPool txPool = NullTxPool.Instance; IDbProvider dbProvider = await TestMemDbProvider.InitAsync(); BlockTree blockTree = new BlockTree(dbProvider.BlocksDb, dbProvider.HeadersDb, dbProvider.BlockInfosDb, new ChainLevelInfoRepository(dbProvider.BlockInfosDb), specProvider, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance); _factory = new EthModuleFactory( txPool, Substitute.For <ITxSender>(), NullWallet.Instance, blockTree, new JsonRpcConfig(), LimboLogs.Instance, Substitute.For <IStateReader>(), Substitute.For <IBlockchainBridgeFactory>(), Substitute.For <ISpecProvider>()); }
public static INdmBlockchainBridge BuildABridge() { MemDbProvider memDbProvider = new MemDbProvider(); StateReader stateReader = new StateReader(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance); StateProvider stateProvider = new StateProvider(memDbProvider.StateDb, memDbProvider.CodeDb, LimboLogs.Instance); StorageProvider storageProvider = new StorageProvider(memDbProvider.StateDb, stateProvider, LimboLogs.Instance); IEthereumEcdsa ecdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); ITxPool txPool = new TxPool.TxPool(new InMemoryTxStorage(), Timestamper.Default, ecdsa, MainnetSpecProvider.Instance, new TxPoolConfig(), stateProvider, LimboLogs.Instance); // BlockTree blockTree = new BlockTree(memDbProvider.BlocksDb, memDbProvider.HeadersDb, memDbProvider.BlockInfosDb, new ChainLevelInfoRepository(memDbProvider.BlockInfosDb), MainnetSpecProvider.Instance, txPool, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance); BlockTree blockTree = Build.A.BlockTree().OfChainLength(1).TestObject; IWallet wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance); VirtualMachine virtualMachine = new VirtualMachine(stateProvider, storageProvider, new BlockhashProvider(blockTree, LimboLogs.Instance), MainnetSpecProvider.Instance, LimboLogs.Instance); TransactionProcessor processor = new TransactionProcessor(MainnetSpecProvider.Instance, stateProvider, storageProvider, virtualMachine, LimboLogs.Instance); BlockchainBridge blockchainBridge = new BlockchainBridge(stateReader, stateProvider, storageProvider, blockTree, txPool, new InMemoryReceiptStorage(), NullFilterStore.Instance, NullFilterManager.Instance, wallet, processor, ecdsa, NullBloomStorage.Instance, Timestamper.Default, LimboLogs.Instance, false); TxPoolBridge txPoolBridge = new TxPoolBridge(txPool, new WalletTxSigner(wallet, ChainId.Mainnet), Timestamper.Default); return(new NdmBlockchainBridge(txPoolBridge, blockchainBridge, txPool)); }
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 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 Broadcast_NewBlock_on_arrival_to_sqrt_of_peers([Values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 50, 100)] int peerCount) { int expectedPeers = (int)Math.Ceiling(Math.Sqrt(peerCount - 1)); // -1 because of ignoring sender Context ctx = new(); BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(10).TestObject; BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; ctx.SyncServer = new SyncServer( new MemDb(), new MemDb(), localBlockTree, NullReceiptStorage.Instance, Always.Valid, Always.Valid, ctx.PeerPool, StaticSelector.Full, new SyncConfig(), NullWitnessCollector.Instance, Policy.FullGossip, MainnetSpecProvider.Instance, LimboLogs.Instance); ISyncServer remoteServer = Substitute.For <ISyncServer>(); int count = 0; remoteServer .When(r => r.AddNewBlock(Arg.Is <Block>(b => b.Hash == remoteBlockTree.Head !.Hash), Arg.Any <ISyncPeer>())) .Do(_ => count++); PeerInfo[] peers = Enumerable.Range(0, peerCount).Take(peerCount) .Select(k => new PeerInfo(new SyncPeerMock(remoteBlockTree, remoteSyncServer: remoteServer))) .ToArray(); ctx.PeerPool.AllPeers.Returns(peers); ctx.PeerPool.PeerCount.Returns(peers.Length); ctx.SyncServer.AddNewBlock(remoteBlockTree.Head !, peers[0].SyncPeer); await Task.Delay(100); // notifications fire on separate task await Task.WhenAll(peers.Select(p => ((SyncPeerMock)p.SyncPeer).Close()).ToArray()); count.Should().Be(expectedPeers); }
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)); }
private SafeContext PrepareDownloader(DbContext dbContext, ISyncPeer syncPeer) { SafeContext ctx = new SafeContext(); ctx = new SafeContext(); BlockTree blockTree = Build.A.BlockTree().OfChainLength((int)BlockTree.BestSuggestedHeader.Number).TestObject; ctx.Pool = new SyncPeerPool(blockTree, new NodeStatsManager(new StatsConfig(), LimboLogs.Instance), 25, LimboLogs.Instance); ctx.Pool.Start(); ctx.Pool.AddPeer(syncPeer); SyncConfig syncConfig = new SyncConfig(); syncConfig.FastSync = true; ctx.SyncModeSelector = StaticSelector.StateNodesWithFastBlocks; ctx.Feed = new StateSyncFeed(dbContext.LocalCodeDb, dbContext.LocalStateDb, new MemDb(), ctx.SyncModeSelector, blockTree, _logManager); ctx.StateSyncDispatcher = new StateSyncDispatcher(ctx.Feed, ctx.Pool, new StateSyncAllocationStrategyFactory(), _logManager); ctx.StateSyncDispatcher.Start(CancellationToken.None); return(ctx); }
public void Initialize() { ISpecProvider specProvider = MainnetSpecProvider.Instance; ITxPool txPool = NullTxPool.Instance; MemDbProvider dbProvider = new MemDbProvider(); BlockTree blockTree = new BlockTree(dbProvider.BlocksDb, dbProvider.HeadersDb, dbProvider.BlockInfosDb, new ChainLevelInfoRepository(dbProvider.BlockInfosDb), specProvider, txPool, NullBloomStorage.Instance, new SyncConfig(), LimboLogs.Instance); _factory = new EthModuleFactory( dbProvider, txPool, NullWallet.Instance, blockTree, new EthereumEcdsa(MainnetSpecProvider.Instance, LimboLogs.Instance), NullBlockProcessor.Instance, new InMemoryReceiptStorage(), specProvider, new JsonRpcConfig(), NullBloomStorage.Instance, LimboLogs.Instance, false); }
public static INdmBlockchainBridge BuildABridge() { IDbProvider memDbProvider = TestMemDbProvider.Init(); StateReader stateReader = new StateReader( new TrieStore(memDbProvider.StateDb, LimboLogs.Instance), memDbProvider.CodeDb, LimboLogs.Instance); var trieStore = new TrieStore(memDbProvider.StateDb, LimboLogs.Instance); StateProvider stateProvider = new StateProvider(trieStore, memDbProvider.CodeDb, LimboLogs.Instance); IEthereumEcdsa ecdsa = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance); BlockTree blockTree = Build.A.BlockTree().OfChainLength(1).TestObject; MainnetSpecProvider specProvider = MainnetSpecProvider.Instance; ITxPool txPool = new TxPool.TxPool(new InMemoryTxStorage(), ecdsa, new ChainHeadSpecProvider(specProvider, blockTree), new TxPoolConfig(), stateProvider, new TxValidator(specProvider.ChainId), LimboLogs.Instance); IWallet wallet = new DevWallet(new WalletConfig(), LimboLogs.Instance); ReceiptsRecovery receiptsRecovery = new ReceiptsRecovery(ecdsa, specProvider); LogFinder logFinder = new LogFinder(blockTree, new InMemoryReceiptStorage(), NullBloomStorage.Instance, LimboLogs.Instance, receiptsRecovery, 1024); ReadOnlyTxProcessingEnv processingEnv = new ReadOnlyTxProcessingEnv( new ReadOnlyDbProvider(memDbProvider, false), new TrieStore(memDbProvider.StateDb, LimboLogs.Instance), new ReadOnlyBlockTree(blockTree), specProvider, LimboLogs.Instance); BlockchainBridge blockchainBridge = new BlockchainBridge( processingEnv, txPool, new InMemoryReceiptStorage(), NullFilterStore.Instance, NullFilterManager.Instance, ecdsa, Timestamper.Default, logFinder, false, false); WalletTxSigner txSigner = new WalletTxSigner(wallet, ChainId.Mainnet); ITxSealer txSealer0 = new TxSealer(txSigner, Timestamper.Default); ITxSealer txSealer1 = new NonceReservingTxSealer(txSigner, Timestamper.Default, txPool); ITxSender txSender = new TxPoolSender(txPool, txSealer0, txSealer1); return(new NdmBlockchainBridge(blockchainBridge, blockTree, stateReader, txSender)); }
public async Task Broadcast_NewBlock_on_arrival() { Context ctx = new(); BlockTree remoteBlockTree = Build.A.BlockTree().OfChainLength(10).TestObject; BlockTree localBlockTree = Build.A.BlockTree().OfChainLength(9).TestObject; ctx.SyncServer = new SyncServer( new MemDb(), new MemDb(), localBlockTree, NullReceiptStorage.Instance, Always.Valid, Always.Valid, ctx.PeerPool, StaticSelector.Full, new SyncConfig(), NullWitnessCollector.Instance, Policy.FullGossip, MainnetSpecProvider.Instance, LimboLogs.Instance); ISyncServer remoteServer1 = Substitute.For <ISyncServer>(); SyncPeerMock syncPeerMock1 = new(remoteBlockTree, TestItem.PublicKeyA, remoteSyncServer : remoteServer1); PeerInfo peer1 = new(syncPeerMock1); ISyncServer remoteServer2 = Substitute.For <ISyncServer>(); SyncPeerMock syncPeerMock2 = new(remoteBlockTree, TestItem.PublicKeyB, remoteSyncServer : remoteServer2); PeerInfo peer2 = new(syncPeerMock2); PeerInfo[] peers = { peer1, peer2 }; ctx.PeerPool.AllPeers.Returns(peers); ctx.PeerPool.PeerCount.Returns(peers.Length); ctx.SyncServer.AddNewBlock(remoteBlockTree.Head !, peer1.SyncPeer); await Task.Delay(100); // notifications fire on separate task await Task.WhenAll(syncPeerMock1.Close(), syncPeerMock2.Close()); remoteServer1.DidNotReceive().AddNewBlock(remoteBlockTree.Head !, Arg.Any <ISyncPeer>()); remoteServer2.Received().AddNewBlock(Arg.Is <Block>(b => b.Hash == remoteBlockTree.Head !.Hash), Arg.Any <ISyncPeer>()); }
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 !); }
public void Initialize() { ISpecProvider specProvider = MainnetSpecProvider.Instance; ITxPool txPool = NullTxPool.Instance; MemDbProvider dbProvider = new MemDbProvider(); IJsonRpcConfig jsonRpcConfig = new JsonRpcConfig(); BlockTree blockTree = new BlockTree( dbProvider.BlocksDb, dbProvider.HeadersDb, dbProvider.BlockInfosDb, new ChainLevelInfoRepository(dbProvider.BlockInfosDb), specProvider, txPool, new BloomStorage(new BloomConfig(), dbProvider.HeadersDb, new InMemoryDictionaryFileStoreFactory()), new SyncConfig(), LimboLogs.Instance); _modulePool = new BoundedModulePool <IEthModule>( 1, new EthModuleFactory( dbProvider, txPool, Substitute.For <ITxSender>(), Substitute.For <ITxSigner>(), NullWallet.Instance, blockTree, new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance), NullBlockProcessor.Instance, new InMemoryReceiptStorage(), specProvider, new JsonRpcConfig(), NullBloomStorage.Instance, LimboLogs.Instance, false)); }
public void parity_netPeers_empty_ActivePeers() { LimboLogs logger = LimboLogs.Instance; MainnetSpecProvider specProvider = MainnetSpecProvider.Instance; EthereumEcdsa ethereumEcdsa = new EthereumEcdsa(specProvider.ChainId, logger); InMemoryTxStorage txStorage = new InMemoryTxStorage(); 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 TxPool.TxPool(txStorage, ethereumEcdsa, new ChainHeadInfoProvider(new FixedBlockChainHeadSpecProvider(specProvider), blockTree, new StateProvider(new TrieStore(new MemDb(), LimboLogs.Instance), new MemDb(), LimboLogs.Instance)), new TxPoolConfig(), new TxValidator(specProvider.ChainId), LimboLogs.Instance, transactionComparerProvider.GetDefaultComparer()); new OnChainTxWatcher(blockTree, txPool, specProvider, LimboLogs.Instance); IReceiptStorage receiptStorage = new InMemoryReceiptStorage(); IPeerManager peerManager = Substitute.For <IPeerManager>(); peerManager.ActivePeers.Returns(new List <Peer> { }); peerManager.ConnectedPeers.Returns(new List <Peer> { new Peer(new Node("111.1.1.1", 11111, true)) }); IParityRpcModule parityRpcModule = new ParityRpcModule(ethereumEcdsa, txPool, blockTree, receiptStorage, new Enode(TestItem.PublicKeyA, IPAddress.Loopback, 8545), _signerStore, new MemKeyStore(new[] { TestItem.PrivateKeyA }), logger, peerManager); string serialized = RpcTest.TestSerializedRequest(parityRpcModule, "parity_netPeers"); string expectedResult = "{\"jsonrpc\":\"2.0\",\"result\":{\"active\":0,\"connected\":1,\"max\":0,\"peers\":[]},\"id\":67}"; Assert.AreEqual(expectedResult, serialized); }
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); }
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() { 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 On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = false) { if (_logger.IsInfo) { _logger.Info($"CREATING NODE {privateKey.Address}"); } _logManagers[privateKey] = LimboLogs.Instance; // _logManagers[privateKey] = new OneLoggerLogManager(new ConsoleAsyncLogger(LogLevel.Debug, $"{privateKey.Address} ")); var nodeLogManager = _logManagers[privateKey]; AutoResetEvent newHeadBlockEvent = new AutoResetEvent(false); _blockEvents.Add(privateKey, newHeadBlockEvent); MemDb blocksDb = new MemDb(); MemDb headersDb = new MemDb(); MemDb blockInfoDb = new MemDb(); MemDb stateDb = new MemDb(); MemDb codeDb = new MemDb(); ISpecProvider specProvider = RinkebySpecProvider.Instance; var trieStore = new TrieStore(stateDb, nodeLogManager); StateReader stateReader = new StateReader(trieStore, codeDb, nodeLogManager); StateProvider stateProvider = new StateProvider(trieStore, codeDb, nodeLogManager); stateProvider.CreateAccount(TestItem.PrivateKeyD.Address, 100.Ether()); GoerliSpecProvider goerliSpecProvider = GoerliSpecProvider.Instance; stateProvider.Commit(goerliSpecProvider.GenesisSpec); stateProvider.CommitTree(0); BlockTree blockTree = new BlockTree(blocksDb, headersDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), goerliSpecProvider, NullBloomStorage.Instance, nodeLogManager); blockTree.NewHeadBlock += (sender, args) => { _blockEvents[privateKey].Set(); }; ITransactionComparerProvider transactionComparerProvider = new TransactionComparerProvider(specProvider, blockTree); TxPool.TxPool txPool = new TxPool.TxPool(new InMemoryTxStorage(), _ethereumEcdsa, new ChainHeadInfoProvider(new FixedBlockChainHeadSpecProvider(GoerliSpecProvider.Instance), blockTree, stateProvider), new TxPoolConfig(), new TxValidator(goerliSpecProvider.ChainId), _logManager, transactionComparerProvider.GetDefaultComparer()); _pools[privateKey] = txPool; BlockhashProvider blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance); _blockTrees.Add(privateKey, blockTree); SnapshotManager snapshotManager = new SnapshotManager(_cliqueConfig, blocksDb, blockTree, _ethereumEcdsa, nodeLogManager); _snapshotManager[privateKey] = snapshotManager; CliqueSealer cliqueSealer = new CliqueSealer(new Signer(ChainId.Goerli, privateKey, LimboLogs.Instance), _cliqueConfig, snapshotManager, nodeLogManager); _genesis.Header.StateRoot = _genesis3Validators.Header.StateRoot = stateProvider.StateRoot; _genesis.Header.Hash = _genesis.Header.CalculateHash(); _genesis3Validators.Header.Hash = _genesis3Validators.Header.CalculateHash(); StorageProvider storageProvider = new StorageProvider(trieStore, stateProvider, nodeLogManager); TransactionProcessor transactionProcessor = new TransactionProcessor(goerliSpecProvider, stateProvider, storageProvider, new VirtualMachine(stateProvider, storageProvider, blockhashProvider, specProvider, nodeLogManager), nodeLogManager); BlockProcessor blockProcessor = new BlockProcessor( goerliSpecProvider, Always.Valid, NoBlockRewards.Instance, transactionProcessor, stateProvider, storageProvider, txPool, NullReceiptStorage.Instance, NullWitnessCollector.Instance, nodeLogManager); BlockchainProcessor processor = new BlockchainProcessor(blockTree, blockProcessor, new AuthorRecoveryStep(snapshotManager), nodeLogManager, BlockchainProcessor.Options.NoReceipts); processor.Start(); var minerTrieStore = trieStore.AsReadOnly(); StateProvider minerStateProvider = new StateProvider(minerTrieStore, codeDb, nodeLogManager); StorageProvider minerStorageProvider = new StorageProvider(minerTrieStore, minerStateProvider, nodeLogManager); VirtualMachine minerVirtualMachine = new VirtualMachine(minerStateProvider, minerStorageProvider, blockhashProvider, specProvider, nodeLogManager); TransactionProcessor minerTransactionProcessor = new TransactionProcessor(goerliSpecProvider, minerStateProvider, minerStorageProvider, minerVirtualMachine, nodeLogManager); BlockProcessor minerBlockProcessor = new BlockProcessor( goerliSpecProvider, Always.Valid, NoBlockRewards.Instance, minerTransactionProcessor, minerStateProvider, minerStorageProvider, txPool, NullReceiptStorage.Instance, NullWitnessCollector.Instance, nodeLogManager); BlockchainProcessor minerProcessor = new BlockchainProcessor(blockTree, minerBlockProcessor, new AuthorRecoveryStep(snapshotManager), nodeLogManager, BlockchainProcessor.Options.NoReceipts); if (withGenesisAlreadyProcessed) { ProcessGenesis(privateKey); } ITxFilterPipeline txFilterPipeline = TxFilterPipelineBuilder.CreateStandardFilteringPipeline(nodeLogManager, specProvider); TxPoolTxSource txPoolTxSource = new TxPoolTxSource(txPool, stateReader, specProvider, transactionComparerProvider, nodeLogManager, txFilterPipeline); CliqueBlockProducer blockProducer = new CliqueBlockProducer( txPoolTxSource, minerProcessor, minerStateProvider, blockTree, _timestamper, new CryptoRandom(), snapshotManager, cliqueSealer, new TargetAdjustedGasLimitCalculator(goerliSpecProvider, new MiningConfig()), MainnetSpecProvider.Instance, _cliqueConfig, nodeLogManager); blockProducer.Start(); _producers.Add(privateKey, blockProducer); return(this); }
private void MineBlock(BlockTree tree, Block block) { tree.SuggestBlock(block); tree.UpdateMainChain(block); }
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); }
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); }
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); }
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 On CreateNode(PrivateKey privateKey, bool withGenesisAlreadyProcessed = false) { if (_logger.IsInfo) { _logger.Info($"CREATING NODE {privateKey.Address}"); } _logManagers[privateKey] = LimboLogs.Instance; // _logManagers[privateKey] = new OneLoggerLogManager(new ConsoleAsyncLogger(LogLevel.Debug, $"{privateKey.Address} ")); var nodeLogManager = _logManagers[privateKey]; AutoResetEvent newHeadBlockEvent = new AutoResetEvent(false); _blockEvents.Add(privateKey, newHeadBlockEvent); MemDb blocksDb = new MemDb(); MemDb headersDb = new MemDb(); MemDb blockInfoDb = new MemDb(); ISnapshotableDb stateDb = new StateDb(); ISnapshotableDb codeDb = new StateDb(); ISpecProvider specProvider = RinkebySpecProvider.Instance; StateReader stateReader = new StateReader(stateDb, codeDb, nodeLogManager); StateProvider stateProvider = new StateProvider(stateDb, codeDb, nodeLogManager); stateProvider.CreateAccount(TestItem.PrivateKeyD.Address, 100.Ether()); stateProvider.Commit(GoerliSpecProvider.Instance.GenesisSpec); stateProvider.CommitTree(); TxPool.TxPool txPool = new TxPool.TxPool(new InMemoryTxStorage(), _timestamper, _ethereumEcdsa, GoerliSpecProvider.Instance, new TxPoolConfig(), stateProvider, _logManager); _pools[privateKey] = txPool; BlockTree blockTree = new BlockTree(blocksDb, headersDb, blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), GoerliSpecProvider.Instance, txPool, NullBloomStorage.Instance, nodeLogManager); blockTree.NewHeadBlock += (sender, args) => { _blockEvents[privateKey].Set(); }; BlockhashProvider blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance); _blockTrees.Add(privateKey, blockTree); IBasicWallet wallet = new BasicWallet(privateKey); SnapshotManager snapshotManager = new SnapshotManager(_cliqueConfig, blocksDb, blockTree, _ethereumEcdsa, nodeLogManager); _snapshotManager[privateKey] = snapshotManager; CliqueSealer cliqueSealer = new CliqueSealer(wallet, _cliqueConfig, snapshotManager, privateKey.Address, nodeLogManager); _genesis.Header.StateRoot = _genesis3Validators.Header.StateRoot = stateProvider.StateRoot; _genesis.Header.Hash = _genesis.Header.CalculateHash(); _genesis3Validators.Header.Hash = _genesis3Validators.Header.CalculateHash(); StorageProvider storageProvider = new StorageProvider(stateDb, stateProvider, nodeLogManager); TransactionProcessor transactionProcessor = new TransactionProcessor(GoerliSpecProvider.Instance, stateProvider, storageProvider, new VirtualMachine(stateProvider, storageProvider, blockhashProvider, specProvider, nodeLogManager), nodeLogManager); BlockProcessor blockProcessor = new BlockProcessor(GoerliSpecProvider.Instance, Always.Valid, NoBlockRewards.Instance, transactionProcessor, stateDb, codeDb, stateProvider, storageProvider, txPool, NullReceiptStorage.Instance, nodeLogManager); BlockchainProcessor processor = new BlockchainProcessor(blockTree, blockProcessor, new AuthorRecoveryStep(snapshotManager), nodeLogManager, false); processor.Start(); StateProvider minerStateProvider = new StateProvider(stateDb, codeDb, nodeLogManager); StorageProvider minerStorageProvider = new StorageProvider(stateDb, minerStateProvider, nodeLogManager); VirtualMachine minerVirtualMachine = new VirtualMachine(minerStateProvider, minerStorageProvider, blockhashProvider, specProvider, nodeLogManager); TransactionProcessor minerTransactionProcessor = new TransactionProcessor(GoerliSpecProvider.Instance, minerStateProvider, minerStorageProvider, minerVirtualMachine, nodeLogManager); BlockProcessor minerBlockProcessor = new BlockProcessor(GoerliSpecProvider.Instance, Always.Valid, NoBlockRewards.Instance, minerTransactionProcessor, stateDb, codeDb, minerStateProvider, minerStorageProvider, txPool, NullReceiptStorage.Instance, nodeLogManager); BlockchainProcessor minerProcessor = new BlockchainProcessor(blockTree, minerBlockProcessor, new AuthorRecoveryStep(snapshotManager), nodeLogManager, false); if (withGenesisAlreadyProcessed) { ProcessGenesis(privateKey); } TxPoolTxSource txPoolTxSource = new TxPoolTxSource(txPool, stateReader, nodeLogManager); CliqueBlockProducer blockProducer = new CliqueBlockProducer(txPoolTxSource, minerProcessor, minerStateProvider, blockTree, _timestamper, new CryptoRandom(), snapshotManager, cliqueSealer, privateKey.Address, _cliqueConfig, nodeLogManager); blockProducer.Start(); _producers.Add(privateKey, blockProducer); return(this); }
private static void MineBlock(BlockTree tree, Block block) { tree.SuggestBlock(block); }