示例#1
0
        private Task StartSync()
        {
            if (!_initConfig.SynchronizationEnabled)
            {
                if (_logger.IsWarn) _logger.Warn($"Skipping blockchain synchronization init due to ({nameof(IInitConfig.SynchronizationEnabled)} set to false)");
                return Task.CompletedTask;
            }

            if (_logger.IsDebug) _logger.Debug($"Starting synchronization from block {_blockTree.Head.ToString(BlockHeader.Format.Short)}.");

            _syncManager.Start();
            return Task.CompletedTask;
        }
示例#2
0
        public void Retrieves_missing_blocks_in_batches()
        {
            _remoteBlockTree = Build.A.BlockTree(_genesisBlock).OfChainLength(QueueBasedSyncManager.MaxBatchSize * 2).TestObject;
            ISynchronizationPeer peer = new SynchronizationPeerMock(_remoteBlockTree);

            ManualResetEvent resetEvent = new ManualResetEvent(false);

            _manager.SyncEvent += (sender, args) =>
            {
                if (args.SyncStatus == SyncStatus.Completed || args.SyncStatus == SyncStatus.Failed)
                {
                    resetEvent.Set();
                }
            };
            _manager.Start();
            _manager.AddPeer(peer);

            resetEvent.WaitOne(_standardTimeoutUnit);
            Assert.AreEqual(QueueBasedSyncManager.MaxBatchSize * 2 - 1, (int)_blockTree.BestSuggested.Number);
        }
示例#3
0
        private Task StartSync()
        {
            if (!_initConfig.SynchronizationEnabled)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Skipping blockchain synchronization init ({nameof(IInitConfig.SynchronizationEnabled)} = false)");
                }
                return(Task.CompletedTask);
            }

            if (_logger.IsDebug)
            {
                _logger.Debug($"Starting synchronization from block {_blockTree.Head.ToString(BlockHeader.Format.Short)}.");
            }

            _syncManager.Start();
            return(Task.CompletedTask);
        }
示例#4
0
            public SyncingContext()
            {
                MemDb stateDb = new MemDb();

                BlockTree   = new BlockTree(new MemDb(), new MemDb(), new SingleReleaseSpecProvider(Constantinople.Instance, 1), NullTransactionPool.Instance, LimboLogs.Instance);
                SyncManager = new QueueBasedSyncManager(
                    stateDb,
                    BlockTree,
                    TestBlockValidator.AlwaysValid,
                    TestHeaderValidator.AlwaysValid,
                    TestTransactionValidator.AlwaysValid,
                    LimboLogs.Instance,
                    new BlockchainConfig(),
                    new PerfService(LimboLogs.Instance),
                    NullReceiptStorage.Instance);


                SyncManager.Start();
                SyncManager.SyncEvent += (sender, args) => TestContext.WriteLine(args.SyncStatus);
            }
示例#5
0
        private async Task StartProcessing(BlockTree blockTree, TransactionStore transactionStore, BlockValidator blockValidator, HeaderValidator headerValidator, TransactionValidator txValidator, InitParams initParams)
        {
            await blockTree.LoadBlocksFromDb(_runnerCancellation.Token).ContinueWith(async t =>
            {
                if (t.IsFaulted)
                {
                    if (_logger.IsErrorEnabled)
                    {
                        _logger.Error("Loading blocks from DB failed.", t.Exception);
                    }
                }
                else if (t.IsCanceled)
                {
                    if (_logger.IsWarnEnabled)
                    {
                        _logger.Warn("Loading blocks from DB cancelled.");
                    }
                }
                else
                {
                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info("Loaded all blocks from DB");
                    }
                    if (!initParams.SynchronizationEnabled)
                    {
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info("Synchronization disabled.");
                        }
                    }
                    else
                    {
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info($"Starting synchronization from block {blockTree.Head.ToString(BlockHeader.Format.Short)}.");
                        }
                        // TODO: only start sync manager after queued blocks are processed
                        _syncManager = new SynchronizationManager(
                            blockTree,
                            blockValidator,
                            headerValidator,
                            transactionStore,
                            txValidator,
                            _logger, new BlockchainConfig());

                        _syncManager.Start();

                        await InitNet(initParams.P2PPort ?? 30303).ContinueWith(initNetTask =>
                        {
                            if (initNetTask.IsFaulted)
                            {
                                _logger.Error("Unable to initialize network layer.", initNetTask.Exception);
                            }
                        });

                        if (initParams.DiscoveryEnabled)
                        {
                            await InitDiscovery(initParams).ContinueWith(initDiscoveryTask =>
                            {
                                if (initDiscoveryTask.IsFaulted)
                                {
                                    _logger.Error("Unable to initialize discovery protocol.", initDiscoveryTask.Exception);
                                }
                            });
                        }
                        else if (_logger.IsInfoEnabled)
                        {
                            _logger.Info("Discovery protocol disabled");
                        }

                        await InitPeerManager().ContinueWith(initPeerManagerTask =>
                        {
                            if (initPeerManagerTask.IsFaulted)
                            {
                                _logger.Error("Unable to initialize peer manager.", initPeerManagerTask.Exception);
                            }
                        });
                    }
                }
            });
        }
