示例#1
0
        public TransactionPool(ITransactionStorage transactionStorage,
                               IPendingTransactionThresholdValidator pendingTransactionThresholdValidator,
                               ITimestamp timestamp, IEthereumSigner signer, ISpecProvider specProvider, ILogManager logManager,
                               int removePendingTransactionInterval = 600,
                               int peerNotificationThreshold        = 20)
        {
            _logger             = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _transactionStorage = transactionStorage ?? throw new ArgumentNullException(nameof(transactionStorage));
            _pendingTransactionThresholdValidator = pendingTransactionThresholdValidator;
            _timestamp    = timestamp ?? throw new ArgumentNullException(nameof(timestamp));
            _signer       = signer ?? throw new ArgumentNullException(nameof(signer));
            _specProvider = specProvider ?? throw new ArgumentNullException(nameof(specProvider));
            _peerNotificationThreshold = peerNotificationThreshold;
            if (removePendingTransactionInterval <= 0)
            {
                return;
            }

            var timer = new Timer(removePendingTransactionInterval * 1000);

            timer.Elapsed += OnTimerElapsed;
            timer.Start();

            _ownTimer           = new Timer(500);
            _ownTimer.Elapsed  += OwnTimerOnElapsed;
            _ownTimer.AutoReset = false;
            _ownTimer.Start();
        }
示例#2
0
 public SnapshotManager(ICliqueConfig cliqueConfig, IDb blocksDb, IBlockTree blockTree, IEthereumSigner signer, ILogManager logManager)
 {
     _logger       = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
     _cliqueConfig = cliqueConfig ?? throw new ArgumentNullException(nameof(cliqueConfig));
     _signatures   = new LruCache <Keccak, Address>(Clique.InMemorySignatures);
     _signer       = signer ?? throw new ArgumentNullException(nameof(signer));
     _blocksDb     = blocksDb ?? throw new ArgumentNullException(nameof(blocksDb));
     _blockTree    = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
 }
示例#3
0
 public BlockchainBridge(IEthereumSigner signer, IStateProvider stateProvider, IKeyStore keyStore, IBlockTree blockTree, IDb db, ITransactionStore transactionStore)
 {
     _signer           = signer;
     _stateProvider    = stateProvider;
     _keyStore         = keyStore;
     _blockTree        = blockTree;
     _db               = db;
     _transactionStore = transactionStore;
 }
示例#4
0
 public void Setup()
 {
     _genesisBlock                 = Build.A.Block.WithNumber(0).TestObject;
     _remoteBlockTree              = Build.A.BlockTree(_genesisBlock).OfChainLength(0).TestObject;
     _logManager                   = LimboLogs.Instance;
     _specProvider                 = RopstenSpecProvider.Instance;
     _ethereumSigner               = new EthereumSigner(_specProvider, _logManager);
     _noTransactionStorage         = NullTransactionStorage.Instance;
     _inMemoryTransactionStorage   = new InMemoryTransactionStorage();
     _persistentTransactionStorage = new PersistentTransactionStorage(new MemDb(), _specProvider);
 }
        public void Setup()
        {
            _specProvider = MainNetSpecProvider.Instance;
            StateDb stateDb = new StateDb();

            _stateProvider = new StateProvider(new StateTree(stateDb), new MemDb(), LimboLogs.Instance);
            StorageProvider storageProvider = new StorageProvider(stateDb, _stateProvider, LimboLogs.Instance);
            VirtualMachine  virtualMachine  = new VirtualMachine(_stateProvider, storageProvider, Substitute.For <IBlockhashProvider>(), LimboLogs.Instance);

            _transactionProcessor = new TransactionProcessor(_specProvider, _stateProvider, storageProvider, virtualMachine, LimboLogs.Instance);
            _ethereumSigner       = new EthereumSigner(_specProvider, LimboLogs.Instance);
        }
示例#6
0
        public CliqueSealEngine(CliqueConfig config, IEthereumSigner signer, PrivateKey key, IDb blocksDb, IBlockTree blockTree, ILogManager logManager)
        {
            _logger    = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _config    = config ?? throw new ArgumentNullException(nameof(config));
            _blocksDb  = blocksDb ?? throw new ArgumentNullException(nameof(blocksDb));
            _signer    = signer ?? throw new ArgumentNullException(nameof(signer));
            _blockTree = blockTree ?? throw new ArgumentNullException();
            _key       = key ?? throw new ArgumentNullException(nameof(key));

            if (config.Epoch == 0)
            {
                config.Epoch = Clique.DefaultEpochLength;
            }
        }
示例#7
0
        private void TestEncodeDecode(IEthereumSigner signer)
        {
            AuthEip8Message authMessage = new AuthEip8Message();

            authMessage.Nonce     = new byte[AuthMessageSerializer.NonceLength]; // sic!
            authMessage.Signature = signer.Sign(_privateKey, Keccak.Compute("anything"));
            authMessage.PublicKey = _privateKey.PublicKey;
            _random.NextBytes(authMessage.Nonce);
            byte[]          data  = _serializer.Serialize(authMessage);
            AuthEip8Message after = _serializer.Deserialize(data);

            Assert.AreEqual(authMessage.Signature, after.Signature);
            Assert.AreEqual(authMessage.PublicKey, after.PublicKey);
            Assert.True(Bytes.AreEqual(authMessage.Nonce, after.Nonce));
            Assert.AreEqual(authMessage.Version, after.Version);
        }
