Search in sources :

Example 1 with FeeMarket

use of org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket in project besu by hyperledger.

the class EthFeeHistory method response.

@Override
public JsonRpcResponse response(final JsonRpcRequestContext request) {
    final Object requestId = request.getRequest().getId();
    final long blockCount = Optional.of(request.getRequiredParameter(0, UnsignedLongParameter.class)).map(UnsignedLongParameter::getValue).orElse(0L);
    if (blockCount < 1 || blockCount > 1024) {
        return new JsonRpcErrorResponse(requestId, JsonRpcError.INVALID_PARAMS);
    }
    final BlockParameter highestBlock = request.getRequiredParameter(1, BlockParameter.class);
    final Optional<List<Double>> maybeRewardPercentiles = request.getOptionalParameter(2, Double[].class).map(Arrays::asList);
    final long chainHeadBlockNumber = blockchain.getChainHeadBlockNumber();
    final long resolvedHighestBlockNumber = highestBlock.getNumber().orElse(chainHeadBlockNumber);
    if (resolvedHighestBlockNumber > chainHeadBlockNumber) {
        return new JsonRpcErrorResponse(requestId, JsonRpcError.INVALID_PARAMS);
    }
    final long oldestBlock = Math.max(0, resolvedHighestBlockNumber - (blockCount - 1));
    final List<BlockHeader> blockHeaders = LongStream.range(oldestBlock, oldestBlock + blockCount).mapToObj(blockchain::getBlockHeader).flatMap(Optional::stream).collect(toUnmodifiableList());
    // we return the base fees for the blocks requested and 1 more because we can always compute it
    final List<Wei> explicitlyRequestedBaseFees = blockHeaders.stream().map(blockHeader -> blockHeader.getBaseFee().orElse(Wei.ZERO)).collect(toUnmodifiableList());
    final long nextBlockNumber = resolvedHighestBlockNumber + 1;
    final Wei nextBaseFee = blockchain.getBlockHeader(nextBlockNumber).map(blockHeader -> blockHeader.getBaseFee().orElse(Wei.ZERO)).orElseGet(() -> Optional.of(protocolSchedule.getByBlockNumber(nextBlockNumber).getFeeMarket()).filter(FeeMarket::implementsBaseFee).map(BaseFeeMarket.class::cast).map(feeMarket -> {
        final BlockHeader lastBlockHeader = blockHeaders.get(blockHeaders.size() - 1);
        return feeMarket.computeBaseFee(nextBlockNumber, explicitlyRequestedBaseFees.get(explicitlyRequestedBaseFees.size() - 1), lastBlockHeader.getGasUsed(), feeMarket.targetGasUsed(lastBlockHeader));
    }).orElse(Wei.ZERO));
    final List<Double> gasUsedRatios = blockHeaders.stream().map(blockHeader -> blockHeader.getGasUsed() / (double) blockHeader.getGasLimit()).collect(toUnmodifiableList());
    final Optional<List<List<Wei>>> maybeRewards = maybeRewardPercentiles.map(rewardPercentiles -> LongStream.range(oldestBlock, oldestBlock + blockCount).mapToObj(blockchain::getBlockByNumber).flatMap(Optional::stream).map(block -> computeRewards(rewardPercentiles.stream().sorted().collect(toUnmodifiableList()), block)).collect(toUnmodifiableList()));
    return new JsonRpcSuccessResponse(requestId, FeeHistory.FeeHistoryResult.from(ImmutableFeeHistory.builder().oldestBlock(oldestBlock).baseFeePerGas(Stream.concat(explicitlyRequestedBaseFees.stream(), Stream.of(nextBaseFee)).collect(toUnmodifiableList())).gasUsedRatio(gasUsedRatios).reward(maybeRewards).build()));
}
Also used : Arrays(java.util.Arrays) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) ImmutableFeeHistory(org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.ImmutableFeeHistory) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) Collectors.toUnmodifiableList(java.util.stream.Collectors.toUnmodifiableList) FeeHistory(org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.FeeHistory) ArrayList(java.util.ArrayList) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) UnsignedLongParameter(org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedLongParameter) TransactionReceipt(org.hyperledger.besu.ethereum.core.TransactionReceipt) Map(java.util.Map) BlockParameter(org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter) BaseFeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket) Wei(org.hyperledger.besu.datatypes.Wei) JsonRpcRequestContext(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext) Block(org.hyperledger.besu.ethereum.core.Block) LongStream(java.util.stream.LongStream) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) Streams(com.google.common.collect.Streams) AbstractMap(java.util.AbstractMap) List(java.util.List) RpcMethod(org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod) Stream(java.util.stream.Stream) Optional(java.util.Optional) Comparator(java.util.Comparator) Transaction(org.hyperledger.besu.ethereum.core.Transaction) UnsignedLongParameter(org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedLongParameter) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) BaseFeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket) BlockParameter(org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter) Collectors.toUnmodifiableList(java.util.stream.Collectors.toUnmodifiableList) ArrayList(java.util.ArrayList) List(java.util.List) Wei(org.hyperledger.besu.datatypes.Wei) Arrays(java.util.Arrays) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Example 2 with FeeMarket