示例#6
0
        private static void InitBlockchain(ChainSpec chainSpec, bool isMining, int miningDelay)
        {
            /* spec */
            var blockMiningTime      = TimeSpan.FromMilliseconds(miningDelay);
            var transactionDelay     = TimeSpan.FromMilliseconds(miningDelay / 4);
            var specProvider         = RopstenSpecProvider.Instance;
            var difficultyCalculator = new DifficultyCalculator(specProvider);
            // var sealEngine = new EthashSealEngine(new Ethash());
            var sealEngine = new FakeSealEngine(blockMiningTime, false);

            /* sync */
            var transactionStore = new TransactionStore();
            var blockTree        = new BlockTree(RopstenSpecProvider.Instance, ChainLogger);

            /* validation */
            var headerValidator = new HeaderValidator(difficultyCalculator, blockTree, sealEngine, specProvider, ChainLogger);
            var ommersValidator = new OmmersValidator(blockTree, headerValidator, ChainLogger);
            var txValidator     = new TransactionValidator(new SignatureValidator(ChainId.Ropsten));
            var blockValidator  = new BlockValidator(txValidator, headerValidator, ommersValidator, specProvider, ChainLogger);

            /* state */
            var dbProvider        = new DbProvider(StateLogger);
            var codeDb            = new InMemoryDb();
            var stateDb           = new InMemoryDb();
            var stateTree         = new StateTree(stateDb);
            var stateProvider     = new StateProvider(stateTree, StateLogger, codeDb);
            var storageProvider   = new StorageProvider(dbProvider, stateProvider, StateLogger);
            var storageDbProvider = new DbProvider(StateLogger);

            /* blockchain */
            var ethereumSigner = new EthereumSigner(specProvider, ChainLogger);

            /* blockchain processing */
            var blockhashProvider    = new BlockhashProvider(blockTree);
            var virtualMachine       = new VirtualMachine(specProvider, stateProvider, storageProvider, blockhashProvider, EvmLogger);
            var transactionProcessor = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, ethereumSigner, ChainLogger);
            var rewardCalculator     = new RewardCalculator(specProvider);
            var blockProcessor       = new BlockProcessor(specProvider, blockValidator, rewardCalculator, transactionProcessor, storageDbProvider, stateProvider, storageProvider, transactionStore, ChainLogger);

            _blockchainProcessor = new BlockchainProcessor(blockTree, sealEngine, transactionStore, difficultyCalculator, blockProcessor, ChainLogger);

            /* genesis */
            foreach (KeyValuePair <Address, BigInteger> allocation in chainSpec.Allocations)
            {
                stateProvider.CreateAccount(allocation.Key, allocation.Value);
            }

            stateProvider.Commit(specProvider.GenesisSpec);

            var testTransactionsGenerator = new TestTransactionsGenerator(transactionStore, ethereumSigner, transactionDelay, ChainLogger);

            stateProvider.CreateAccount(testTransactionsGenerator.SenderAddress, 1000.Ether());
            stateProvider.Commit(specProvider.GenesisSpec);

            if (isMining)
            {
                testTransactionsGenerator.Start();
            }

            Block genesis = chainSpec.Genesis;

            genesis.Header.StateRoot = stateProvider.StateRoot;
            genesis.Header.RecomputeHash();
            // we are adding test transactions account so the state root will change (not an actual ropsten at the moment)
//            var expectedGenesisHash = "0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d";
//            if (chainSpec.Genesis.Hash != new Keccak(expectedGenesisHash))
//            {
//                throw new Exception($"Unexpected genesis hash for Ropsten, expected {expectedGenesisHash}, but was {chainSpec.Genesis.Hash}");
//            }

            /* start test processing */
            sealEngine.IsMining = isMining;
            _blockchainProcessor.Start();
            blockTree.AddBlock(genesis);

            _syncManager = new SynchronizationManager(
                blockTree,
                blockValidator,
                headerValidator,
                transactionStore,
                txValidator,
                NetworkLogger);
            _syncManager.Start();
        }