Search in sources :

Example 1 with ProcessableBlockHeader

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();
    }
}
Also used : ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) IOException(java.io.IOException) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 2 with ProcessableBlockHeader

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);
    }
}
Also used : SealableBlockHeader(org.hyperledger.besu.ethereum.core.SealableBlockHeader) Address(org.hyperledger.besu.datatypes.Address) MutableWorldState(org.hyperledger.besu.ethereum.core.MutableWorldState) BlockBody(org.hyperledger.besu.ethereum.core.BlockBody) CancellationException(java.util.concurrent.CancellationException) SecurityModuleException(org.hyperledger.besu.plugin.services.securitymodule.SecurityModuleException) CancellationException(java.util.concurrent.CancellationException) ProtocolSpec(org.hyperledger.besu.ethereum.mainnet.ProtocolSpec) SecurityModuleException(org.hyperledger.besu.plugin.services.securitymodule.SecurityModuleException) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) Block(org.hyperledger.besu.ethereum.core.Block) SealableBlockHeader(org.hyperledger.besu.ethereum.core.SealableBlockHeader) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 3 with ProcessableBlockHeader

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();
}
Also used : BaseFeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket) AbstractPendingTransactionsSorter(org.hyperledger.besu.ethereum.eth.transactions.sorter.AbstractPendingTransactionsSorter) EvmAccount(org.hyperledger.besu.evm.account.EvmAccount) WorldUpdater(org.hyperledger.besu.evm.worldstate.WorldUpdater) SealableBlockHeader(org.hyperledger.besu.ethereum.core.SealableBlockHeader) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) Bytes(org.apache.tuweni.bytes.Bytes) Address(org.hyperledger.besu.datatypes.Address) Supplier(java.util.function.Supplier) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) Lists(com.google.common.collect.Lists) BaseFeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket) Wei(org.hyperledger.besu.datatypes.Wei) ScheduleBasedBlockHeaderFunctions(org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions) BigInteger(java.math.BigInteger) MergeConfigOptions(org.hyperledger.besu.config.MergeConfigOptions) Block(org.hyperledger.besu.ethereum.core.Block) BodyValidation(org.hyperledger.besu.ethereum.mainnet.BodyValidation) Bytes32(org.apache.tuweni.bytes.Bytes32) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) Difficulty(org.hyperledger.besu.ethereum.core.Difficulty) AbstractBlockProcessor(org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor) Logger(org.slf4j.Logger) CancellationException(java.util.concurrent.CancellationException) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) SecurityModuleException(org.hyperledger.besu.plugin.services.securitymodule.SecurityModuleException) BlockHeaderBuilder(org.hyperledger.besu.ethereum.core.BlockHeaderBuilder) MutableWorldState(org.hyperledger.besu.ethereum.core.MutableWorldState) DifficultyCalculator(org.hyperledger.besu.ethereum.mainnet.DifficultyCalculator) MainnetTransactionProcessor(org.hyperledger.besu.ethereum.mainnet.MainnetTransactionProcessor) List(java.util.List) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) BlockBody(org.hyperledger.besu.ethereum.core.BlockBody) Optional(java.util.Optional) BlockHeaderFunctions(org.hyperledger.besu.ethereum.core.BlockHeaderFunctions) ProtocolSpec(org.hyperledger.besu.ethereum.mainnet.ProtocolSpec) Transaction(org.hyperledger.besu.ethereum.core.Transaction) Collections(java.util.Collections) Hash(org.hyperledger.besu.datatypes.Hash) DifficultyCalculator(org.hyperledger.besu.ethereum.mainnet.DifficultyCalculator) BigInteger(java.math.BigInteger) Wei(org.hyperledger.besu.datatypes.Wei) Bytes32(org.apache.tuweni.bytes.Bytes32)

Example 4 with ProcessableBlockHeader

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;
}
Also used : EvmAccount(org.hyperledger.besu.evm.account.EvmAccount) WorldUpdater(org.hyperledger.besu.evm.worldstate.WorldUpdater) Wei(org.hyperledger.besu.datatypes.Wei) SealableBlockHeader(org.hyperledger.besu.ethereum.core.SealableBlockHeader) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Example 5 with ProcessableBlockHeader

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);
}
Also used : TransactionTestFixture(org.hyperledger.besu.ethereum.core.TransactionTestFixture) Transaction(org.hyperledger.besu.ethereum.core.Transaction) Address(org.hyperledger.besu.datatypes.Address) WorldUpdater(org.hyperledger.besu.evm.worldstate.WorldUpdater) ProcessableBlockHeader(org.hyperledger.besu.ethereum.core.ProcessableBlockHeader) Test(org.junit.Test)

Aggregations

ProcessableBlockHeader (org.hyperledger.besu.ethereum.core.ProcessableBlockHeader)21 Address (org.hyperledger.besu.datatypes.Address)14 Transaction (org.hyperledger.besu.ethereum.core.Transaction)12 Test (org.junit.Test)12 WorldUpdater (org.hyperledger.besu.evm.worldstate.WorldUpdater)9 ArrayList (java.util.ArrayList)7 BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)7 Wei (org.hyperledger.besu.datatypes.Wei)6 MutableWorldState (org.hyperledger.besu.ethereum.core.MutableWorldState)5 Bytes (org.apache.tuweni.bytes.Bytes)4 TransactionTestFixture (org.hyperledger.besu.ethereum.core.TransactionTestFixture)4 EvmAccount (org.hyperledger.besu.evm.account.EvmAccount)4 MutableAccount (org.hyperledger.besu.evm.account.MutableAccount)4 Optional (java.util.Optional)3 Bytes32 (org.apache.tuweni.bytes.Bytes32)3 Hash (org.hyperledger.besu.datatypes.Hash)3 SealableBlockHeader (org.hyperledger.besu.ethereum.core.SealableBlockHeader)3 BaseFeePendingTransactionsSorter (org.hyperledger.besu.ethereum.eth.transactions.sorter.BaseFeePendingTransactionsSorter)3 TransactionProcessingResult (org.hyperledger.besu.ethereum.processing.TransactionProcessingResult)3 Logger (org.slf4j.Logger)3