Skip to content

Commit

Permalink
Extra data based pricing (#10)
Browse files Browse the repository at this point in the history
Signed-off-by: Fabio Di Fabio <fabio.difabio@consensys.net>
  • Loading branch information
fab-10 authored May 30, 2024
1 parent c216a58 commit 3d56714
Show file tree
Hide file tree
Showing 24 changed files with 575 additions and 188 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public class LineaPluginTestBase extends AcceptanceTestBase {
public void setup() throws Exception {
minerNode =
besu.createCliqueNodeWithExtraCliOptionsAndRpcApis(
"miner1", LINEA_CLIQUE_OPTIONS, getTestCliOptions(), Set.of("LINEA"));
"miner1", LINEA_CLIQUE_OPTIONS, getTestCliOptions(), Set.of("LINEA", "MINER"));
minerNode.setTransactionPoolConfiguration(
ImmutableTransactionPoolConfiguration.builder()
.from(TransactionPoolConfiguration.DEFAULT)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,12 @@
import org.web3j.tx.TransactionManager;

public class ProfitableTransactionTest extends LineaPluginTestBase {
private static final int VERIFICATION_GAS_COST = 1_200_000;
private static final int VERIFICATION_CAPACITY = 90_000;
private static final int GAS_PRICE_RATIO = 15;
private static final double MIN_MARGIN = 1.0;
private static final double MIN_MARGIN = 1.5;
private static final Wei MIN_GAS_PRICE = Wei.of(1_000_000_000);

@Override
public List<String> getTestCliOptions() {
return new TestCommandLineOptionsBuilder()
.set("--plugin-linea-verification-gas-cost=", String.valueOf(VERIFICATION_GAS_COST))
.set("--plugin-linea-verification-capacity=", String.valueOf(VERIFICATION_CAPACITY))
.set("--plugin-linea-gas-price-ratio=", String.valueOf(GAS_PRICE_RATIO))
.set("--plugin-linea-min-margin=", String.valueOf(MIN_MARGIN))
.build();
}
Expand Down Expand Up @@ -70,7 +64,7 @@ public void transactionIsNotMinedWhenUnprofitable() throws Exception {

final var txUnprofitable =
txManager.sendTransaction(
MIN_GAS_PRICE.getAsBigInteger(),
MIN_GAS_PRICE.getAsBigInteger().divide(BigInteger.valueOf(100)),
BigInteger.valueOf(MAX_TX_GAS_LIMIT / 2),
credentials.getAddress(),
txData.toString(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/*
* Copyright Consensys Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package linea.plugin.acc.test.extradata;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

import linea.plugin.acc.test.LineaPluginTestBase;
import linea.plugin.acc.test.TestCommandLineOptionsBuilder;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt32;
import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.tests.acceptance.dsl.account.Account;
import org.hyperledger.besu.tests.acceptance.dsl.account.Accounts;
import org.hyperledger.besu.tests.acceptance.dsl.transaction.NodeRequests;
import org.hyperledger.besu.tests.acceptance.dsl.transaction.Transaction;
import org.hyperledger.besu.tests.acceptance.dsl.transaction.account.TransferTransaction;
import org.junit.jupiter.api.Test;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.utils.Numeric;

public class ExtraDataPricingTest extends LineaPluginTestBase {
private static final Wei MIN_GAS_PRICE = Wei.of(1_000_000_000);
private static final int WEI_IN_KWEI = 1000;

@Override
public List<String> getTestCliOptions() {
return getTestCommandLineOptionsBuilder().build();
}

protected TestCommandLineOptionsBuilder getTestCommandLineOptionsBuilder() {
return new TestCommandLineOptionsBuilder()
.set("--plugin-linea-extra-data-pricing-enabled=", Boolean.TRUE.toString());
}

@Test
public void updateMinGasPriceViaExtraData() {
minerNode.getMiningParameters().setMinTransactionGasPrice(MIN_GAS_PRICE);
final var doubleMinGasPrice = MIN_GAS_PRICE.multiply(2);

final var extraData =
createExtraDataPricingField(
0, MIN_GAS_PRICE.toLong() / WEI_IN_KWEI, doubleMinGasPrice.toLong() / WEI_IN_KWEI);
final var reqSetExtraData = new ExtraDataPricingTest.MinerSetExtraDataRequest(extraData);
final var respSetExtraData = reqSetExtraData.execute(minerNode.nodeRequests());

assertThat(respSetExtraData).isTrue();

final Account sender = accounts.getSecondaryBenefactor();
final Account recipient = accounts.createAccount("recipient");

final TransferTransaction transferTx = accountTransactions.createTransfer(sender, recipient, 1);
final var txHash = minerNode.execute(transferTx);

minerNode.verify(eth.expectSuccessfulTransactionReceipt(txHash.toHexString()));

assertThat(minerNode.getMiningParameters().getMinTransactionGasPrice())
.isEqualTo(doubleMinGasPrice);
}

@Test
public void updateProfitabilityParamsViaExtraData() throws IOException {
final Web3j web3j = minerNode.nodeRequests().eth();
final Account sender = accounts.getSecondaryBenefactor();
final Account recipient = accounts.createAccount("recipient");
minerNode.getMiningParameters().setMinTransactionGasPrice(MIN_GAS_PRICE);

final var extraData =
createExtraDataPricingField(
MIN_GAS_PRICE.multiply(2).toLong() / WEI_IN_KWEI,
MIN_GAS_PRICE.toLong() / WEI_IN_KWEI,
MIN_GAS_PRICE.toLong() / WEI_IN_KWEI);
final var reqSetExtraData = new ExtraDataPricingTest.MinerSetExtraDataRequest(extraData);
final var respSetExtraData = reqSetExtraData.execute(minerNode.nodeRequests());

assertThat(respSetExtraData).isTrue();

// when this first tx is mined the above extra data pricing will have effect on following txs
final TransferTransaction profitableTx =
accountTransactions.createTransfer(sender, recipient, 1);
final var protitableTx = minerNode.execute(profitableTx);

minerNode.verify(eth.expectSuccessfulTransactionReceipt(protitableTx.toHexString()));

// this tx will be evaluated with the previously set extra data pricing to be unprofitable
final RawTransaction unprofitableTx =
RawTransaction.createTransaction(
BigInteger.ZERO,
MIN_GAS_PRICE.getAsBigInteger(),
BigInteger.valueOf(21000),
recipient.getAddress(),
"");

final byte[] signedUnprofitableTx =
TransactionEncoder.signMessage(
unprofitableTx, Credentials.create(Accounts.GENESIS_ACCOUNT_ONE_PRIVATE_KEY));

final EthSendTransaction signedUnprofitableTxResp =
web3j.ethSendRawTransaction(Numeric.toHexString(signedUnprofitableTx)).send();

assertThat(signedUnprofitableTxResp.hasError()).isTrue();
assertThat(signedUnprofitableTxResp.getError().getMessage()).isEqualTo("Gas price too low");

assertThat(getTxPoolContent()).isEmpty();
}

static class MinerSetExtraDataRequest implements Transaction<Boolean> {
private final Bytes32 extraData;

public MinerSetExtraDataRequest(final Bytes32 extraData) {
this.extraData = extraData;
}

@Override
public Boolean execute(final NodeRequests nodeRequests) {
try {
return new Request<>(
"miner_setExtraData",
List.of(extraData.toHexString()),
nodeRequests.getWeb3jService(),
MinerSetExtraDataResponse.class)
.send()
.getResult();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

static class MinerSetExtraDataResponse extends org.web3j.protocol.core.Response<Boolean> {}
}

private Bytes32 createExtraDataPricingField(
final long fixedCostKWei, final long variableCostKWei, final long minGasPriceKWei) {
final UInt32 fixed = UInt32.valueOf(BigInteger.valueOf(fixedCostKWei));
final UInt32 variable = UInt32.valueOf(BigInteger.valueOf(variableCostKWei));
final UInt32 min = UInt32.valueOf(BigInteger.valueOf(minGasPriceKWei));

return Bytes32.rightPad(
Bytes.concatenate(Bytes.of((byte) 1), fixed.toBytes(), variable.toBytes(), min.toBytes()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public List<String> getTestCliOptions() {
protected void assertIsProfitable(
final Transaction tx,
final Wei baseFee,
final Wei estimatedPriorityFee,
final Wei estimatedMaxGasPrice,
final long estimatedGasLimit) {
final var minGasPrice = minerNode.getMiningParameters().getMinTransactionGasPrice();
Expand All @@ -62,6 +61,6 @@ protected void assertIsProfitable(
protected void assertMinGasPriceLowerBound(final Wei baseFee, final Wei estimatedMaxGasPrice) {
// since we are in compatibility mode, we want to check that returned profitable priority fee is
// the min priority fee per gas * multiplier + base fee
assertIsProfitable(null, baseFee, null, estimatedMaxGasPrice, 0);
assertIsProfitable(null, baseFee, estimatedMaxGasPrice, 0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,11 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.Response;
import org.web3j.protocol.http.HttpService;

public class EstimateGasTest extends LineaPluginTestBase {
protected static final int VERIFICATION_GAS_COST = 1_200_000;
protected static final int VERIFICATION_CAPACITY = 90_000;
protected static final int GAS_PRICE_RATIO = 15;
protected static final int FIXED_GAS_COST_WEI = 0;
protected static final int VARIABLE_GAS_COST_WEI = 1_000_000_000;
protected static final double MIN_MARGIN = 1.0;
protected static final double ESTIMATE_GAS_MIN_MARGIN = 1.0;
protected static final Wei MIN_GAS_PRICE = Wei.of(1_000_000_000);
Expand All @@ -65,9 +63,8 @@ public List<String> getTestCliOptions() {

protected TestCommandLineOptionsBuilder getTestCommandLineOptionsBuilder() {
return new TestCommandLineOptionsBuilder()
.set("--plugin-linea-verification-gas-cost=", String.valueOf(VERIFICATION_GAS_COST))
.set("--plugin-linea-verification-capacity=", String.valueOf(VERIFICATION_CAPACITY))
.set("--plugin-linea-gas-price-ratio=", String.valueOf(GAS_PRICE_RATIO))
.set("--plugin-linea-fixed-gas-cost-wei=", String.valueOf(FIXED_GAS_COST_WEI))
.set("--plugin-linea-variable-gas-cost-wei=", String.valueOf(VARIABLE_GAS_COST_WEI))
.set("--plugin-linea-min-margin=", String.valueOf(MIN_MARGIN))
.set("--plugin-linea-estimate-gas-min-margin=", String.valueOf(ESTIMATE_GAS_MIN_MARGIN))
.set("--plugin-linea-max-tx-gas-limit=", String.valueOf(MAX_TRANSACTION_GAS_LIMIT));
Expand All @@ -82,9 +79,8 @@ public void setMinGasPrice() {
public void createDefaultConfigurations() {
profitabilityConf =
LineaProfitabilityCliOptions.create().toDomainObject().toBuilder()
.verificationCapacity(VERIFICATION_CAPACITY)
.verificationGasCost(VERIFICATION_GAS_COST)
.gasPriceRatio(GAS_PRICE_RATIO)
.fixedCostWei(FIXED_GAS_COST_WEI)
.variableCostWei(VARIABLE_GAS_COST_WEI)
.minMargin(MIN_MARGIN)
.estimateGasMinMargin(ESTIMATE_GAS_MIN_MARGIN)
.build();
Expand Down Expand Up @@ -145,34 +141,29 @@ public void lineaEstimateGasIsProfitable() {
.signature(LineaEstimateGas.FAKE_SIGNATURE_FOR_SIZE_CALCULATION)
.build();

assertIsProfitable(tx, baseFee, estimatedPriorityFee, estimatedMaxGasPrice, estimatedGasLimit);
assertIsProfitable(tx, baseFee, estimatedMaxGasPrice, estimatedGasLimit);
}

protected void assertIsProfitable(
final org.hyperledger.besu.ethereum.core.Transaction tx,
final Wei baseFee,
final Wei estimatedPriorityFee,
final Wei estimatedMaxGasPrice,
final long estimatedGasLimit) {

final var minGasPrice = minerNode.getMiningParameters().getMinTransactionGasPrice();

final var profitabilityCalculator = new TransactionProfitabilityCalculator(profitabilityConf);

final var profitablePriorityFee =
profitabilityCalculator.profitablePriorityFeePerGas(
tx, profitabilityConf.txPoolMinMargin(), minGasPrice, estimatedGasLimit);

assertThat(profitablePriorityFee.greaterThan(minGasPrice)).isTrue();
assertThat(estimatedMaxGasPrice.greaterOrEqualThan(minGasPrice)).isTrue();

assertThat(
profitabilityCalculator.isProfitable(
"Test",
tx,
profitabilityConf.txPoolMinMargin(),
minerNode.getMiningParameters().getMinTransactionGasPrice(),
profitabilityConf.estimateGasMinMargin(),
estimatedMaxGasPrice,
estimatedGasLimit))
estimatedGasLimit,
minGasPrice))
.isTrue();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public static BlockHeader createBlockHeader(
null,
null,
null,
null,
blockHeaderFunctions);
}
}
Loading

0 comments on commit 3d56714

Please sign in to comment.