Search in sources :

Example 26 with Gas

use of org.hyperledger.besu.evm.Gas in project besu by hyperledger.

the class FlatTraceGenerator method computeGas.

private static Gas computeGas(final TraceFrame traceFrame, final Optional<TraceFrame> nextTraceFrame) {
    if (traceFrame.getGasCost().isPresent()) {
        final Gas gasNeeded = traceFrame.getGasCost().get();
        final Gas currentGas = traceFrame.getGasRemaining();
        if (currentGas.compareTo(gasNeeded) >= 0) {
            final Gas gasRemaining = currentGas.minus(gasNeeded);
            return gasRemaining.minus(Gas.of(Math.floorDiv(gasRemaining.toLong(), EIP_150_DIVISOR)));
        }
    }
    return nextTraceFrame.map(TraceFrame::getGasRemaining).orElse(Gas.ZERO);
}
Also used : Gas(org.hyperledger.besu.evm.Gas)

Example 27 with Gas

use of org.hyperledger.besu.evm.Gas in project besu by hyperledger.

the class PrivateTransactionProcessor method refunded.

@SuppressWarnings("unused")
private Gas refunded(final Transaction transaction, final Gas gasRemaining, final Gas gasRefund) {
    // Integer truncation takes care of the the floor calculation needed after the divide.
    final Gas maxRefundAllowance = Gas.of(transaction.getGasLimit()).minus(gasRemaining).dividedBy(gasCalculator.getMaxRefundQuotient());
    final Gas refundAllowance = maxRefundAllowance.min(gasRefund);
    return gasRemaining.plus(refundAllowance);
}
Also used : Gas(org.hyperledger.besu.evm.Gas)

Example 28 with Gas

use of org.hyperledger.besu.evm.Gas in project hedera-services by hashgraph.

the class EvmTxProcessor method execute.

/**
 * Executes the {@link MessageFrame} of the EVM transaction. Returns the result as {@link
 * TransactionProcessingResult}
 *
 * @param sender
 * 		The origin {@link Account} that initiates the transaction
 * @param receiver
 * 		the priority form of the receiving {@link Address} (i.e., EIP-1014 if present); or the newly created address
 * @param gasPrice
 * 		GasPrice to use for gas calculations
 * @param gasLimit
 * 		Externally provided gas limit
 * @param value
 * 		Evm transaction value (HBars)
 * @param payload
 * 		Transaction payload. For Create transactions, the bytecode + constructor arguments
 * @param contractCreation
 * 		Whether or not this is a contract creation transaction
 * @param consensusTime
 * 		Current consensus time
 * @param isStatic
 * 		Whether or not the execution is static
 * @param expiry
 * 		In the case of Create transactions, the expiry of the top-level contract being created
 * @param mirrorReceiver
 * 		the mirror form of the receiving {@link Address}; or the newly created address
 * @return the result of the EVM execution returned as {@link TransactionProcessingResult}
 */