示例#8
0
        public VirtualMachineTestsBase()
        {
            ILogManager logger = LimboLogs.Instance;;
            IDb         codeDb = new StateDb();

            _stateDb = new StateDb();
            StateTree stateTree = new StateTree(_stateDb);

            TestState       = new StateProvider(stateTree, codeDb, logger);
            Storage         = new StorageProvider(_stateDb, TestState, logger);
            _ethereumSigner = new EthereumSigner(SpecProvider, logger);
            IBlockhashProvider blockhashProvider = new TestBlockhashProvider();
            IVirtualMachine    virtualMachine    = new VirtualMachine(TestState, Storage, blockhashProvider, logger);

            _processor = new TransactionProcessor(SpecProvider, TestState, Storage, virtualMachine, logger);
        }
示例#9
0
        public TestTransactionsGenerator(ITransactionPool transactionPool, IEthereumSigner signer, TimeSpan txDelay, ILogManager logManager)
        {
            _logger          = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _transactionPool = transactionPool ?? throw new ArgumentNullException(nameof(transactionPool));
            _signer          = signer ?? throw new ArgumentNullException(nameof(signer));
            _txDelay         = txDelay;

            if (txDelay > TimeSpan.FromMilliseconds(0))
            {
                _timer.Elapsed += TimerOnElapsed;
                _timer.Interval = txDelay.TotalMilliseconds;
            }

            _privateKeyBytes[31] = 1;
            _privateKey          = new PrivateKey(_privateKeyBytes);
            SenderAddress        = _privateKey.PublicKey.Address;
            _logger.Debug($"Test transactions will be coming from {SenderAddress}.");
        }
        public VirtualMachineTestsBase()
        {
            SpecProvider = RopstenSpecProvider.Instance;
            ILogManager logger = NullLogManager.Instance;
            IDb         codeDb = new MemDb();

            _stateDb = new SnapshotableDb(new MemDb());
            StateTree stateTree = new StateTree(_stateDb);

            TestState          = new StateProvider(stateTree, codeDb, logger);
            _storageDbProvider = new MemDbProvider(logger);
            Storage            = new StorageProvider(_storageDbProvider, TestState, logger);
            _ethereumSigner    = new EthereumSigner(SpecProvider, logger);
            IBlockhashProvider blockhashProvider = new TestBlockhashProvider();
            IVirtualMachine    virtualMachine    = new VirtualMachine(TestState, Storage, blockhashProvider, logger);

            _processor = new TransactionProcessor(SpecProvider, TestState, Storage, virtualMachine, this, logger);
        }
示例#11
0
        private void TestEncodeDecode(IEthereumSigner signer)
        {
            AuthMessage authMessage = new AuthMessage();
            authMessage.EphemeralPublicHash = new Keccak(new byte[AuthMessageSerializer.EphemeralHashLength]);
            authMessage.Nonce = new byte[AuthMessageSerializer.NonceLength];
            authMessage.Signature = signer.Sign(_privateKey, Keccak.Compute("anything"));
            _random.NextBytes(authMessage.EphemeralPublicHash.Bytes);
            authMessage.PublicKey = _privateKey.PublicKey;
            _random.NextBytes(authMessage.Nonce);
            authMessage.IsTokenUsed = true;
            byte[] bytes = _serializer.Serialize(authMessage);
            AuthMessage after = _serializer.Deserialize(bytes);

            Assert.AreEqual(authMessage.Signature, after.Signature);
            Assert.AreEqual(authMessage.EphemeralPublicHash, after.EphemeralPublicHash);
            Assert.AreEqual(authMessage.PublicKey, after.PublicKey);
            Assert.True(Bytes.AreEqual(authMessage.Nonce, after.Nonce));
            Assert.AreEqual(authMessage.IsTokenUsed, after.IsTokenUsed);
        }
示例#12
0
        public BlockchainProcessor(
            IBlockTree blockTree,
            ISealEngine sealEngine,
            ITransactionStore transactionStore,
            IDifficultyCalculator difficultyCalculator,
            IBlockProcessor blockProcessor,
            IEthereumSigner signer,
            ILogManager logManager)
        {
            _logger    = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _blockTree = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
            _blockTree.NewBestSuggestedBlock += OnNewBestBlock;

            _transactionStore     = transactionStore ?? throw new ArgumentNullException(nameof(transactionStore));
            _difficultyCalculator = difficultyCalculator ?? throw new ArgumentNullException(nameof(difficultyCalculator));
            _sealEngine           = sealEngine ?? throw new ArgumentNullException(nameof(sealEngine));
            _blockProcessor       = blockProcessor ?? throw new ArgumentNullException(nameof(blockProcessor));
            _signer = signer ?? throw new ArgumentNullException(nameof(signer));
        }