use of org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket 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 3 with FeeMarket

use of org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket in project besu by hyperledger.

the class BftBlockCreatorTest method createdBlockPassesValidationRulesAndHasAppropriateHashAndMixHash.

@Test
public void createdBlockPassesValidationRulesAndHasAppropriateHashAndMixHash() {
    // Construct a parent block.
    final BlockHeaderTestFixture blockHeaderBuilder = new BlockHeaderTestFixture();
    // required to pass validation rule checks.
    blockHeaderBuilder.gasLimit(5000);
    final BlockHeader parentHeader = blockHeaderBuilder.buildHeader();
    final Optional<BlockHeader> optionalHeader = Optional.of(parentHeader);
    // Construct a block chain and world state
    final MutableBlockchain blockchain = mock(MutableBlockchain.class);
    when(blockchain.getChainHeadHash()).thenReturn(parentHeader.getHash());
    when(blockchain.getBlockHeader(any())).thenReturn(optionalHeader);
    final BlockHeader blockHeader = mock(BlockHeader.class);
    when(blockHeader.getBaseFee()).thenReturn(Optional.empty());
    when(blockchain.getChainHeadHeader()).thenReturn(blockHeader);
    final List<Address> initialValidatorList = Lists.newArrayList();
    for (int i = 0; i < 4; i++) {
        initialValidatorList.add(AddressHelpers.ofValue(i));
    }
    final IbftExtraDataCodec bftExtraDataEncoder = new IbftExtraDataCodec();
    final BaseBftProtocolSchedule bftProtocolSchedule = new BaseBftProtocolSchedule() {

        @Override
        public BlockHeaderValidator.Builder createBlockHeaderRuleset(final BftConfigOptions config, final FeeMarket feeMarket) {
            return IbftBlockHeaderValidationRulesetFactory.blockHeaderValidator(5, Optional.empty());
        }
    };
    final GenesisConfigOptions configOptions = GenesisConfigFile.fromConfig("{\"config\": {\"spuriousDragonBlock\":0}}").getConfigOptions();
    final ForksSchedule<BftConfigOptions> forksSchedule = new ForksSchedule<>(List.of(new ForkSpec<>(0, configOptions.getBftConfigOptions())));
    final ProtocolSchedule protocolSchedule = bftProtocolSchedule.createProtocolSchedule(configOptions, forksSchedule, PrivacyParameters.DEFAULT, false, bftExtraDataEncoder, EvmConfiguration.DEFAULT);
    final ProtocolContext protContext = new ProtocolContext(blockchain, createInMemoryWorldStateArchive(), setupContextWithBftExtraDataEncoder(initialValidatorList, bftExtraDataEncoder));
    final GasPricePendingTransactionsSorter pendingTransactions = new GasPricePendingTransactionsSorter(TransactionPoolConfiguration.DEFAULT_TX_RETENTION_HOURS, 1, TestClock.fixed(), metricsSystem, blockchain::getChainHeadHeader, TransactionPoolConfiguration.DEFAULT_PRICE_BUMP);
    final BftBlockCreator blockCreator = new BftBlockCreator(forksSchedule, initialValidatorList.get(0), () -> Optional.of(10_000_000L), parent -> bftExtraDataEncoder.encode(new BftExtraData(Bytes.wrap(new byte[32]), Collections.emptyList(), Optional.empty(), 0, initialValidatorList)), pendingTransactions, protContext, protocolSchedule, Wei.ZERO, 0.8, parentHeader, bftExtraDataEncoder);
    final int secondsBetweenBlocks = 1;
    final Block block = blockCreator.createBlock(parentHeader.getTimestamp() + 1);
    final BlockHeaderValidator rules = IbftBlockHeaderValidationRulesetFactory.blockHeaderValidator(secondsBetweenBlocks, Optional.empty()).build();
    // NOTE: The header will not contain commit seals, so can only do light validation on header.
    final boolean validationResult = rules.validateHeader(block.getHeader(), parentHeader, protContext, HeaderValidationMode.LIGHT);
    assertThat(validationResult).isTrue();
    final BlockHeader header = block.getHeader();
    final BftExtraData extraData = bftExtraDataEncoder.decode(header);
    assertThat(block.getHash()).isEqualTo(new BftBlockHashing(bftExtraDataEncoder).calculateDataHashForCommittedSeal(header, extraData));
}
Also used : Address(org.hyperledger.besu.datatypes.Address) ForkSpec(org.hyperledger.besu.consensus.common.ForkSpec) BftConfigOptions(org.hyperledger.besu.config.BftConfigOptions) BftBlockCreator(org.hyperledger.besu.consensus.common.bft.blockcreation.BftBlockCreator) IbftExtraDataCodec(org.hyperledger.besu.consensus.ibft.IbftExtraDataCodec) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) BaseBftProtocolSchedule(org.hyperledger.besu.consensus.common.bft.BaseBftProtocolSchedule) BlockHeaderValidator(org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator) ForksSchedule(org.hyperledger.besu.consensus.common.ForksSchedule) GenesisConfigOptions(org.hyperledger.besu.config.GenesisConfigOptions) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) BaseBftProtocolSchedule(org.hyperledger.besu.consensus.common.bft.BaseBftProtocolSchedule) BftExtraData(org.hyperledger.besu.consensus.common.bft.BftExtraData) BlockHeaderTestFixture(org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture) BftBlockHashing(org.hyperledger.besu.consensus.common.bft.BftBlockHashing) Block(org.hyperledger.besu.ethereum.core.Block) MutableBlockchain(org.hyperledger.besu.ethereum.chain.MutableBlockchain) GasPricePendingTransactionsSorter(org.hyperledger.besu.ethereum.eth.transactions.sorter.GasPricePendingTransactionsSorter) Test(org.junit.Test)