protected TransactionProcessingResult execute(final Account sender, final Address receiver, final long gasPrice, final long gasLimit, final long value, final Bytes payload, final boolean contractCreation, final Instant consensusTime, final boolean isStatic, final OptionalLong expiry, final Address mirrorReceiver) {
    final Wei gasCost = Wei.of(Math.multiplyExact(gasLimit, gasPrice));
    final Wei upfrontCost = gasCost.add(value);
    final Gas intrinsicGas = gasCalculator.transactionIntrinsicGasCost(Bytes.EMPTY, contractCreation);
    final HederaWorldState.Updater updater = (HederaWorldState.Updater) worldState.updater();
    final var senderEvmAddress = sender.getId().asEvmAddress();
    final var senderAccount = updater.getOrCreateSenderAccount(senderEvmAddress);
    final MutableAccount mutableSender = senderAccount.getMutable();
    if (!isStatic) {
        if (intrinsicGas.toLong() > gasLimit) {
            throw new InvalidTransactionException(INSUFFICIENT_GAS);
        }
        final var senderCanAffordGas = mutableSender.getBalance().compareTo(upfrontCost) >= 0;
        validateTrue(senderCanAffordGas, INSUFFICIENT_PAYER_BALANCE);
        mutableSender.decrementBalance(gasCost);
    }
    final Address coinbase = Id.fromGrpcAccount(dynamicProperties.fundingAccount()).asEvmAddress();
    final HederaBlockValues blockValues = new HederaBlockValues(gasLimit, consensusTime.getEpochSecond());
    final Gas gasAvailable = Gas.of(gasLimit).minus(intrinsicGas);
    final Deque<MessageFrame> messageFrameStack = new ArrayDeque<>();
    final var stackedUpdater = updater.updater();
    Wei valueAsWei = Wei.of(value);
    final MessageFrame.Builder commonInitialFrame = MessageFrame.builder().messageFrameStack(messageFrameStack).maxStackSize(MAX_STACK_SIZE).worldUpdater(stackedUpdater).initialGas(gasAvailable).originator(senderEvmAddress).gasPrice(Wei.of(gasPrice)).sender(senderEvmAddress).value(valueAsWei).apparentValue(valueAsWei).blockValues(blockValues).depth(0).completer(unused -> {
    }).isStatic(isStatic).miningBeneficiary(coinbase).blockHashLookup(ALWAYS_UNAVAILABLE_BLOCK_HASH).contextVariables(Map.of("sbh", storageByteHoursTinyBarsGiven(consensusTime), "HederaFunctionality", getFunctionType(), "expiry", expiry));
    final MessageFrame initialFrame = buildInitialFrame(commonInitialFrame, updater, receiver, payload);
    messageFrameStack.addFirst(initialFrame);
    while (!messageFrameStack.isEmpty()) {
        process(messageFrameStack.peekFirst(), new HederaTracer());
    }
    var gasUsedByTransaction = calculateGasUsedByTX(gasLimit, initialFrame);
    final Gas sbhRefund = updater.getSbhRefund();
    final Map<Address, Map<Bytes, Pair<Bytes, Bytes>>> stateChanges;
    if (isStatic) {
        stateChanges = Map.of();
    } else {
        // return gas price to accounts
        final Gas refunded = Gas.of(gasLimit).minus(gasUsedByTransaction).plus(sbhRefund);
        final Wei refundedWei = refunded.priceFor(Wei.of(gasPrice));
        mutableSender.incrementBalance(refundedWei);
        /* Send TX fees to coinbase */
        final var mutableCoinbase = updater.getOrCreate(coinbase).getMutable();
        final Gas coinbaseFee = Gas.of(gasLimit).minus(refunded);
        mutableCoinbase.incrementBalance(coinbaseFee.priceFor(Wei.of(gasPrice)));
        initialFrame.getSelfDestructs().forEach(updater::deleteAccount);
        if (dynamicProperties.shouldEnableTraceability()) {
            stateChanges = updater.getFinalStateChanges();
        } else {
            stateChanges = Map.of();
        }
        /* Commit top level Updater */
        updater.commit();
    }
    /* Externalise Result */
    if (initialFrame.getState() == MessageFrame.State.COMPLETED_SUCCESS) {
        return TransactionProcessingResult.successful(initialFrame.getLogs(), gasUsedByTransaction.toLong(), sbhRefund.toLong(), gasPrice, initialFrame.getOutputData(), mirrorReceiver, stateChanges);
    } else {
        return TransactionProcessingResult.failed(gasUsedByTransaction.toLong(), sbhRefund.toLong(), gasPrice, initialFrame.getRevertReason(), initialFrame.getExceptionalHaltReason(), stateChanges);
    }
}
Also used : Address(org.hyperledger.besu.datatypes.Address) MessageFrame(org.hyperledger.besu.evm.frame.MessageFrame) HederaWorldState(com.hedera.services.store.contracts.HederaWorldState) InvalidTransactionException(com.hedera.services.exceptions.InvalidTransactionException) ArrayDeque(java.util.ArrayDeque) Bytes(org.apache.tuweni.bytes.Bytes) HederaWorldUpdater(com.hedera.services.store.contracts.HederaWorldUpdater) Gas(org.hyperledger.besu.evm.Gas) Wei(org.hyperledger.besu.datatypes.Wei) MutableAccount(org.hyperledger.besu.evm.account.MutableAccount) Map(java.util.Map)

