Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added evm_setBlockGasLimit #332

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
25 changes: 24 additions & 1 deletion SUPPORTED_APIS.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ The `status` options are:
| `EVM` | `evm_setAccountNonce` | `NOT IMPLEMENTED` | Sets the given account's nonce to the specified value |
| `EVM` | `evm_setAccountStorageAt` | `NOT IMPLEMENTED` | Sets the given account's storage slot to the specified data |
| `EVM` | `evm_setAutomine` | `NOT IMPLEMENTED` | Enables or disables the automatic mining of new blocks with each new transaction submitted to the network |
| `EVM` | `evm_setBlockGasLimit` | `NOT IMPLEMENTED` | Sets the Block Gas Limit of the network |
| `EVM` | [`evm_setBlockGasLimit`](#evm_setblockgaslimit) | `SUPPORTED` | Sets the Block Gas Limit of the network |
vbar marked this conversation as resolved.
Show resolved Hide resolved
| `EVM` | `evm_setIntervalMining` | `NOT IMPLEMENTED` | Enables (with a numeric argument greater than 0) or disables (with a numeric argument equal to 0), the automatic mining of blocks at a regular interval of milliseconds, each of which will include all pending transactions |
| [`EVM`](#evm-namespace) | [`evm_setNextBlockTimestamp`](#evm_setnextblocktimestamp) | `SUPPORTED` | Works like `evm_increaseTime`, but takes the exact timestamp that you want in the next block, and increases the time accordingly |
| [`EVM`](#evm-namespace) | [`evm_setTime`](#evm_settime) | `SUPPORTED` | Sets the internal clock time to the given timestamp |
Expand Down Expand Up @@ -1785,6 +1785,29 @@ curl --request POST \
--data '{"jsonrpc": "2.0","id": "1","method": "evm_revert","params": ["0x1"]}'
```

### `evm_setBlockGasLimit`

[source](src/node/evm.rs)

Sets the Block Gas Limit of the network
vbar marked this conversation as resolved.
Show resolved Hide resolved

#### Arguments

+ `gas_limit: U64`

#### Status

`SUPPORTED`

#### Example

```bash
curl --request POST \
--url http://localhost:8011/ \
--header 'content-type: application/json' \
--data '{"jsonrpc": "2.0","id": "1","method": "evm_setBlockGasLimit","params": ["0x1000000000000"]}'
```

## `WEB3 NAMESPACE`

### `web3_clientVersion`
Expand Down
19 changes: 19 additions & 0 deletions e2e-tests/test/evm-apis.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,22 @@ describe("evm_revert", function () {
expect(reverted).to.be.true;
});
});

describe("evm_setBlockGasLimit", function () {
it("Should change block gas limit", async function () {
// Arrange
const wallet = new Wallet(RichAccounts[0].PrivateKey, provider);

// Act
const blockBefore = await provider.getBlock("latest");
const limitBefore = BigNumber.from(blockBefore.gasLimit).toString();
AnastasiiaVashchuk marked this conversation as resolved.
Show resolved Hide resolved
await provider.send("evm_setBlockGasLimit", ["0x1000000000000"]);
await provider.send("evm_mine");
vbar marked this conversation as resolved.
Show resolved Hide resolved
const blockAfter = await provider.getBlock("latest");
await provider.send("evm_setBlockGasLimit", [limitBefore]);
AnastasiiaVashchuk marked this conversation as resolved.
Show resolved Hide resolved

// Assert
expect(limitBefore).to.eq(BigNumber.from("0x4000000000000").toString());
expect(BigNumber.from(blockAfter.gasLimit).toString()).to.eq(BigNumber.from("0x1000000000000").toString());
});
});
3 changes: 3 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ impl TestNodeConfig {

pub mod node {
use clap::Parser;
use multivm::vm_latest::constants::BATCH_GAS_LIMIT;
use serde::Deserialize;
use std::{fmt::Display, str::FromStr};

Expand All @@ -134,6 +135,7 @@ pub mod node {
pub show_gas_details: ShowGasDetails,
pub resolve_hashes: bool,
pub system_contracts_options: system_contracts::Options,
pub batch_gas_limit: u64,
}

impl Default for InMemoryNodeConfig {
Expand All @@ -147,6 +149,7 @@ pub mod node {
show_gas_details: Default::default(),
resolve_hashes: Default::default(),
system_contracts_options: Default::default(),
batch_gas_limit: BATCH_GAS_LIMIT,
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/namespaces/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,14 @@ pub trait EvmNamespaceT {
/// `true` if a snapshot was reverted, otherwise `false`.
#[rpc(name = "evm_revert")]
fn revert_snapshot(&self, snapshot_id: U64) -> RpcResult<bool>;

/// Set the block gas limit for the following blocks.
///
/// # Parameters
/// - `gas_limit`: The new gas limit.
///
/// # Returns
/// `true` if the gas limit changed, `false` if the parameter was the same as the existing gas limit.
#[rpc(name = "evm_setBlockGasLimit")]
fn set_block_gas_limit(&self, gas_limit: U64) -> RpcResult<bool>;
}
9 changes: 9 additions & 0 deletions src/node/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,13 @@ impl<S: ForkSource + std::fmt::Debug + Clone + Send + Sync + 'static> EvmNamespa
})
.into_boxed_future()
}

fn set_block_gas_limit(&self, gas_limit: U64) -> RpcResult<bool> {
self.set_block_gas_limit(gas_limit)
.map_err(|err| {
tracing::error!("failed setting gas limit: {:?}", err);
into_jsrpc_error(Web3Error::InternalError(err))
})
.into_boxed_future()
}
}
41 changes: 29 additions & 12 deletions src/node/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ use multivm::{
},
vm_latest::HistoryDisabled,
vm_latest::{
constants::{BATCH_GAS_LIMIT, MAX_VM_PUBDATA_PER_BATCH},
utils::l2_blocks::load_last_l2_block,
ToTracerPointer, TracerPointer, Vm,
constants::MAX_VM_PUBDATA_PER_BATCH, utils::l2_blocks::load_last_l2_block, ToTracerPointer,
TracerPointer, Vm,
},
};
use std::convert::TryInto;
Expand Down Expand Up @@ -93,6 +92,7 @@ pub fn create_empty_block<TX>(
timestamp: u64,
batch: u32,
parent_block_hash: Option<H256>,
batch_gas_limit: u64,
) -> Block<TX> {
let hash = compute_hash(block_number, H256::zero());
let parent_hash = parent_block_hash.unwrap_or(if block_number == 0 {
Expand All @@ -108,7 +108,7 @@ pub fn create_empty_block<TX>(
l1_batch_number: Some(U64::from(batch)),
transactions: vec![],
gas_used: U256::from(0),
gas_limit: U256::from(BATCH_GAS_LIMIT),
gas_limit: U256::from(batch_gas_limit),
..Default::default()
}
}
Expand Down Expand Up @@ -249,7 +249,13 @@ impl<S: std::fmt::Debug + ForkSource> InMemoryNodeInner<S> {
let mut blocks = HashMap::<H256, Block<TransactionVariant>>::new();
blocks.insert(
block_hash,
create_empty_block(0, NON_FORK_FIRST_BLOCK_TIMESTAMP, 0, None),
create_empty_block(
0,
NON_FORK_FIRST_BLOCK_TIMESTAMP,
0,
None,
config.batch_gas_limit,
),
);

let fee_input_provider =
Expand Down Expand Up @@ -504,7 +510,7 @@ impl<S: std::fmt::Debug + ForkSource> InMemoryNodeInner<S> {
let result = InMemoryNodeInner::estimate_gas_step(
l2_tx.clone(),
gas_per_pubdata_byte,
BATCH_GAS_LIMIT,
self.config.batch_gas_limit,
batch_env.clone(),
system_env.clone(),
&self.fork_storage,
Expand Down Expand Up @@ -1467,7 +1473,7 @@ impl<S: ForkSource + std::fmt::Debug + Clone> InMemoryNode<S> {
l1_batch_number: Some(U64::from(batch_env.number.0)),
transactions: vec![TransactionVariant::Full(transaction)],
gas_used: U256::from(tx_result.statistics.gas_used),
gas_limit: U256::from(BATCH_GAS_LIMIT),
gas_limit: U256::from(inner.config.batch_gas_limit),
..Default::default()
};

Expand Down Expand Up @@ -1642,6 +1648,7 @@ impl<S: ForkSource + std::fmt::Debug + Clone> InMemoryNode<S> {
block_ctx.timestamp,
block_ctx.batch,
Some(parent_block_hash),
inner.config.batch_gas_limit,
);

inner.current_batch = inner.current_batch.saturating_add(1);
Expand Down Expand Up @@ -1758,6 +1765,7 @@ pub fn load_last_l1_batch<S: ReadStorage>(storage: StoragePtr<S>) -> Option<(u64
#[cfg(test)]
mod tests {
use ethabi::{Token, Uint};
use multivm::vm_latest::constants::BATCH_GAS_LIMIT;
use zksync_basic_types::Nonce;
use zksync_types::{utils::deployed_address_create, K256PrivateKey};

Expand Down Expand Up @@ -1823,16 +1831,19 @@ mod tests {

#[tokio::test]
async fn test_create_empty_block_creates_genesis_block_with_hash_and_zero_parent_hash() {
let first_block = create_empty_block::<TransactionVariant>(0, 1000, 1, None);
let first_block =
create_empty_block::<TransactionVariant>(0, 1000, 1, None, BATCH_GAS_LIMIT);

assert_eq!(first_block.hash, compute_hash(0, H256::zero()));
assert_eq!(first_block.parent_hash, H256::zero());
}

#[tokio::test]
async fn test_create_empty_block_creates_block_with_parent_hash_link_to_prev_block() {
let first_block = create_empty_block::<TransactionVariant>(0, 1000, 1, None);
let second_block = create_empty_block::<TransactionVariant>(1, 1000, 1, None);
let first_block =
create_empty_block::<TransactionVariant>(0, 1000, 1, None, BATCH_GAS_LIMIT);
let second_block =
create_empty_block::<TransactionVariant>(1, 1000, 1, None, BATCH_GAS_LIMIT);

assert_eq!(second_block.parent_hash, first_block.hash);
}
Expand All @@ -1844,9 +1855,15 @@ mod tests {
1000,
1,
Some(compute_hash(123, H256::zero())),
BATCH_GAS_LIMIT,
);
let second_block = create_empty_block::<TransactionVariant>(
1,
1000,
1,
Some(first_block.hash),
BATCH_GAS_LIMIT,
);
let second_block =
create_empty_block::<TransactionVariant>(1, 1000, 1, Some(first_block.hash));

assert_eq!(first_block.parent_hash, compute_hash(123, H256::zero()));
assert_eq!(second_block.parent_hash, first_block.hash);
Expand Down
12 changes: 12 additions & 0 deletions src/node/in_memory_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,18 @@ impl<S: ForkSource + std::fmt::Debug + Clone + Send + Sync + 'static> InMemoryNo
})
}

pub fn set_block_gas_limit(&self, gas_limit: U64) -> Result<bool> {
self.get_inner()
.write()
.map_err(|err| anyhow!("failed acquiring lock: {:?}", err))
.map(|mut writer| {
let gas_limit = gas_limit.as_u64();
let same = writer.config.batch_gas_limit == gas_limit;
writer.config.batch_gas_limit = gas_limit;
!same
})
}

pub fn set_balance(&self, address: Address, balance: U256) -> Result<bool> {
self.get_inner()
.write()
Expand Down
1 change: 1 addition & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ pub fn mine_empty_blocks<S: std::fmt::Debug + ForkSource>(
block_ctx.timestamp,
block_ctx.batch,
None,
node.config.batch_gas_limit,
);

node.block_hashes.insert(block.number.as_u64(), block.hash);
Expand Down