Search in sources :

Example 66 with Wei

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

the class TransactionPoolTest method shouldIgnoreFeeCapIfSetZero.

@Test
public void shouldIgnoreFeeCapIfSetZero() {
    final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create();
    final EthContext ethContext = ethProtocolManager.ethContext();
    final Wei twoEthers = Wei.fromEth(2);
    final TransactionPool transactionPool = new TransactionPool(transactions, protocolSchedule, protocolContext, transactionBroadcaster, ethContext, new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), metricsSystem, ImmutableTransactionPoolConfiguration.builder().txFeeCap(Wei.ZERO).build());
    when(transactionValidator.validate(any(Transaction.class), any(Optional.class), any())).thenReturn(valid());
    when(transactionValidator.validateForSender(any(Transaction.class), nullable(Account.class), any(TransactionValidationParams.class))).thenReturn(valid());
    assertThat(transactionPool.addLocalTransaction(new TransactionTestFixture().nonce(1).gasPrice(twoEthers.add(Wei.of(1))).createTransaction(KEY_PAIR1)).isValid()).isTrue();
}
Also used : EthProtocolManager(org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager) EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) MiningParameters(org.hyperledger.besu.ethereum.core.MiningParameters) Account(org.hyperledger.besu.evm.account.Account) TransactionTestFixture(org.hyperledger.besu.ethereum.core.TransactionTestFixture) Transaction(org.hyperledger.besu.ethereum.core.Transaction) Optional(java.util.Optional) Wei(org.hyperledger.besu.datatypes.Wei) TransactionValidationParams(org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams) Test(org.junit.Test)

Example 67 with Wei

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

the class TransactionPoolTest method shouldRejectLocalTransactionIfFeeCapExceeded.

@Test
public void shouldRejectLocalTransactionIfFeeCapExceeded() {
    final EthProtocolManager ethProtocolManager = EthProtocolManagerTestUtil.create();
    final EthContext ethContext = ethProtocolManager.ethContext();
    final Wei twoEthers = Wei.fromEth(2);
    TransactionPool transactionPool = new TransactionPool(transactions, protocolSchedule, protocolContext, transactionBroadcaster, ethContext, new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), metricsSystem, ImmutableTransactionPoolConfiguration.builder().txFeeCap(twoEthers).build());
    final TransactionTestFixture builder = new TransactionTestFixture();
    final Transaction transactionLocal = builder.nonce(1).gasPrice(twoEthers.add(Wei.of(1))).createTransaction(KEY_PAIR1);
    when(transactionValidator.validate(any(Transaction.class), any(Optional.class), any())).thenReturn(valid());
    when(transactionValidator.validateForSender(any(Transaction.class), nullable(Account.class), any(TransactionValidationParams.class))).thenReturn(valid());
    final ValidationResult<TransactionInvalidReason> result = transactionPool.addLocalTransaction(transactionLocal);
    assertThat(result.getInvalidReason()).isEqualTo(TransactionInvalidReason.TX_FEECAP_EXCEEDED);
}
Also used : EthContext(org.hyperledger.besu.ethereum.eth.manager.EthContext) Account(org.hyperledger.besu.evm.account.Account) TransactionTestFixture(org.hyperledger.besu.ethereum.core.TransactionTestFixture) Optional(java.util.Optional) EthProtocolManager(org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager) MiningParameters(org.hyperledger.besu.ethereum.core.MiningParameters) Transaction(org.hyperledger.besu.ethereum.core.Transaction) TransactionInvalidReason(org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason) Wei(org.hyperledger.besu.datatypes.Wei) TransactionValidationParams(org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams) Test(org.junit.Test)

Example 68 with Wei

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

the class TransactionReplacementByFeeMarketRule method shouldReplace.

@Override
public boolean shouldReplace(final TransactionInfo existingTransactionInfo, final TransactionInfo newTransactionInfo, final Optional<Wei> baseFee) {
    // bail early if basefee is absent or neither transaction supports 1559 fee market
    if (baseFee.isEmpty() || !(isNotGasPriced(existingTransactionInfo) || isNotGasPriced(newTransactionInfo))) {
        return false;
    }
    Wei newEffPrice = priceOf(newTransactionInfo.getTransaction(), baseFee);
    Wei newEffPriority = newTransactionInfo.getTransaction().getEffectivePriorityFeePerGas(baseFee);
    // bail early if price is not strictly positive
    if (newEffPrice.equals(Wei.ZERO)) {
        return false;
    }
    Wei curEffPrice = priceOf(existingTransactionInfo.getTransaction(), baseFee);
    Wei curEffPriority = existingTransactionInfo.getTransaction().getEffectivePriorityFeePerGas(baseFee);
    if (isBumpedBy(curEffPrice, newEffPrice, priceBump)) {
        // replace if new effective priority is >= current effective priority
        return newEffPriority.compareTo(curEffPriority) >= 0;
    } else if (curEffPrice.equals(newEffPrice)) {
        // replace if the new effective priority is bumped by priceBump relative to current priority
        return isBumpedBy(curEffPriority, newEffPriority, priceBump);
    }
    return false;
}
Also used : Wei(org.hyperledger.besu.datatypes.Wei)

Example 69 with Wei

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

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