Example 29 with Gas

use of org.hyperledger.besu.evm.Gas in project hedera-services by hashgraph.

the class HederaLogOperation method execute.

@Override
public OperationResult execute(final MessageFrame frame, final EVM evm) {
    final long dataLocation = clampedToLong(frame.popStackItem());
    final long numBytes = clampedToLong(frame.popStackItem());
    final Gas cost = gasCalculator().logOperationGasCost(frame, dataLocation, numBytes, numTopics);
    final Optional<Gas> optionalCost = Optional.of(cost);
    if (frame.isStatic()) {
        return new OperationResult(optionalCost, Optional.of(ExceptionalHaltReason.ILLEGAL_STATE_CHANGE));
    } else if (frame.getRemainingGas().compareTo(cost) < 0) {
        return new OperationResult(optionalCost, Optional.of(ExceptionalHaltReason.INSUFFICIENT_GAS));
    }
    final var addressOrAlias = frame.getRecipientAddress();
    final var updater = (HederaStackedWorldStateUpdater) frame.getWorldUpdater();
    final var aliases = updater.aliases();
    var address = aliases.resolveForEvm(addressOrAlias);
    if (!aliases.isMirror(address)) {
        address = UNRESOLVABLE_ADDRESS_STANDIN;
        log.warn("Could not resolve logger address {}", addressOrAlias);
    }
    final Bytes data = frame.readMemory(dataLocation, numBytes);
    final ImmutableList.Builder<LogTopic> builder = ImmutableList.builderWithExpectedSize(numTopics);
    for (int i = 0; i < numTopics; i++) {
        builder.add(LogTopic.create(leftPad(frame.popStackItem())));
    }
    frame.addLog(new Log(address, data, builder.build()));
    return new OperationResult(optionalCost, Optional.empty());
}
Also used : Bytes(org.apache.tuweni.bytes.Bytes) Log(org.hyperledger.besu.evm.log.Log) ImmutableList(com.google.common.collect.ImmutableList) HederaStackedWorldStateUpdater(com.hedera.services.store.contracts.HederaStackedWorldStateUpdater) Gas(org.hyperledger.besu.evm.Gas) LogTopic(org.hyperledger.besu.evm.log.LogTopic)

Aggregations

Gas (org.hyperledger.besu.evm.Gas)29 Address (org.hyperledger.besu.datatypes.Address)6 Bytes (org.apache.tuweni.bytes.Bytes)5 Wei (org.hyperledger.besu.datatypes.Wei)4 MutableAccount (org.hyperledger.besu.evm.account.MutableAccount)4 UInt256 (org.apache.tuweni.units.bigints.UInt256)3 MessageFrame (org.hyperledger.besu.evm.frame.MessageFrame)3 HederaWorldState (com.hedera.services.store.contracts.HederaWorldState)2 HederaWorldUpdater (com.hedera.services.store.contracts.HederaWorldUpdater)2 ImmutableList (com.google.common.collect.ImmutableList)1 InvalidTransactionException (com.hedera.services.exceptions.InvalidTransactionException)1 HederaStackedWorldStateUpdater (com.hedera.services.store.contracts.HederaStackedWorldStateUpdater)1 ArrayDeque (java.util.ArrayDeque)1 Map (java.util.Map)1 Bytes32 (org.apache.tuweni.bytes.Bytes32)1 BadBlockManager (org.hyperledger.besu.ethereum.chain.BadBlockManager)1 MutableWorldState (org.hyperledger.besu.ethereum.core.MutableWorldState)1 MutableProtocolSchedule (org.hyperledger.besu.ethereum.mainnet.MutableProtocolSchedule)1 ProtocolSpec (org.hyperledger.besu.ethereum.mainnet.ProtocolSpec)1 PrivateTransactionValidator (org.hyperledger.besu.ethereum.privacy.PrivateTransactionValidator)1