Search in sources :

Example 16 with Wei

use of org.hyperledger.besu.datatypes.Wei in project besu by hyperledger.

the class BlockchainQueriesTest method getAccountBalanceAtBlockNumber.

@Test
public void getAccountBalanceAtBlockNumber() {
    final List<Address> addresses = Arrays.asList(gen.address(), gen.address(), gen.address());
    final int blockCount = 3;
    final BlockchainWithData data = setupBlockchain(blockCount, addresses);
    final BlockchainQueries queries = data.blockchainQueries;
    for (int i = 0; i < blockCount; i++) {
        final long curBlockNumber = i;
        final BlockHeader header = data.blockData.get(i).block.getHeader();
        final Hash stateRoot = header.getStateRoot();
        final WorldState worldState = data.worldStateArchive.get(stateRoot, header.getHash()).get();
        assertThat(addresses).isNotEmpty();
        addresses.forEach(address -> {
            final Account actualAccount = worldState.get(address);
            final Optional<Wei> result = queries.accountBalance(address, curBlockNumber);
            assertThat(result).contains(actualAccount.getBalance());
        });
    }
}
Also used : Account(org.hyperledger.besu.evm.account.Account) Address(org.hyperledger.besu.datatypes.Address) WorldState(org.hyperledger.besu.evm.worldstate.WorldState) Wei(org.hyperledger.besu.datatypes.Wei) BlockHeader(org.hyperledger.besu.ethereum.core.BlockHeader) Hash(org.hyperledger.besu.datatypes.Hash) Test(org.junit.Test)

Example 17 with Wei

use of org.hyperledger.besu.datatypes.Wei in project besu by hyperledger.

the class BlockchainQueriesTest method getAccountBalanceNonExistentAtBlockNumber.

@Test
public void getAccountBalanceNonExistentAtBlockNumber() {
    final List<Address> addresses = Arrays.asList(gen.address(), gen.address(), gen.address());
    final BlockchainWithData data = setupBlockchain(3, addresses);
    final BlockchainQueries queries = data.blockchainQueries;
    assertThat(addresses).isNotEmpty();
    // Get random non-existent account
    final Wei result = queries.accountBalance(gen.address(), 1L).get();
    assertThat(result).isEqualTo(Wei.ZERO);
}
Also used : Address(org.hyperledger.besu.datatypes.Address) Wei(org.hyperledger.besu.datatypes.Wei) Test(org.junit.Test)

Example 18 with Wei

use of org.hyperledger.besu.datatypes.Wei 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 19 with Wei

use of org.hyperledger.besu.datatypes.Wei 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 20 with Wei

use of org.hyperledger.besu.datatypes.Wei in project besu by hyperledger.

the class BlockTransactionSelector method evaluateTransaction.

/*
   * Passed into the PendingTransactions, and is called on each transaction until sufficient
   * transactions are found which fill a block worth of gas.
   *
   * This function will continue to be called until the block under construction is suitably
   * full (in terms of gasLimit) and the provided transaction's gasLimit does not fit within
   * the space remaining in the block.
   *
   */
private TransactionSelectionResult evaluateTransaction(final Transaction transaction) {
    if (isCancelled.get()) {
        throw new CancellationException("Cancelled during transaction selection.");
    }
    if (transactionTooLargeForBlock(transaction)) {
        LOG.trace("{} too large to select for block creation", transaction);
        if (blockOccupancyAboveThreshold()) {
            return TransactionSelectionResult.COMPLETE_OPERATION;
        } else {
            return TransactionSelectionResult.CONTINUE;
        }
    }
    // If the gas price specified by the transaction is less than this node is willing to accept,
    // do not include it in the block.
    final Wei actualMinTransactionGasPriceInBlock = feeMarket.getTransactionPriceCalculator().price(transaction, processableBlockHeader.getBaseFee());
    if (minTransactionGasPrice.compareTo(actualMinTransactionGasPriceInBlock) > 0) {
        LOG.warn("Gas fee of {} lower than configured minimum {}, deleting", transaction, minTransactionGasPrice);
        return TransactionSelectionResult.DELETE_TRANSACTION_AND_CONTINUE;
    }
    final WorldUpdater worldStateUpdater = worldState.updater();
    final BlockHashLookup blockHashLookup = new BlockHashLookup(processableBlockHeader, blockchain);
    final boolean isGoQuorumPrivateTransaction = transaction.isGoQuorumPrivateTransaction(transactionProcessor.getTransactionValidator().getGoQuorumCompatibilityMode());
    TransactionProcessingResult effectiveResult;
    if (isGoQuorumPrivateTransaction) {
        final ValidationResult<TransactionInvalidReason> validationResult = validateTransaction(processableBlockHeader, transaction, worldStateUpdater);
        if (!validationResult.isValid()) {
            LOG.warn("Invalid transaction: {}. Block {} Transaction {}", validationResult.getErrorMessage(), processableBlockHeader.getParentHash().toHexString(), transaction.getHash().toHexString());
            return transactionSelectionResultForInvalidResult(validationResult);
        } else {
            // valid GoQuorum private tx, we need to hand craft the receipt and increment the nonce
            effectiveResult = publicResultForWhenWeHaveAPrivateTransaction(transaction);
            worldStateUpdater.getOrCreate(transaction.getSender()).getMutable().incrementNonce();
        }
    } else {
        effectiveResult = transactionProcessor.processTransaction(blockchain, worldStateUpdater, processableBlockHeader, transaction, miningBeneficiary, blockHashLookup, false, TransactionValidationParams.mining());
    }
    if (!effectiveResult.isInvalid()) {
        worldStateUpdater.commit();
        LOG.trace("Selected {} for block creation", transaction);
        updateTransactionResultTracking(transaction, effectiveResult);
    } else {
        return transactionSelectionResultForInvalidResult(effectiveResult.getValidationResult());
    }
    return TransactionSelectionResult.CONTINUE;
}
Also used : BlockHashLookup(org.hyperledger.besu.ethereum.vm.BlockHashLookup) CancellationException(java.util.concurrent.CancellationException) TransactionInvalidReason(org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason) WorldUpdater(org.hyperledger.besu.evm.worldstate.WorldUpdater) Wei(org.hyperledger.besu.datatypes.Wei) TransactionProcessingResult(org.hyperledger.besu.ethereum.processing.TransactionProcessingResult)

Aggregations

Wei (org.hyperledger.besu.datatypes.Wei)69 Address (org.hyperledger.besu.datatypes.Address)24 Test (org.junit.Test)20 Transaction (org.hyperledger.besu.ethereum.core.Transaction)18 Bytes (org.apache.tuweni.bytes.Bytes)16 Hash (org.hyperledger.besu.datatypes.Hash)14 BlockHeader (org.hyperledger.besu.ethereum.core.BlockHeader)13 MutableAccount (org.hyperledger.besu.evm.account.MutableAccount)12 Account (org.hyperledger.besu.evm.account.Account)9 WorldUpdater (org.hyperledger.besu.evm.worldstate.WorldUpdater)9 Optional (java.util.Optional)8 TransactionInvalidReason (org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason)7 ArrayList (java.util.ArrayList)6 JsonRpcSuccessResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse)6 ProtocolSchedule (org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule)6 JsonObject (io.vertx.core.json.JsonObject)5 Response (okhttp3.Response)5 Bytes32 (org.apache.tuweni.bytes.Bytes32)5 MessageFrame (org.hyperledger.besu.evm.frame.MessageFrame)5 List (java.util.List)4