Example 4 with FeeMarket

use of org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket in project besu by hyperledger.

the class MainnetProtocolSpecs method londonDefinition.

static ProtocolSpecBuilder londonDefinition(final Optional<BigInteger> chainId, final OptionalInt configContractSizeLimit, final OptionalInt configStackSizeLimit, final boolean enableRevertReason, final GenesisConfigOptions genesisConfigOptions, final boolean quorumCompatibilityMode, final EvmConfiguration evmConfiguration) {
    final int contractSizeLimit = configContractSizeLimit.orElse(SPURIOUS_DRAGON_CONTRACT_SIZE_LIMIT);
    final int stackSizeLimit = configStackSizeLimit.orElse(MessageFrame.DEFAULT_MAX_STACK_SIZE);
    final long londonForkBlockNumber = genesisConfigOptions.getLondonBlockNumber().orElse(Long.MAX_VALUE);
    final BaseFeeMarket londonFeeMarket = FeeMarket.london(londonForkBlockNumber, genesisConfigOptions.getBaseFeePerGas());
    return berlinDefinition(chainId, configContractSizeLimit, configStackSizeLimit, enableRevertReason, quorumCompatibilityMode, evmConfiguration).gasCalculator(LondonGasCalculator::new).gasLimitCalculator(new LondonTargetingGasLimitCalculator(londonForkBlockNumber, londonFeeMarket)).transactionValidatorBuilder(gasCalculator -> new MainnetTransactionValidator(gasCalculator, londonFeeMarket, true, chainId, Set.of(TransactionType.FRONTIER, TransactionType.ACCESS_LIST, TransactionType.EIP1559), quorumCompatibilityMode)).transactionProcessorBuilder((gasCalculator, transactionValidator, contractCreationProcessor, messageCallProcessor) -> new MainnetTransactionProcessor(gasCalculator, transactionValidator, contractCreationProcessor, messageCallProcessor, true, stackSizeLimit, londonFeeMarket, CoinbaseFeePriceCalculator.eip1559())).contractCreationProcessorBuilder((gasCalculator, evm) -> new ContractCreationProcessor(gasCalculator, evm, true, List.of(MaxCodeSizeRule.of(contractSizeLimit), PrefixCodeRule.of()), 1, SPURIOUS_DRAGON_FORCE_DELETE_WHEN_EMPTY_ADDRESSES)).evmBuilder((gasCalculator, jdCacheConfig) -> MainnetEVMs.london(gasCalculator, chainId.orElse(BigInteger.ZERO), evmConfiguration)).feeMarket(londonFeeMarket).difficultyCalculator(MainnetDifficultyCalculators.LONDON).blockHeaderValidatorBuilder(feeMarket -> MainnetBlockHeaderValidator.createBaseFeeMarketValidator(londonFeeMarket)).ommerHeaderValidatorBuilder(feeMarket -> MainnetBlockHeaderValidator.createBaseFeeMarketOmmerValidator(londonFeeMarket)).blockBodyValidatorBuilder(BaseFeeBlockBodyValidator::new).name(LONDON_FORK_NAME);
}
Also used : BaseFeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket) WorldUpdater(org.hyperledger.besu.evm.worldstate.WorldUpdater) GoQuorumBlockProcessor(org.hyperledger.besu.ethereum.goquorum.GoQuorumBlockProcessor) PowAlgorithm(org.hyperledger.besu.config.PowAlgorithm) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) GenesisConfigOptions(org.hyperledger.besu.config.GenesisConfigOptions) ByzantiumGasCalculator(org.hyperledger.besu.evm.gascalculator.ByzantiumGasCalculator) BlockValidatorBuilder(org.hyperledger.besu.ethereum.mainnet.ProtocolSpecBuilder.BlockValidatorBuilder) BlockProcessorBuilder(org.hyperledger.besu.ethereum.mainnet.ProtocolSpecBuilder.BlockProcessorBuilder) TransactionReceipt(org.hyperledger.besu.ethereum.core.TransactionReceipt) MainnetEVMs(org.hyperledger.besu.evm.MainnetEVMs) TangerineWhistleGasCalculator(org.hyperledger.besu.evm.gascalculator.TangerineWhistleGasCalculator) BigInteger(java.math.BigInteger) HomesteadGasCalculator(org.hyperledger.besu.evm.gascalculator.HomesteadGasCalculator) ImmutableSet(com.google.common.collect.ImmutableSet) Blockchain(org.hyperledger.besu.ethereum.chain.Blockchain) CoinbaseFeePriceCalculator(org.hyperledger.besu.ethereum.core.feemarket.CoinbaseFeePriceCalculator) Set(java.util.Set) EvmConfiguration(org.hyperledger.besu.evm.internal.EvmConfiguration) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) TransactionProcessingResult(org.hyperledger.besu.ethereum.processing.TransactionProcessingResult) List(java.util.List) IstanbulGasCalculator(org.hyperledger.besu.evm.gascalculator.IstanbulGasCalculator) MutableAccount(org.hyperledger.besu.evm.account.MutableAccount) Optional(java.util.Optional) ContractCreationProcessor(org.hyperledger.besu.evm.processor.ContractCreationProcessor) TransactionType(org.hyperledger.besu.plugin.data.TransactionType) PrefixCodeRule(org.hyperledger.besu.evm.contractvalidation.PrefixCodeRule) IntStream(java.util.stream.IntStream) MessageCallProcessor(org.hyperledger.besu.evm.processor.MessageCallProcessor) PrivateTransactionValidator(org.hyperledger.besu.ethereum.privacy.PrivateTransactionValidator) Address(org.hyperledger.besu.datatypes.Address) OptionalInt(java.util.OptionalInt) MaxCodeSizeRule(org.hyperledger.besu.evm.contractvalidation.MaxCodeSizeRule) FrontierGasCalculator(org.hyperledger.besu.evm.gascalculator.FrontierGasCalculator) BaseFeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket) Wei(org.hyperledger.besu.datatypes.Wei) LondonGasCalculator(org.hyperledger.besu.evm.gascalculator.LondonGasCalculator) PetersburgGasCalculator(org.hyperledger.besu.evm.gascalculator.PetersburgGasCalculator) PrivateMetadataUpdater(org.hyperledger.besu.ethereum.privacy.storage.PrivateMetadataUpdater) WorldState(org.hyperledger.besu.evm.worldstate.WorldState) GoQuorumBlockValidator(org.hyperledger.besu.ethereum.goquorum.GoQuorumBlockValidator) Resources(com.google.common.io.Resources) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) MutableWorldState(org.hyperledger.besu.ethereum.core.MutableWorldState) IOException(java.io.IOException) PrivateTransactionProcessor(org.hyperledger.besu.ethereum.privacy.PrivateTransactionProcessor) JsonArray(io.vertx.core.json.JsonArray) MainnetBlockValidator(org.hyperledger.besu.ethereum.MainnetBlockValidator) SpuriousDragonGasCalculator(org.hyperledger.besu.evm.gascalculator.SpuriousDragonGasCalculator) BerlinGasCalculator(org.hyperledger.besu.evm.gascalculator.BerlinGasCalculator) ConstantinopleGasCalculator(org.hyperledger.besu.evm.gascalculator.ConstantinopleGasCalculator) MessageFrame(org.hyperledger.besu.evm.frame.MessageFrame) Transaction(org.hyperledger.besu.ethereum.core.Transaction) Collections(java.util.Collections) ContractCreationProcessor(org.hyperledger.besu.evm.processor.ContractCreationProcessor)