示例#13
0
 public BlockchainBridge(IEthereumSigner signer,
                         IStateProvider stateProvider,
                         IBlockTree blockTree,
                         ITransactionPool transactionPool,
                         ITransactionPoolInfoProvider transactionPoolInfoProvider,
                         IReceiptStorage receiptStorage,
                         IFilterStore filterStore,
                         IFilterManager filterManager,
                         IWallet wallet,
                         ITransactionProcessor transactionProcessor)
 {
     _signer                      = signer ?? throw new ArgumentNullException(nameof(signer));
     _stateProvider               = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider));
     _blockTree                   = blockTree ?? throw new ArgumentNullException(nameof(blockTree));
     _transactionPool             = transactionPool ?? throw new ArgumentNullException(nameof(_transactionPool));
     _transactionPoolInfoProvider = transactionPoolInfoProvider ?? throw new ArgumentNullException(nameof(transactionPoolInfoProvider));
     _receiptStorage              = receiptStorage ?? throw new ArgumentNullException(nameof(receiptStorage));
     _filterStore                 = filterStore ?? throw new ArgumentException(nameof(filterStore));
     _filterManager               = filterManager ?? throw new ArgumentException(nameof(filterManager));
     _wallet                      = wallet ?? throw new ArgumentException(nameof(wallet));
     _transactionProcessor        = transactionProcessor ?? throw new ArgumentException(nameof(transactionProcessor));
 }
示例#14
0
        public TransactionPool(ITransactionStorage transactionStorage,
                               IPendingTransactionThresholdValidator pendingTransactionThresholdValidator,
                               ITimestamp timestamp, IEthereumSigner signer, ILogManager logManager,
                               int removePendingTransactionInterval = 600,
                               int peerNotificationThreshold        = 20)
        {
            _logger             = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager));
            _transactionStorage = transactionStorage;
            _pendingTransactionThresholdValidator = pendingTransactionThresholdValidator;
            _timestamp = timestamp;
            _signer    = signer;
            _peerNotificationThreshold = peerNotificationThreshold;
            if (removePendingTransactionInterval <= 0)
            {
                return;
            }

            var timer = new Timer {
                Interval = removePendingTransactionInterval * 1000
            };

            timer.Elapsed += OnTimerElapsed;
            timer.Start();
        }
 // TODO: auto create signer here
 public TransactionBuilder SignedAndResolved(IEthereumSigner signer, PrivateKey privateKey, UInt256 blockNumber)
 {
     signer.Sign(privateKey, TestObjectInternal, blockNumber);
     TestObjectInternal.SenderAddress = privateKey.Address;
     return(this);
 }
示例#16
0
        private async Task InitBlockchain()
        {
            ChainSpec chainSpec = LoadChainSpec(_initConfig.ChainSpecPath);

            /* spec */
            // TODO: rebuild to use chainspec
            ISpecProvider specProvider;

            if (chainSpec.ChainId == RopstenSpecProvider.Instance.ChainId)
            {
                specProvider = RopstenSpecProvider.Instance;
            }
            else if (chainSpec.ChainId == MainNetSpecProvider.Instance.ChainId)
            {
                specProvider = MainNetSpecProvider.Instance;
            }
            else
            {
                throw new NotSupportedException($"Not yet tested, not yet supported ChainId {chainSpec.ChainId}");
            }

            var ethereumSigner = new EthereumSigner(
                specProvider,
                _logManager);

            var transactionStore = new TransactionStore();

            var sealEngine = ConfigureSealEngine(
                transactionStore,
                ethereumSigner);

            /* sync */
            IDbConfig dbConfig = _configProvider.GetConfig <IDbConfig>();

            foreach (PropertyInfo propertyInfo in typeof(IDbConfig).GetProperties())
            {
                _logger.Info($"DB {propertyInfo.Name}: {propertyInfo.GetValue(dbConfig)}");
            }

            var blocksDb = new DbOnTheRocks(
                Path.Combine(_dbBasePath, DbOnTheRocks.BlocksDbPath),
                dbConfig);

            var blockInfosDb = new DbOnTheRocks(
                Path.Combine(_dbBasePath, DbOnTheRocks.BlockInfosDbPath),
                dbConfig);

            var receiptsDb = new DbOnTheRocks(
                Path.Combine(_dbBasePath, DbOnTheRocks.ReceiptsDbPath),
                dbConfig);

            /* blockchain */
            _blockTree = new BlockTree(
                blocksDb,
                blockInfosDb,
                receiptsDb,
                specProvider,
                _logManager);

            var difficultyCalculator = new DifficultyCalculator(
                specProvider);

            /* validation */
            var headerValidator = new HeaderValidator(
                difficultyCalculator,
                _blockTree,
                sealEngine,
                specProvider,
                _logManager);

            var ommersValidator = new OmmersValidator(
                _blockTree,
                headerValidator,
                _logManager);

            var txValidator = new TransactionValidator(
                new SignatureValidator(specProvider.ChainId));

            var blockValidator = new BlockValidator(
                txValidator,
                headerValidator,
                ommersValidator,
                specProvider,
                _logManager);

            /* state */
            var dbProvider = new RocksDbProvider(
                _dbBasePath,
                _logManager,
                dbConfig);

            var stateDb = dbProvider.GetOrCreateStateDb();

            var stateTree = new StateTree(stateDb);

            var stateProvider = new StateProvider(
                stateTree,
                dbProvider.GetOrCreateCodeDb(),
                _logManager);

            var storageProvider = new StorageProvider(
                dbProvider,
                stateProvider,
                _logManager);

            /* blockchain processing */
            var blockhashProvider = new BlockhashProvider(
                _blockTree);

            var virtualMachine = new VirtualMachine(
                stateProvider,
                storageProvider,
                blockhashProvider,
                _logManager);

            var transactionProcessor = new TransactionProcessor(
                specProvider,
                stateProvider,
                storageProvider,
                virtualMachine,
                _tracer,
                _logManager);

            var rewardCalculator = new RewardCalculator(
                specProvider);

            var blockProcessor = new BlockProcessor(
                specProvider,
                blockValidator,
                rewardCalculator,
                transactionProcessor,
                dbProvider,
                stateProvider,
                storageProvider,
                transactionStore,
                _logManager);

            _blockchainProcessor = new BlockchainProcessor(
                _blockTree,
                sealEngine,
                transactionStore,
                difficultyCalculator,
                blockProcessor,
                ethereumSigner,
                _logManager, _perfService);

            // create shared objects between discovery and peer manager
            _nodeFactory       = new NodeFactory();
            _nodeStatsProvider = new NodeStatsProvider(_configProvider.GetConfig <IStatsConfig>(), _nodeFactory, _logManager);

            var jsonSerializer = new JsonSerializer(
                _logManager);

            var encrypter = new AesEncrypter(
                _configProvider,
                _logManager);

            _keyStore = new FileKeyStore(
                _configProvider,
                jsonSerializer,
                encrypter,
                _cryptoRandom,
                _logManager);

            //creating blockchain bridge
            BlockchainBridge = new BlockchainBridge(
                ethereumSigner,
                stateProvider,
                _keyStore,
                _blockTree,
                stateDb,
                transactionStore);

            EthereumSigner = ethereumSigner;

            _blockchainProcessor.Start();
            LoadGenesisBlock(chainSpec,
                             string.IsNullOrWhiteSpace(_initConfig.GenesisHash) ? null : new Keccak(_initConfig.GenesisHash),
                             _blockTree, stateProvider, specProvider);

#pragma warning disable 4014
            LoadBlocksFromDb();
#pragma warning restore 4014

            await InitializeNetwork(
                transactionStore,
                blockValidator,
                headerValidator,
                txValidator);
        }
