private async Task ProducerLoop() { while (!_cancellationTokenSource.IsCancellationRequested) { BlockHeader parentHeader = _blockTree.Head; if (parentHeader == null) { if (_logger.IsWarn) { _logger.Warn($"Preparing new block - parent header is null"); } } else if (_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash)) { ProduceNewBlock(parentHeader); } var timeToNextStep = _auRaStepCalculator.TimeToNextStep; if (_logger.IsDebug) { _logger.Debug($"Waiting {timeToNextStep} for next AuRa step."); } await TaskExt.DelayAtLeast(timeToNextStep); } }
public void SetUp() { _stepDelay = TimeSpan.FromMilliseconds(20); _pendingTxSelector = Substitute.For <IPendingTxSelector>(); _blockchainProcessor = Substitute.For <IBlockchainProcessor>(); _sealer = Substitute.For <ISealer>(); _blockTree = Substitute.For <IBlockTree>(); _blockProcessingQueue = Substitute.For <IBlockProcessingQueue>(); _stateProvider = Substitute.For <IStateProvider>(); _timestamper = Substitute.For <ITimestamper>(); _auRaStepCalculator = Substitute.For <IAuRaStepCalculator>(); _auraConfig = Substitute.For <IAuraConfig>(); _nodeAddress = TestItem.AddressA; _auRaBlockProducer = new AuRaBlockProducer( _pendingTxSelector, _blockchainProcessor, _stateProvider, _sealer, _blockTree, _blockProcessingQueue, _timestamper, LimboLogs.Instance, _auRaStepCalculator, _auraConfig, _nodeAddress); _auraConfig.ForceSealing.Returns(true); _pendingTxSelector.SelectTransactions(Arg.Any <long>()).Returns(Array.Empty <Transaction>()); _sealer.CanSeal(Arg.Any <long>(), Arg.Any <Keccak>()).Returns(true); _sealer.SealBlock(Arg.Any <Block>(), Arg.Any <CancellationToken>()).Returns(c => Task.FromResult(c.Arg <Block>())); _blockProcessingQueue.IsEmpty.Returns(true); _auRaStepCalculator.TimeToNextStep.Returns(_stepDelay); _blockTree.BestKnownNumber.Returns(1); _blockTree.Head.Returns(Build.A.BlockHeader.WithAura(10, Bytes.Empty).TestObject); _blockchainProcessor.Process(Arg.Any <Block>(), ProcessingOptions.ProducingBlock, Arg.Any <IBlockTracer>()).Returns(c => c.Arg <Block>()); }
protected Task <bool> TryProduceNewBlock(CancellationToken token) { lock (_newBlockLock) { BlockHeader parentHeader = GetCurrentBlockParent(); if (parentHeader == null) { if (Logger.IsWarn) { Logger.Warn("Preparing new block - parent header is null"); } } else { if (_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash)) { Interlocked.Exchange(ref Metrics.CanProduceBlocks, 1); return(ProduceNewBlock(parentHeader, token)); } else { Interlocked.Exchange(ref Metrics.CanProduceBlocks, 0); } } Metrics.FailedBlockSeals++; return(Task.FromResult(false)); } }
protected async Task TryProduceNewBlock(CancellationToken token) { BlockHeader parentHeader = BlockTree.Head; if (parentHeader == null) { if (Logger.IsWarn) { Logger.Warn($"Preparing new block - parent header is null"); } } else if (_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash)) { await ProduceNewBlock(parentHeader, token); } }
protected Task <bool> TryProduceNewBlock(CancellationToken token) { lock (_newBlockLock) { BlockHeader parentHeader = BlockTree.Head?.Header; if (parentHeader == null) { if (Logger.IsWarn) { Logger.Warn($"Preparing new block - parent header is null"); } } else if (_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash)) { return(ProduceNewBlock(parentHeader, token)); } return(Task.FromResult(false)); } }
private Block PrepareBlock(Block parentBlock) { BlockHeader parentHeader = parentBlock.Header; if (parentHeader == null) { if (_logger.IsError) { _logger.Error($"Preparing new block on top of {parentBlock.ToString(Block.Format.Short)} - parent header is null"); } return(null); } if (_recentNotAllowedParent == parentBlock.Hash) { return(null); } if (!_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash)) { if (_logger.IsInfo) { _logger.Info($"Not allowed to sign block ({parentBlock.Number + 1})"); } _recentNotAllowedParent = parentHeader.Hash; return(null); } if (_logger.IsInfo) { _logger.Info($"Preparing new block on top of {parentBlock.ToString(Block.Format.Short)}"); } UInt256 timestamp = _timestamp.EpochSeconds; BlockHeader header = new BlockHeader( parentBlock.Hash, Keccak.OfAnEmptySequenceRlp, Address.Zero, 1, parentBlock.Number + 1, parentBlock.GasLimit, timestamp > parentBlock.Timestamp ? timestamp : parentBlock.Timestamp + 1, new byte[0]); // If the block isn't a checkpoint, cast a random vote (good enough for now) UInt256 number = header.Number; // Assemble the voting snapshot to check which votes make sense Snapshot snapshot = _snapshotManager.GetOrCreateSnapshot(number - 1, header.ParentHash); bool isEpochBlock = (ulong)number % 30000 == 0; if (!isEpochBlock) { // Gather all the proposals that make sense voting on List <Address> addresses = new List <Address>(); foreach (var proposal in _proposals) { Address address = proposal.Key; bool authorize = proposal.Value; if (_snapshotManager.IsValidVote(snapshot, address, authorize)) { addresses.Add(address); } } // If there's pending proposals, cast a vote on them if (addresses.Count > 0) { header.Beneficiary = addresses[_cryptoRandom.NextInt(addresses.Count)]; header.Nonce = _proposals[header.Beneficiary] ? Clique.NonceAuthVote : Clique.NonceDropVote; } } // Set the correct difficulty header.Difficulty = CalculateDifficulty(snapshot, _address); header.TotalDifficulty = parentBlock.TotalDifficulty + header.Difficulty; if (_logger.IsDebug) { _logger.Debug($"Setting total difficulty to {parentBlock.TotalDifficulty} + {header.Difficulty}."); } // Set extra data int mainBytesLength = Clique.ExtraVanityLength + Clique.ExtraSealLength; int signerBytesLength = isEpochBlock ? 20 * snapshot.Signers.Count : 0; int extraDataLength = mainBytesLength + signerBytesLength; header.ExtraData = new byte[extraDataLength]; byte[] clientName = Encoding.UTF8.GetBytes("Nethermind"); Array.Copy(clientName, header.ExtraData, clientName.Length); if (isEpochBlock) { for (int i = 0; i < snapshot.Signers.Keys.Count; i++) { Address signer = snapshot.Signers.Keys[i]; int index = Clique.ExtraVanityLength + 20 * i; Array.Copy(signer.Bytes, 0, header.ExtraData, index, signer.Bytes.Length); } } // Mix digest is reserved for now, set to empty header.MixHash = Keccak.Zero; // Ensure the timestamp has the correct delay header.Timestamp = parentBlock.Timestamp + _config.BlockPeriod; if (header.Timestamp < _timestamp.EpochSeconds) { header.Timestamp = new UInt256(_timestamp.EpochSeconds); } var transactions = _transactionPool.GetPendingTransactions().OrderBy(t => t.Nonce).ThenByDescending(t => t.GasPrice).ThenBy(t => t.GasLimit); // by nonce in case there are two transactions for the same account var selectedTxs = new List <Transaction>(); BigInteger gasRemaining = header.GasLimit; if (_logger.IsDebug) { _logger.Debug($"Collecting pending transactions at min gas price {MinGasPriceForMining} and block gas limit {gasRemaining}."); } int total = 0; _stateProvider.StateRoot = parentHeader.StateRoot; Dictionary <Address, UInt256> nonces = new Dictionary <Address, UInt256>(); foreach (Transaction transaction in transactions) { total++; if (transaction.SenderAddress == null) { if (_logger.IsError) { _logger.Error("Rejecting null sender pending transaction."); } continue; } if (transaction.GasPrice < MinGasPriceForMining) { if (_logger.IsTrace) { _logger.Trace($"Rejecting transaction - gas price ({transaction.GasPrice}) too low (min gas price: {MinGasPriceForMining}."); } continue; } if (transaction.Nonce != _stateProvider.GetNonce(transaction.SenderAddress) && (!nonces.ContainsKey(transaction.SenderAddress) || nonces[transaction.SenderAddress] + 1 != transaction.Nonce)) { if (_logger.IsTrace) { _logger.Trace($"Rejecting transaction based on nonce."); } continue; } if (transaction.GasLimit > gasRemaining) { if (_logger.IsTrace) { _logger.Trace($"Rejecting transaction - gas limit ({transaction.GasPrice}) more than remaining gas ({gasRemaining})."); } continue; } UInt256 requiredBalance = transaction.GasLimit + transaction.Value; UInt256 balance = _stateProvider.GetBalance(transaction.SenderAddress); if (transaction.GasLimit + transaction.Value > balance) { if (_logger.IsTrace) { _logger.Trace($"Rejecting transaction - insufficient balance - required {requiredBalance}, actual {balance}."); } continue; } selectedTxs.Add(transaction); nonces[transaction.SenderAddress] = transaction.Nonce; gasRemaining -= transaction.GasLimit; } if (_logger.IsDebug) { _logger.Debug($"Collected {selectedTxs.Count} out of {total} pending transactions."); } Block block = new Block(header, selectedTxs, new BlockHeader[0]); header.TransactionsRoot = block.CalculateTransactionsRoot(); block.Author = _address; return(block); }
private Block?PrepareBlock(Block parentBlock) { BlockHeader parentHeader = parentBlock.Header; if (parentHeader == null) { if (_logger.IsError) { _logger.Error( $"Preparing new block on top of {parentBlock.ToString(Block.Format.Short)} - parent header is null"); } return(null); } if (_recentNotAllowedParent == parentBlock.Hash) { return(null); } if (!_sealer.CanSeal(parentHeader.Number + 1, parentHeader.Hash)) { if (_logger.IsTrace) { _logger.Trace($"Not allowed to sign block ({parentBlock.Number + 1})"); } _recentNotAllowedParent = parentHeader.Hash; return(null); } if (_logger.IsInfo) { _logger.Info($"Preparing new block on top of {parentBlock.ToString(Block.Format.Short)}"); } UInt256 timestamp = _timestamper.UnixTime.Seconds; BlockHeader header = new BlockHeader( parentBlock.Hash, Keccak.OfAnEmptySequenceRlp, Address.Zero, 1, parentBlock.Number + 1, _gasLimitCalculator.GetGasLimit(parentBlock.Header), timestamp > parentBlock.Timestamp ? timestamp : parentBlock.Timestamp + 1, Array.Empty <byte>()); // If the block isn't a checkpoint, cast a random vote (good enough for now) long number = header.Number; // Assemble the voting snapshot to check which votes make sense Snapshot snapshot = _snapshotManager.GetOrCreateSnapshot(number - 1, header.ParentHash); bool isEpochBlock = (ulong)number % 30000 == 0; if (!isEpochBlock && _proposals.Any()) { // Gather all the proposals that make sense voting on List <Address> addresses = new List <Address>(); foreach (var proposal in _proposals) { Address address = proposal.Key; bool authorize = proposal.Value; if (_snapshotManager.IsValidVote(snapshot, address, authorize)) { addresses.Add(address); } } // If there's pending proposals, cast a vote on them if (addresses.Count > 0) { header.Beneficiary = addresses[_cryptoRandom.NextInt(addresses.Count)]; if (_proposals.TryGetValue(header.Beneficiary !, out bool proposal)) { header.Nonce = proposal ? Clique.NonceAuthVote : Clique.NonceDropVote; } } } // Set the correct difficulty header.BaseFee = BlockHeader.CalculateBaseFee(parentHeader, _specProvider.GetSpec(header.Number)); header.Difficulty = CalculateDifficulty(snapshot, _sealer.Address); header.TotalDifficulty = parentBlock.TotalDifficulty + header.Difficulty; if (_logger.IsDebug) { _logger.Debug($"Setting total difficulty to {parentBlock.TotalDifficulty} + {header.Difficulty}."); } // Set extra data int mainBytesLength = Clique.ExtraVanityLength + Clique.ExtraSealLength; int signerBytesLength = isEpochBlock ? 20 * snapshot.Signers.Count : 0; int extraDataLength = mainBytesLength + signerBytesLength; header.ExtraData = new byte[extraDataLength]; byte[] clientName = Encoding.UTF8.GetBytes("Nethermind " + ClientVersion.Version); Array.Copy(clientName, header.ExtraData, clientName.Length); if (isEpochBlock) { for (int i = 0; i < snapshot.Signers.Keys.Count; i++) { Address signer = snapshot.Signers.Keys[i]; int index = Clique.ExtraVanityLength + 20 * i; Array.Copy(signer.Bytes, 0, header.ExtraData, index, signer.Bytes.Length); } } // Mix digest is reserved for now, set to empty header.MixHash = Keccak.Zero; // Ensure the timestamp has the correct delay header.Timestamp = parentBlock.Timestamp + _config.BlockPeriod; if (header.Timestamp < _timestamper.UnixTime.Seconds) { header.Timestamp = new UInt256(_timestamper.UnixTime.Seconds); } _stateProvider.StateRoot = parentHeader.StateRoot; var selectedTxs = _txSource.GetTransactions(parentBlock.Header, header.GasLimit); Block block = new Block(header, selectedTxs, Array.Empty <BlockHeader>()); header.TxRoot = new TxTrie(block.Transactions).RootHash; block.Header.Author = _sealer.Address; return(block); }
public bool CanSeal(long blockNumber, Keccak parentHash) => _sealer.CanSeal(blockNumber, parentHash);