Example 5 with FeeMarket

use of org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket in project besu by hyperledger.

the class TransactionPool method validateTransaction.

private ValidationResult<TransactionInvalidReason> validateTransaction(final Transaction transaction, final boolean isLocal) {
    final BlockHeader chainHeadBlockHeader = getChainHeadBlockHeader();
    final FeeMarket feeMarket = protocolSchedule.getByBlockNumber(chainHeadBlockHeader.getNumber()).getFeeMarket();
    // Check whether it's a GoQuorum transaction
    boolean goQuorumCompatibilityMode = getTransactionValidator().getGoQuorumCompatibilityMode();
    if (transaction.isGoQuorumPrivateTransaction(goQuorumCompatibilityMode)) {
        final Optional<Wei> weiValue = ofNullable(transaction.getValue());
        if (weiValue.isPresent() && !weiValue.get().isZero()) {
            return ValidationResult.invalid(TransactionInvalidReason.ETHER_VALUE_NOT_SUPPORTED);
        }
    }
    // executable:
    if ((!effectiveGasPriceIsAboveConfiguredMinGasPrice(transaction) && !miningParameters.isMiningEnabled()) || (!feeMarket.satisfiesFloorTxCost(transaction))) {
        return ValidationResult.invalid(TransactionInvalidReason.GAS_PRICE_TOO_LOW);
    }
    final ValidationResult<TransactionInvalidReason> basicValidationResult = getTransactionValidator().validate(transaction, chainHeadBlockHeader.getBaseFee(), TransactionValidationParams.transactionPool());
    if (!basicValidationResult.isValid()) {
        return basicValidationResult;
    }
    if (isLocal && strictReplayProtectionShouldBeEnforceLocally(chainHeadBlockHeader) && transaction.getChainId().isEmpty()) {
        // Strict replay protection is enabled but the tx is not replay-protected
        return ValidationResult.invalid(TransactionInvalidReason.REPLAY_PROTECTED_SIGNATURE_REQUIRED);
    }
    if (transaction.getGasLimit() > chainHeadBlockHeader.getGasLimit()) {
        return ValidationResult.invalid(TransactionInvalidReason.EXCEEDS_BLOCK_GAS_LIMIT, String.format("Transaction gas limit of %s exceeds block gas limit of %s", transaction.getGasLimit(), chainHeadBlockHeader.getGasLimit()));
    }
    if (transaction.getType().equals(TransactionType.EIP1559) && !feeMarket.implementsBaseFee()) {
        return ValidationResult.invalid(TransactionInvalidReason.INVALID_TRANSACTION_FORMAT, "EIP-1559 transaction are not allowed yet");
    }
    return protocolContext.getWorldStateArchive().getMutable(chainHeadBlockHeader.getStateRoot(), chainHeadBlockHeader.getHash(), false).map(worldState -> {
        final Account senderAccount = worldState.get(transaction.getSender());
        return getTransactionValidator().validateForSender(transaction, senderAccount, TransactionValidationParams.transactionPool());
    }).orElseGet(() -> ValidationResult.invalid(CHAIN_HEAD_WORLD_STATE_NOT_AVAILABLE));
}
Also used : ADDED(org.hyperledger.besu.ethereum.eth.transactions.sorter.AbstractPendingTransactionsSorter.TransactionAddedStatus.ADDED) ValidationResult(org.hyperledger.besu.ethereum.mainnet.ValidationResult) AbstractPendingTransactionsSorter(org.hyperledger.besu.ethereum.eth.transactions.sorter.AbstractPendingTransactionsSorter) Account(org.hyperledger.besu.evm.account.Account) EthPeer(org.hyperledger.besu.ethereum.eth.manager.EthPeer) LoggerFactory(org.slf4j.LoggerFactory) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) Collections.singletonList(java.util.Collections.singletonList) MainnetTransactionValidator(org.hyperledger.besu.ethereum.mainnet.MainnetTransactionValidator) ProtocolSchedule(org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule) HashSet(java.util.HashSet) TransactionAddedStatus(org.hyperledger.besu.ethereum.eth.transactions.sorter.AbstractPendingTransactionsSorter.TransactionAddedStatus) CHAIN_HEAD_WORLD_STATE_NOT_AVAILABLE(org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason.CHAIN_HEAD_WORLD_STATE_NOT_AVAILABLE) Wei(org.hyperledger.besu.datatypes.Wei) TransactionInvalidReason(org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason) BlockAddedEvent(org.hyperledger.besu.ethereum.chain.BlockAddedEvent) BlockAddedObserver(org.hyperledger.besu.ethereum.chain.BlockAddedObserver) Logger(org.slf4j.Logger) Optional.ofNullable(java.util.Optional.ofNullable) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) BesuMetricCategory(org.hyperledger.besu.metrics.BesuMetricCategory) Collection(java.util.Collection) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) Set(java.util.Set) TransactionValidationParams(org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams) MiningParameters(org.hyperledger.besu.ethereum.core.MiningParameters) LabelledMetric(org.hyperledger.besu.plugin.services.metrics.LabelledMetric) ProtocolContext(org.hyperledger.besu.ethereum.ProtocolContext) Optional(java.util.Optional) MetricsSystem(org.hyperledger.besu.plugin.services.MetricsSystem) MutableBlockchain(org.hyperledger.besu.ethereum.chain.MutableBlockchain) TransactionType(org.hyperledger.besu.plugin.data.TransactionType) Transaction(org.hyperledger.besu.ethereum.core.Transaction) Hash(org.hyperledger.besu.datatypes.Hash) Counter(org.hyperledger.besu.plugin.services.metrics.Counter) FeeMarket(org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket) Account(org.hyperledger.besu.evm.account.Account) TransactionInvalidReason(org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason) Wei(org.hyperledger.besu.datatypes.Wei) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader)

Aggregations

BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)6 FeeMarket (org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket)6 Optional (java.util.Optional)5 Wei (org.hyperledger.besu.datatypes.Wei)5 Transaction (org.hyperledger.besu.ethereum.core.Transaction)5 List (java.util.List)4 Address (org.hyperledger.besu.datatypes.Address)4 ProtocolSchedule (org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule)4 BaseFeeMarket (org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket)4 BigInteger (java.math.BigInteger)3 Collections (java.util.Collections)3 Set (java.util.Set)3 GenesisConfigOptions (org.hyperledger.besu.config.GenesisConfigOptions)3 ProtocolContext (org.hyperledger.besu.ethereum.ProtocolContext)3 Blockchain (org.hyperledger.besu.ethereum.chain.Blockchain)3 Block (org.hyperledger.besu.ethereum.core.Block)3 MutableWorldState (org.hyperledger.besu.ethereum.core.MutableWorldState)3 TransactionReceipt (org.hyperledger.besu.ethereum.core.TransactionReceipt)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Resources (com.google.common.io.Resources)2