示例#17
0
        private async Task InitBlockchain()
        {
            /* spec */
            if (_chainSpec.ChainId == RopstenSpecProvider.Instance.ChainId)
            {
                _specProvider = RopstenSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == MainNetSpecProvider.Instance.ChainId)
            {
                _specProvider = MainNetSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == RinkebySpecProvider.Instance.ChainId)
            {
                _specProvider = RinkebySpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == GoerliSpecProvider.Instance.ChainId)
            {
                _specProvider = GoerliSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == SturebySpecProvider.Instance.ChainId)
            {
                _specProvider = SturebySpecProvider.Instance;
            }
            else
            {
                _specProvider = new SingleReleaseSpecProvider(LatestRelease.Instance, _chainSpec.ChainId);
            }

            /* sync */
            IDbConfig dbConfig = _configProvider.GetConfig <IDbConfig>();

            foreach (PropertyInfo propertyInfo in typeof(IDbConfig).GetProperties())
            {
                _logger.Info($"DB {propertyInfo.Name}: {propertyInfo.GetValue(dbConfig)}");
            }

            _dbProvider = HiveEnabled
                ? (IDbProvider) new MemDbProvider()
                : new RocksDbProvider(_initConfig.BaseDbPath, dbConfig, _logManager, _initConfig.StoreTraces, _initConfig.StoreReceipts);

            _ethereumSigner  = new EthereumSigner(_specProvider, _logManager);
            _transactionPool = new TransactionPool(
                new PersistentTransactionStorage(_dbProvider.PendingTxsDb, _specProvider),
                new PendingTransactionThresholdValidator(_initConfig.ObsoletePendingTransactionInterval,
                                                         _initConfig.RemovePendingTransactionInterval), new Timestamp(),
                _ethereumSigner, _specProvider, _logManager, _initConfig.RemovePendingTransactionInterval,
                _initConfig.PeerNotificationThreshold);
            _receiptStorage = new PersistentReceiptStorage(_dbProvider.ReceiptsDb, _specProvider);

//            IDbProvider debugRecorder = new RocksDbProvider(Path.Combine(_dbBasePath, "debug"), dbConfig);
//            _dbProvider = new RpcDbProvider(_jsonSerializer, new BasicJsonRpcClient(KnownRpcUris.NethVm1, _jsonSerializer, _logManager), _logManager, debugRecorder);

//            IDbProvider debugReader = new ReadOnlyDbProvider(new RocksDbProvider(Path.Combine(_dbBasePath, "debug"), dbConfig));
//            _dbProvider = debugReader;

            _blockTree = new BlockTree(
                _dbProvider.BlocksDb,
                _dbProvider.BlockInfosDb,
                _specProvider,
                _transactionPool,
                _logManager);

            _recoveryStep = new TxSignaturesRecoveryStep(_ethereumSigner, _transactionPool);

            CliqueConfig cliqueConfig = null;

            _snapshotManager = null;
            switch (_chainSpec.SealEngineType)
            {
            case SealEngineType.None:
                _sealer           = NullSealEngine.Instance;
                _sealValidator    = NullSealEngine.Instance;
                _rewardCalculator = NoBlockRewards.Instance;
                break;

            case SealEngineType.Clique:
                _rewardCalculator        = NoBlockRewards.Instance;
                cliqueConfig             = new CliqueConfig();
                cliqueConfig.BlockPeriod = _chainSpec.CliquePeriod;
                cliqueConfig.Epoch       = _chainSpec.CliqueEpoch;
                _snapshotManager         = new SnapshotManager(cliqueConfig, _dbProvider.BlocksDb, _blockTree, _ethereumSigner, _logManager);
                _sealValidator           = new CliqueSealValidator(cliqueConfig, _snapshotManager, _logManager);
                _recoveryStep            = new CompositeDataRecoveryStep(_recoveryStep, new AuthorRecoveryStep(_snapshotManager));
                if (_initConfig.IsMining)
                {
                    _sealer = new CliqueSealer(new BasicWallet(_nodeKey), cliqueConfig, _snapshotManager, _nodeKey.Address, _logManager);
                }
                else
                {
                    _sealer = NullSealEngine.Instance;
                }
                break;

            case SealEngineType.NethDev:
                _sealer           = NullSealEngine.Instance;
                _sealValidator    = NullSealEngine.Instance;
                _rewardCalculator = NoBlockRewards.Instance;
                break;

            case SealEngineType.Ethash:
                _rewardCalculator = new RewardCalculator(_specProvider);
                var difficultyCalculator = new DifficultyCalculator(_specProvider);
                if (_initConfig.IsMining)
                {
                    _sealer = new EthashSealer(new Ethash(_logManager), _logManager);
                }
                else
                {
                    _sealer = NullSealEngine.Instance;
                }

                _sealValidator = new EthashSealValidator(_logManager, difficultyCalculator, new Ethash(_logManager));
                break;

            default:
                throw new NotSupportedException($"Seal engine type {_chainSpec.SealEngineType} is not supported in Nethermind");
            }

            /* validation */
            var headerValidator = new HeaderValidator(
                _blockTree,
                _sealValidator,
                _specProvider,
                _logManager);

            var ommersValidator = new OmmersValidator(
                _blockTree,
                headerValidator,
                _logManager);

            var txValidator = new TransactionValidator(
                new SignatureValidator(_specProvider.ChainId));

            _blockValidator = new BlockValidator(
                txValidator,
                headerValidator,
                ommersValidator,
                _specProvider,
                _logManager);

            var stateTree = new StateTree(_dbProvider.StateDb);

            var stateProvider = new StateProvider(
                stateTree,
                _dbProvider.CodeDb,
                _logManager);

            _stateProvider = stateProvider;

            var storageProvider = new StorageProvider(
                _dbProvider.StateDb,
                stateProvider,
                _logManager);

            _transactionPoolInfoProvider = new TransactionPoolInfoProvider(stateProvider);

            /* blockchain processing */
            var blockhashProvider = new BlockhashProvider(
                _blockTree);

            var virtualMachine = new VirtualMachine(
                stateProvider,
                storageProvider,
                blockhashProvider,
                _logManager);

            var transactionProcessor = new TransactionProcessor(
                _specProvider,
                stateProvider,
                storageProvider,
                virtualMachine,
                _logManager);

            _blockProcessor = new BlockProcessor(
                _specProvider,
                _blockValidator,
                _rewardCalculator,
                transactionProcessor,
                _dbProvider.StateDb,
                _dbProvider.CodeDb,
                _dbProvider.TraceDb,
                stateProvider,
                storageProvider,
                _transactionPool,
                _receiptStorage,
                _logManager);

            _blockchainProcessor = new BlockchainProcessor(
                _blockTree,
                _blockProcessor,
                _recoveryStep,
                _logManager,
                _initConfig.StoreReceipts,
                _initConfig.StoreTraces);

            // create shared objects between discovery and peer manager
            IStatsConfig statsConfig = _configProvider.GetConfig <IStatsConfig>();

            _nodeStatsManager = new NodeStatsManager(statsConfig, _logManager, !statsConfig.CaptureNodeStatsEventHistory);

            var encrypter = new AesEncrypter(
                _configProvider.GetConfig <IKeyStoreConfig>(),
                _logManager);

            _keyStore = new FileKeyStore(
                _configProvider.GetConfig <IKeyStoreConfig>(),
                _ethereumJsonSerializer,
                encrypter,
                _cryptoRandom,
                _logManager);

            switch (_initConfig)
            {
            case var _ when HiveEnabled:
                _wallet = new HiveWallet();
                break;

            case var config when config.EnableUnsecuredDevWallet && config.KeepDevWalletInMemory:
                _wallet = new DevWallet(_logManager);
                break;

            case var config when config.EnableUnsecuredDevWallet && !config.KeepDevWalletInMemory:
                _wallet = new DevKeyStoreWallet(_keyStore, _logManager);
                break;

            default:
                _wallet = new NullWallet();
                break;
            }

            if (_initConfig.IsMining)
            {
                IReadOnlyDbProvider minerDbProvider = new ReadOnlyDbProvider(_dbProvider, false);
                AlternativeChain    producerChain   = new AlternativeChain(_blockTree, _blockValidator, _rewardCalculator,
                                                                           _specProvider, minerDbProvider, _recoveryStep, _logManager, _transactionPool, _receiptStorage);

                switch (_chainSpec.SealEngineType)
                {
                case SealEngineType.Clique:
                {
                    // TODO: need to introduce snapshot provider for clique and pass it here instead of CliqueSealEngine
                    if (_logger.IsWarn)
                    {
                        _logger.Warn("Starting Clique block producer & sealer");
                    }
                    _blockProducer = new CliqueBlockProducer(_transactionPool, producerChain.Processor,
                                                             _blockTree, _timestamp, _cryptoRandom, producerChain.StateProvider, _snapshotManager, (CliqueSealer)_sealer, _nodeKey.Address, cliqueConfig, _logManager);
                    break;
                }

                case SealEngineType.NethDev:
                {
                    if (_logger.IsWarn)
                    {
                        _logger.Warn("Starting Dev block producer & sealer");
                    }
                    _blockProducer = new DevBlockProducer(_transactionPool, producerChain.Processor, _blockTree,
                                                          _timestamp, _logManager);
                    break;
                }

                default:
                    throw new NotSupportedException($"Mining in {_chainSpec.SealEngineType} mode is not supported");
                }

                _blockProducer.Start();
            }

            if (!HiveEnabled)
            {
                _blockchainProcessor.Start();
                LoadGenesisBlock(_chainSpec, string.IsNullOrWhiteSpace(_initConfig.GenesisHash) ? null : new Keccak(_initConfig.GenesisHash), _blockTree, stateProvider, _specProvider);
                if (_initConfig.ProcessingEnabled)
                {
#pragma warning disable 4014
                    LoadBlocksFromDb();
#pragma warning restore 4014
                }
                else
                {
                    if (_logger.IsWarn)
                    {
                        _logger.Warn($"Shutting down processor due to {nameof(InitConfig)}.{nameof(InitConfig.ProcessingEnabled)} set to false");
                    }
                    await _blockchainProcessor.StopAsync();
                }
            }

            await InitializeNetwork(
                _receiptStorage,
                headerValidator,
                txValidator);
        }
