use of org.hyperledger.besu.ethereum.core.ProcessableBlockHeader in project besu by hyperledger.
the class TransactionLogBloomCacher method cacheLogsBloomForBlockHeader.
void cacheLogsBloomForBlockHeader(final BlockHeader blockHeader, final Optional<BlockHeader> commonAncestorBlockHeader, final Optional<File> reusedCacheFile) {
try {
if (cachingStatus.cachingCount.incrementAndGet() != 1) {
return;
}
final long blockNumber = blockHeader.getNumber();
LOG.debug("Caching logs bloom for block {}.", "0x" + Long.toHexString(blockNumber));
final File cacheFile = reusedCacheFile.orElse(calculateCacheFileName(blockNumber, cacheDir));
if (cacheFile.exists()) {
try {
final Optional<Long> ancestorBlockNumber = commonAncestorBlockHeader.map(ProcessableBlockHeader::getNumber);
if (ancestorBlockNumber.isPresent()) {
// reload the cache in case of reorg
for (long number = ancestorBlockNumber.get() + 1; number < blockHeader.getNumber(); number++) {
final Optional<BlockHeader> ancestorBlockHeader = blockchain.getBlockHeader(number);
if (ancestorBlockHeader.isPresent()) {
cacheSingleBlock(ancestorBlockHeader.get(), cacheFile, true);
}
}
}
cacheSingleBlock(blockHeader, cacheFile, true);
} catch (final InvalidCacheException e) {
populateLatestSegment(blockNumber);
}
} else {
populateLatestSegment(blockNumber);
}
} catch (final IOException e) {
if (e.getMessage().contains(NO_SPACE_LEFT_ON_DEVICE)) {
LOG.error(e.getMessage());
System.exit(0);
}
LOG.error("Unhandled caching exception.", e);
} finally {
cachingStatus.cachingCount.decrementAndGet();
}
}
use of org.hyperledger.besu.ethereum.core.ProcessableBlockHeader in project besu by hyperledger.
the class AbstractBlockCreator method createBlock.
protected Block createBlock(final Optional<List<Transaction>> maybeTransactions, final Optional<List<BlockHeader>> maybeOmmers, final Optional<Bytes32> maybePrevRandao, final long timestamp, boolean rewardCoinbase) {
try {
final ProcessableBlockHeader processableBlockHeader = createPendingBlockHeader(timestamp, maybePrevRandao);
final Address miningBeneficiary = miningBeneficiaryCalculator.getMiningBeneficiary(processableBlockHeader.getNumber());
throwIfStopped();
final MutableWorldState disposableWorldState = duplicateWorldStateAtParent();
throwIfStopped();
final List<BlockHeader> ommers = maybeOmmers.orElse(selectOmmers());
throwIfStopped();
final BlockTransactionSelector.TransactionSelectionResults transactionResults = selectTransactions(processableBlockHeader, disposableWorldState, maybeTransactions, miningBeneficiary);
throwIfStopped();
final ProtocolSpec newProtocolSpec = protocolSchedule.getByBlockNumber(processableBlockHeader.getNumber());
if (rewardCoinbase && !rewardBeneficiary(disposableWorldState, processableBlockHeader, ommers, miningBeneficiary, newProtocolSpec.getBlockReward(), newProtocolSpec.isSkipZeroBlockRewards())) {
LOG.trace("Failed to apply mining reward, exiting.");
throw new RuntimeException("Failed to apply mining reward.");
}
throwIfStopped();
final SealableBlockHeader sealableBlockHeader = BlockHeaderBuilder.create().populateFrom(processableBlockHeader).ommersHash(BodyValidation.ommersHash(MergeConfigOptions.isMergeEnabled() ? Collections.emptyList() : ommers)).stateRoot(disposableWorldState.rootHash()).transactionsRoot(BodyValidation.transactionsRoot(transactionResults.getTransactions())).receiptsRoot(BodyValidation.receiptsRoot(transactionResults.getReceipts())).logsBloom(BodyValidation.logsBloom(transactionResults.getReceipts())).gasUsed(transactionResults.getCumulativeGasUsed()).extraData(extraDataCalculator.get(parentHeader)).buildSealableBlockHeader();
final BlockHeader blockHeader = createFinalBlockHeader(sealableBlockHeader);
return new Block(blockHeader, new BlockBody(transactionResults.getTransactions(), ommers));
} catch (final SecurityModuleException ex) {
throw new IllegalStateException("Failed to create block signature", ex);
} catch (final CancellationException ex) {
throw ex;
} catch (final Exception ex) {
// TODO(tmm): How are we going to know this has exploded, and thus restart it?
throw new IllegalStateException("Block creation failed unexpectedly. Will restart on next block added to chain.", ex);
}
}
use of org.hyperledger.besu.ethereum.core.ProcessableBlockHeader in project besu by hyperledger.
the class AbstractBlockCreator method createPendingBlockHeader.
private ProcessableBlockHeader createPendingBlockHeader(final long timestamp, final Optional<Bytes32> maybePrevRandao) {
final long newBlockNumber = parentHeader.getNumber() + 1;
long gasLimit = protocolSpec.getGasLimitCalculator().nextGasLimit(parentHeader.getGasLimit(), targetGasLimitSupplier.get().orElse(parentHeader.getGasLimit()), newBlockNumber);
final DifficultyCalculator difficultyCalculator = protocolSpec.getDifficultyCalculator();
final BigInteger difficulty = difficultyCalculator.nextDifficulty(timestamp, parentHeader, protocolContext);
final Wei baseFee = Optional.of(protocolSpec.getFeeMarket()).filter(FeeMarket::implementsBaseFee).map(BaseFeeMarket.class::cast).map(feeMarket -> feeMarket.computeBaseFee(newBlockNumber, parentHeader.getBaseFee().orElse(Wei.ZERO), parentHeader.getGasUsed(), feeMarket.targetGasUsed(parentHeader))).orElse(null);
final Bytes32 prevRandao = maybePrevRandao.orElse(null);
return BlockHeaderBuilder.create().parentHash(parentHeader.getHash()).coinbase(coinbase).difficulty(Difficulty.of(difficulty)).number(newBlockNumber).gasLimit(gasLimit).timestamp(timestamp).baseFee(baseFee).prevRandao(prevRandao).buildProcessableBlockHeader();
}
use of org.hyperledger.besu.ethereum.core.ProcessableBlockHeader in project besu by hyperledger.
the class AbstractBlockCreator method rewardBeneficiary.
/* Copied from BlockProcessor (with modifications). */
boolean rewardBeneficiary(final MutableWorldState worldState, final ProcessableBlockHeader header, final List<BlockHeader> ommers, final Address miningBeneficiary, final Wei blockReward, final boolean skipZeroBlockRewards) {
// TODO(tmm): Added to make this work, should come from blockProcessor.
final int MAX_GENERATION = 6;
if (skipZeroBlockRewards && blockReward.isZero()) {
return true;
}
final Wei coinbaseReward = protocolSpec.getBlockProcessor().getCoinbaseReward(blockReward, header.getNumber(), ommers.size());
final WorldUpdater updater = worldState.updater();
final EvmAccount beneficiary = updater.getOrCreate(miningBeneficiary);
beneficiary.getMutable().incrementBalance(coinbaseReward);
for (final BlockHeader ommerHeader : ommers) {
if (ommerHeader.getNumber() - header.getNumber() > MAX_GENERATION) {
LOG.trace("Block processing error: ommer block number {} more than {} generations current block number {}", ommerHeader.getNumber(), MAX_GENERATION, header.getNumber());
return false;
}
final EvmAccount ommerCoinbase = updater.getOrCreate(ommerHeader.getCoinbase());
final Wei ommerReward = protocolSpec.getBlockProcessor().getOmmerReward(blockReward, header.getNumber(), ommerHeader.getNumber());
ommerCoinbase.getMutable().incrementBalance(ommerReward);
}
updater.commit();
return true;
}
use of org.hyperledger.besu.ethereum.core.ProcessableBlockHeader in project besu by hyperledger.
the class BlockTransactionSelectorTest method transactionWithIncorrectNonceRemainsInPoolAndNotSelected.
@Test
public void transactionWithIncorrectNonceRemainsInPoolAndNotSelected() {
final ProcessableBlockHeader blockHeader = createBlockWithGasLimit(5000);
final TransactionTestFixture txTestFixture = new TransactionTestFixture();
final Transaction futureTransaction = txTestFixture.nonce(5).gasLimit(1).createTransaction(keyPair);
pendingTransactions.addRemoteTransaction(futureTransaction);
when(transactionProcessor.processTransaction(eq(blockchain), any(WorldUpdater.class), eq(blockHeader), eq(futureTransaction), any(), any(), anyBoolean(), any())).thenReturn(TransactionProcessingResult.invalid(ValidationResult.invalid(TransactionInvalidReason.INCORRECT_NONCE)));
final Address miningBeneficiary = AddressHelpers.ofValue(1);
final BlockTransactionSelector selector = new BlockTransactionSelector(transactionProcessor, blockchain, worldState, pendingTransactions, blockHeader, this::createReceipt, Wei.ZERO, 0.8, this::isCancelled, miningBeneficiary, FeeMarket.legacy());
final BlockTransactionSelector.TransactionSelectionResults results = selector.buildTransactionListForBlock();
Assertions.assertThat(pendingTransactions.getTransactionByHash(futureTransaction.getHash())).isPresent();
assertThat(results.getTransactions().size()).isEqualTo(0);
}
Aggregations