示例#18
0
        private async Task InitBlockchain(InitParams initParams)
        {
            ChainSpec chainSpec = LoadChainSpec(initParams.ChainSpecPath);

            /* spec */
            // TODO: rebuild to use chainspec
            ISpecProvider specProvider;

            if (chainSpec.ChainId == RopstenSpecProvider.Instance.ChainId)
            {
                specProvider = RopstenSpecProvider.Instance;
            }
            else if (chainSpec.ChainId == MainNetSpecProvider.Instance.ChainId)
            {
                specProvider = MainNetSpecProvider.Instance;
            }
            else
            {
                throw new NotSupportedException($"Not yet tested, not yet supported ChainId {chainSpec.ChainId}");
            }

            var ethereumSigner   = new EthereumSigner(specProvider, _logManager);
            var transactionStore = new TransactionStore();
            var sealEngine       = ConfigureSealEngine(transactionStore, ethereumSigner, initParams);

            /* sync */
            var blocksDb     = new DbOnTheRocks(Path.Combine(_dbBasePath, DbOnTheRocks.BlocksDbPath));
            var blockInfosDb = new DbOnTheRocks(Path.Combine(_dbBasePath, DbOnTheRocks.BlockInfosDbPath));
            var receiptsDb   = new DbOnTheRocks(Path.Combine(_dbBasePath, DbOnTheRocks.ReceiptsDbPath));

            /* blockchain */
            var blockTree            = new BlockTree(blocksDb, blockInfosDb, receiptsDb, specProvider, _logManager);
            var difficultyCalculator = new DifficultyCalculator(specProvider);

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

            /* state */
            var dbProvider      = new RocksDbProvider(_dbBasePath, _logManager);
            var codeDb          = new DbOnTheRocks(Path.Combine(_dbBasePath, DbOnTheRocks.CodeDbPath));
            var stateDb         = new DbOnTheRocks(Path.Combine(_dbBasePath, DbOnTheRocks.StateDbPath));
            var stateTree       = new StateTree(stateDb);
            var stateProvider   = new StateProvider(stateTree, codeDb, _logManager);
            var storageProvider = new StorageProvider(dbProvider, stateProvider, _logManager);

            /* blockchain processing */
            var blockhashProvider    = new BlockhashProvider(blockTree);
            var virtualMachine       = new VirtualMachine(stateProvider, storageProvider, blockhashProvider, _logManager);
            var transactionProcessor = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, _tracer, _logManager);
            var rewardCalculator     = new RewardCalculator(specProvider);
            var blockProcessor       = new BlockProcessor(specProvider, blockValidator, rewardCalculator, transactionProcessor, dbProvider, stateProvider, storageProvider, transactionStore, _logManager);

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

            // create shared objects between discovery and peer manager
            _nodeFactory       = new NodeFactory();
            _nodeStatsProvider = new NodeStatsProvider(_configProvider);
            var jsonSerializer = new JsonSerializer(_logManager);
            var encrypter      = new AesEncrypter(_configProvider, _logManager);

            _keyStore = new FileKeyStore(_configProvider, jsonSerializer, encrypter, _cryptoRandom, _logManager);

            //creating blockchain bridge
            BlockchainBridge = new BlockchainBridge(ethereumSigner, stateProvider, _keyStore, blockTree, stateDb, transactionStore);
            EthereumSigner   = ethereumSigner;

            _blockchainProcessor.Start();
            LoadGenesisBlock(chainSpec, string.IsNullOrWhiteSpace(initParams.GenesisHash) ? null : new Keccak(initParams.GenesisHash), blockTree, stateProvider, specProvider);
            await StartProcessing(blockTree, transactionStore, blockValidator, headerValidator, txValidator, initParams);
        }
示例#19
0
 public JsonRpcModelMapper(IEthereumSigner signer)
 {
     _signer = signer;
 }
 public TxSignaturesRecoveryStep(IEthereumSigner signer, ITransactionPool transactionPool)
 {
     _signer          = signer ?? throw new ArgumentNullException(nameof(signer));
     _transactionPool = transactionPool ?? throw new ArgumentNullException(nameof(signer));
 }
示例#21
0
 public void SetUp()
 {
     Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
     _signer = new EthereumSigner(OlympicSpecProvider.Instance, NullLogManager.Instance);
 }
示例#22
0
        private async Task InitBlockchain()
        {
            /* spec */
            if (_chainSpec.ChainId == RopstenSpecProvider.Instance.ChainId)
            {
                _specProvider = RopstenSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == MainNetSpecProvider.Instance.ChainId)
            {
                _specProvider = MainNetSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == RinkebySpecProvider.Instance.ChainId)
            {
                _specProvider = RinkebySpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == GoerliSpecProvider.Instance.ChainId)
            {
                _specProvider = GoerliSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == SturebySpecProvider.Instance.ChainId)
            {
                _specProvider = SturebySpecProvider.Instance;
            }
            else
            {
                _specProvider = new SingleReleaseSpecProvider(LatestRelease.Instance, _chainSpec.ChainId);
            }

            /* sync */
            IDbConfig dbConfig = _configProvider.GetConfig <IDbConfig>();

            foreach (PropertyInfo propertyInfo in typeof(IDbConfig).GetProperties())
            {
                _logger.Info($"DB {propertyInfo.Name}: {propertyInfo.GetValue(dbConfig)}");
            }

            _dbProvider = HiveEnabled
                ? (IDbProvider) new MemDbProvider()
                : new RocksDbProvider(_initConfig.BaseDbPath, dbConfig, _logManager);

            _ethereumSigner  = new EthereumSigner(_specProvider, _logManager);
            _transactionPool = new TransactionPool(
                new PersistentTransactionStorage(_dbProvider.PendingTxsDb, _specProvider),
                new PendingTransactionThresholdValidator(_initConfig.ObsoletePendingTransactionInterval,
                                                         _initConfig.RemovePendingTransactionInterval), new Timestamp(),
                _ethereumSigner, _logManager, _initConfig.RemovePendingTransactionInterval,
                _initConfig.PeerNotificationThreshold);
            _receiptStorage = new PersistentReceiptStorage(_dbProvider.ReceiptsDb, _specProvider);

//            IDbProvider debugRecorder = new RocksDbProvider(Path.Combine(_dbBasePath, "debug"), dbConfig);
//            _dbProvider = new RpcDbProvider(_jsonSerializer, new BasicJsonRpcClient(KnownRpcUris.NethVm1, _jsonSerializer, _logManager), _logManager, debugRecorder);

//            IDbProvider debugReader = new ReadOnlyDbProvider(new RocksDbProvider(Path.Combine(_dbBasePath, "debug"), dbConfig));
//            _dbProvider = debugReader;

            /* blockchain */
            _blockTree = new BlockTree(
                _dbProvider.BlocksDb,
                _dbProvider.BlockInfosDb,
                _specProvider,
                _transactionPool,
                _logManager);

            var cliqueConfig = new CliqueConfig(15, 30000);
            var clique       = new CliqueSealEngine(cliqueConfig, _ethereumSigner, _nodeKey, _dbProvider.BlocksDb, _blockTree,
                                                    _logManager);

            clique.CanSeal = _initConfig.IsMining;

            // TODO: read seal engine from ChainSpec
            _sealEngine =
                (_specProvider is MainNetSpecProvider) ? ConfigureSealEngine() :
                (_specProvider is RopstenSpecProvider) ? ConfigureSealEngine() :
                (_specProvider is SturebySpecProvider) ? ConfigureSealEngine() :
                (_specProvider is RinkebySpecProvider) ? clique :
                (_specProvider is GoerliSpecProvider) ? (ISealEngine)clique :
                NullSealEngine.Instance;

            _rewardCalculator = (_sealEngine is CliqueSealEngine)
                ? (IRewardCalculator) new NoBlockRewards()
                : new RewardCalculator(_specProvider);

            /* validation */
            var headerValidator = new HeaderValidator(
                _blockTree,
                _sealEngine,
                _specProvider,
                _logManager);

            var ommersValidator = new OmmersValidator(
                _blockTree,
                headerValidator,
                _logManager);

            var txValidator = new TransactionValidator(
                new SignatureValidator(_specProvider.ChainId));

            _blockValidator = new BlockValidator(
                txValidator,
                headerValidator,
                ommersValidator,
                _specProvider,
                _logManager);

            var stateTree = new StateTree(_dbProvider.StateDb);

            var stateProvider = new StateProvider(
                stateTree,
                _dbProvider.CodeDb,
                _logManager);

            _stateProvider = stateProvider;

            var storageProvider = new StorageProvider(
                _dbProvider.StateDb,
                stateProvider,
                _logManager);

            _transactionPoolInfoProvider = new TransactionPoolInfoProvider(stateProvider);

            /* blockchain processing */
            var blockhashProvider = new BlockhashProvider(
                _blockTree);

            var virtualMachine = new VirtualMachine(
                stateProvider,
                storageProvider,
                blockhashProvider,
                _logManager);

            var transactionProcessor = new TransactionProcessor(
                _specProvider,
                stateProvider,
                storageProvider,
                virtualMachine,
                _logManager);

            var txRecoveryStep = new TxSignaturesRecoveryStep(_ethereumSigner, _transactionPool);

            _recoveryStep = _sealEngine is CliqueSealEngine
                ? new CompositeDataRecoveryStep(txRecoveryStep, new AuthorRecoveryStep(clique))
                : (IBlockDataRecoveryStep)txRecoveryStep;

            _blockProcessor = new BlockProcessor(
                _specProvider,
                _blockValidator,
                _rewardCalculator,
                transactionProcessor,
                _dbProvider.StateDb,
                _dbProvider.CodeDb,
                _dbProvider.TraceDb,
                stateProvider,
                storageProvider,
                _transactionPool,
                _receiptStorage,
                _logManager);

            _blockchainProcessor = new BlockchainProcessor(
                _blockTree,
                _blockProcessor,
                _recoveryStep,
                _logManager,
                true,
                true);

            // create shared objects between discovery and peer manager
            _nodeFactory       = new NodeFactory(_logManager);
            _nodeStatsProvider =
                new NodeStatsProvider(_configProvider.GetConfig <IStatsConfig>(), _nodeFactory, _logManager);

            var jsonSerializer = new JsonSerializer(
                _logManager);

            var encrypter = new AesEncrypter(
                _configProvider,
                _logManager);

            _keyStore = new FileKeyStore(
                _configProvider,
                jsonSerializer,
                encrypter,
                _cryptoRandom,
                _logManager);

            if (_initConfig.IsMining)
            {
                IReadOnlyDbProvider minerDbProvider = new ReadOnlyDbProvider(_dbProvider, false);
                AlternativeChain    producerChain   = new AlternativeChain(_blockTree, _blockValidator, _rewardCalculator,
                                                                           _specProvider, minerDbProvider, _recoveryStep, _logManager, _transactionPool, _receiptStorage);

                if (_sealEngine is CliqueSealEngine engine)
                {
                    // TODO: need to introduce snapshot provider for clique and pass it here instead of CliqueSealEngine
                    if (_logger.IsWarn)
                    {
                        _logger.Warn("Starting Clique block producer & sealer");
                    }
                    _blockProducer = new CliqueBlockProducer(_transactionPool, producerChain.Processor, _blockTree,
                                                             producerChain.StateProvider, _timestamp, _cryptoRandom, engine, cliqueConfig, _nodeKey.Address,
                                                             _logManager);
                }
                else
                {
                    if (_logger.IsWarn)
                    {
                        _logger.Warn("Starting Dev block producer & sealer");
                    }
                    _blockProducer = new DevBlockProducer(_transactionPool, producerChain.Processor, _blockTree,
                                                          _timestamp, _logManager);
                }

                _blockProducer.Start();
            }

            if (!HiveEnabled)
            {
                _blockchainProcessor.Start();
                LoadGenesisBlock(_chainSpec, string.IsNullOrWhiteSpace(_initConfig.GenesisHash) ?
                                 null : new Keccak(_initConfig.GenesisHash), _blockTree, stateProvider, _specProvider);
                if (_initConfig.ProcessingEnabled)
                {
#pragma warning disable 4014
                    LoadBlocksFromDb();
#pragma warning restore 4014
                }
                else
                {
                    if (_logger.IsWarn)
                    {
                        _logger.Warn($"Shutting down processor due to {nameof(InitConfig)}.{nameof(InitConfig.ProcessingEnabled)} set to false");
                    }
                    await _blockchainProcessor.StopAsync();
                }
            }

            await InitializeNetwork(
                _receiptStorage,
                headerValidator,
                txValidator);
        }
 public TransactionBuilder Signed(IEthereumSigner signer, PrivateKey privateKey, UInt256 blockNumber)
 {
     signer.Sign(privateKey, TestObjectInternal, blockNumber);
     return(this);
 }
示例#24
0
 public void Setup()
 {
     _specProvider   = RopstenSpecProvider.Instance;
     _ethereumSigner = new EthereumSigner(_specProvider, NullLogManager.Instance);
 }