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

Introduce a rustfmt.toml file with nightly features #4541

Merged
merged 7 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .cargo-husky/hooks/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ set -xe
# Setting RUSTFLAGS env for clippy makes it not include custom rules
RUSTFLAGS=-Dwarnings cargo check --workspace --all-targets --profile bench ${ALL_FEATURES}
cargo clippy --all --all-targets ${ALL_FEATURES} -- -D warnings
cargo fmt --all -- --check
cargo +nightly fmt --all -- --check
cargo test --doc --workspace ${ALL_FEATURES}
cargo test --workspace --all-targets ${ALL_FEATURES}
8 changes: 8 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,12 @@
"ALCHEMY_URL": "${localEnv:ALCHEMY_URL}",
"INFURA_URL": "${localEnv:INFURA_URL}"
},
"customizations": {
"vscode": {
"extensions": ["rust-lang.rust-analyzer"],
"settings": {
"rust-analyzer.rustfmt.extraArgs": ["+nightly"]
}
}
}
}
10 changes: 9 additions & 1 deletion .github/workflows/hardhat-core-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -282,18 +282,26 @@ jobs:
steps:
- uses: actions/checkout@v3

- name: Install nightly rustfmt
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
profile: minimal
components: rustfmt

- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
override: true
components: clippy, rustfmt
components: clippy

- uses: Swatinem/rust-cache@v2

- name: Run cargo fmt
uses: actions-rs/cargo@v1
with:
toolchain: nightly
command: fmt
args: --all --check

Expand Down
15 changes: 7 additions & 8 deletions crates/edr/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use std::{str::FromStr, time::SystemTime};
use std::{net::SocketAddr, path::PathBuf, str::FromStr, time::SystemTime};

use anyhow::anyhow;
use edr_eth::{serde::ZeroXPrefixedBytes, Address, Bytes, SpecId, U256};
Expand All @@ -16,7 +14,8 @@ pub use super::NodeArgs;
mod number;
pub use number::{u256_number, u64_number, Number};

/// struct representing the deserialized conifguration file, eg hardhat.config.json
/// struct representing the deserialized conifguration file, eg
/// hardhat.config.json
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(default)]
pub struct ConfigFile {
Expand Down Expand Up @@ -133,10 +132,10 @@ impl TryFrom<AccountConfig> for ServerAccountConfig {

#[cfg(test)]
mod tests {
use super::*;

use toml;

use super::*;

#[test]
fn test_config_file_serde() {
let config_file = ConfigFile::default();
Expand All @@ -145,8 +144,8 @@ mod tests {
assert_eq!(config_file, deserialized);
}

/// test that specifying a non-default value for one field still allows the other fields to
/// take their default values.
/// test that specifying a non-default value for one field still allows the
/// other fields to take their default values.
#[test]
fn test_config_file_mixed_defaults() {
let original = "chain_id = 999";
Expand Down
3 changes: 2 additions & 1 deletion crates/edr/src/config/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ where
}
}

/// deserialize a [`Number`] but always as a [`Number::U64`], panicking if the value overflows.
/// deserialize a [`Number`] but always as a [`Number::U64`], panicking if the
/// value overflows.
pub fn u64_number<'de, D>(deserializer: D) -> Result<Number, D::Error>
where
D: serde::Deserializer<'de>,
Expand Down
19 changes: 11 additions & 8 deletions crates/edr/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use std::ffi::OsString;
use std::fs;
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::{
ffi::OsString,
fs,
net::{IpAddr, Ipv4Addr},
path::{Path, PathBuf},
};

use anyhow::anyhow;
use clap::{Args, Parser, Subcommand};
use tracing::{event, Level};

use edr_eth::Address;
use tracing::{event, Level};

pub mod config;

Expand All @@ -23,9 +24,11 @@ struct Cli {
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum Command {
/// Start the local Ethereum development node to serve JSON-RPC requests over HTTP.
/// Start the local Ethereum development node to serve JSON-RPC requests
/// over HTTP.
Node(NodeArgs),
/// Write default configuration values to edr.toml, overwriting any existing file.
/// Write default configuration values to edr.toml, overwriting any existing
/// file.
InitConfigFile,
}

Expand Down
30 changes: 16 additions & 14 deletions crates/edr/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use assert_cmd::{
assert::Assert,
cargo::CommandCargoExt, // for process::Command::cargo_bin
};
use predicates::str::contains;

use edr_eth::{
remote::{
client::Request as RpcRequest,
Expand All @@ -17,18 +15,20 @@ use edr_eth::{
Bytes, U256, U64,
};
use edr_rpc_server::{HardhatMethodInvocation, MethodInvocation};
use predicates::str::contains;

#[tokio::test]
async fn node() -> Result<(), Box<dyn std::error::Error>> {
let address = secret_key_to_address(edr_defaults::SECRET_KEYS[0]).unwrap();

// the order of operations is a little weird in this test, because we spawn a separate process
// for the server, and we want to make sure that we end that process gracefully. more
// specifically, once the server is started, we avoid the ? operator until the server has been
// stopped.
// the order of operations is a little weird in this test, because we spawn a
// separate process for the server, and we want to make sure that we end
// that process gracefully. more specifically, once the server is started,
// we avoid the ? operator until the server has been stopped.

// hold method invocations separately from requests so that we can easily iterate over them in
// order to check for corresponding log entries in the server output:
// hold method invocations separately from requests so that we can easily
// iterate over them in order to check for corresponding log entries in the
// server output:
let method_invocations = [
MethodInvocation::Eth(EthMethodInvocation::Accounts()),
MethodInvocation::Eth(EthMethodInvocation::BlockNumber()),
Expand Down Expand Up @@ -93,7 +93,8 @@ async fn node() -> Result<(), Box<dyn std::error::Error>> {
MethodInvocation::Hardhat(HardhatMethodInvocation::StopImpersonatingAccount(address)),
];

// prepare request body before even spawning the server because serialization could fail:
// prepare request body before even spawning the server because serialization
// could fail:
let request_body: String = serde_json::to_string(
&method_invocations
.iter()
Expand Down Expand Up @@ -121,12 +122,12 @@ async fn node() -> Result<(), Box<dyn std::error::Error>> {
.stdout(Stdio::piped())
.spawn()?;

// (required for CI runs on MacOS) sleep a moment to make sure the server comes up before we
// start sending requests:
// (required for CI runs on MacOS) sleep a moment to make sure the server comes
// up before we start sending requests:
std::thread::sleep(std::time::Duration::from_secs(1));

// query the server, but don't check the Result yet, because returning early would prevent us
// from gracefully terminating the server:
// query the server, but don't check the Result yet, because returning early
// would prevent us from gracefully terminating the server:
let send_result = reqwest::Client::new()
.post("http://127.0.0.1:8549/")
.header(reqwest::header::CONTENT_TYPE, "application/json")
Expand All @@ -143,7 +144,8 @@ async fn node() -> Result<(), Box<dyn std::error::Error>> {
// validate query Result:
send_result?.text().await?;

// assert that the standard output of the server process contains the expected log entries:
// assert that the standard output of the server process contains the expected
// log entries:
Assert::new(output.clone()).stdout(contains("Listening on 127.0.0.1:8549"));
for (i, default_secret_key) in edr_defaults::SECRET_KEYS.to_vec().iter().enumerate() {
Assert::new(output.clone())
Expand Down
7 changes: 4 additions & 3 deletions crates/edr_defaults/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ pub const SECRET_KEYS: [&str; 20] = [
"df57089febbacf7ba0bc227dafbffa9fc08a93fdc68e1e42411a14efcf23656e",
];

/// The default cache directory. Cache dirs for specific subsystems such as the RPC Client are
/// subdirectories of this directory.
/// The default cache directory. Cache dirs for specific subsystems such as the
/// RPC Client are subdirectories of this directory.
pub const CACHE_DIR: &str = "./edr-cache";

/// Maximum concurrent requests to a remote blockchain node to avoid getting rate limited.
/// Maximum concurrent requests to a remote blockchain node to avoid getting
/// rate limited.
pub const MAX_CONCURRENT_REQUESTS: usize = 5;
3 changes: 2 additions & 1 deletion crates/edr_eth/src/access_list.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Part of this code was adapted from ethers-rs and is distributed under their licenss:
// Part of this code was adapted from ethers-rs and is distributed under their
// licenss:
// - https://github.com/gakonst/ethers-rs/blob/cba6f071aedafb766e82e4c2f469ed5e4638337d/LICENSE-APACHE
// - https://github.com/gakonst/ethers-rs/blob/cba6f071aedafb766e82e4c2f469ed5e4638337d/LICENSE-MIT
// For the original context see: https://github.com/gakonst/ethers-rs/blob/3d9c3290d42b77c510e5b5d0b6f7a2f72913bfff/ethers-core/src/types/transaction/eip2930.rs
Expand Down
6 changes: 3 additions & 3 deletions crates/edr_eth/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// Part of this code was adapted from foundry and is distributed under their licenss:
// Part of this code was adapted from foundry and is distributed under their
// licenss:
// - https://github.com/foundry-rs/foundry/blob/01b16238ff87dc7ca8ee3f5f13e389888c2a2ee4/LICENSE-APACHE
// - https://github.com/foundry-rs/foundry/blob/01b16238ff87dc7ca8ee3f5f13e389888c2a2ee4/LICENSE-MIT
// For the original context see: https://github.com/foundry-rs/foundry/blob/01b16238ff87dc7ca8ee3f5f13e389888c2a2ee4/anvil/core/src/eth/proof.rs

//! Ethereum account types

pub use revm_primitives::KECCAK_EMPTY;
use revm_primitives::{ruint, AccountInfo};

use crate::{trie::KECCAK_NULL_RLP, B256, U256};

pub use revm_primitives::KECCAK_EMPTY;

/// Basic account type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
Expand Down
45 changes: 26 additions & 19 deletions crates/edr_eth/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Part of this code was adapted from foundry and is distributed under their licenss:
// Part of this code was adapted from foundry and is distributed under their
// licenss:
// - https://github.com/foundry-rs/foundry/blob/01b16238ff87dc7ca8ee3f5f13e389888c2a2ee4/LICENSE-APACHE
// - https://github.com/foundry-rs/foundry/blob/01b16238ff87dc7ca8ee3f5f13e389888c2a2ee4/LICENSE-MIT
// For the original context see: https://github.com/foundry-rs/foundry/blob/01b16238ff87dc7ca8ee3f5f13e389888c2a2ee4/anvil/core/src/eth/block.rs
Expand All @@ -16,13 +17,6 @@ use revm_primitives::{
};
use rlp::Decodable;

use crate::{
transaction::SignedTransaction,
trie::{self, KECCAK_NULL_RLP},
withdrawal::Withdrawal,
Address, Bloom, Bytes, B256, B64, U256,
};

use self::difficulty::calculate_ethash_canonical_difficulty;
pub use self::{
options::BlockOptions,
Expand All @@ -31,6 +25,12 @@ pub use self::{
IsSafeBlockNumberArgs, LargestSafeBlockNumberArgs,
},
};
use crate::{
transaction::SignedTransaction,
trie::{self, KECCAK_NULL_RLP},
withdrawal::Withdrawal,
Address, Bloom, Bytes, B256, B64, U256,
};

/// Ethereum block
#[derive(Clone, Debug, Eq)]
Expand All @@ -54,7 +54,8 @@ pub struct Block {
}

impl Block {
/// Constructs a new block from the provided partial header, transactions, and ommers.
/// Constructs a new block from the provided partial header, transactions,
/// and ommers.
pub fn new(
mut partial_header: PartialHeader,
transactions: Vec<SignedTransaction>,
Expand Down Expand Up @@ -138,7 +139,8 @@ pub struct Header {
/// Blob gas was added by EIP-4844 and is ignored in older headers.
#[cfg_attr(feature = "serde", serde(flatten))]
pub blob_gas: Option<BlobGas>,
/// The hash tree root of the parent beacon block for the given execution block (EIP-4788).
/// The hash tree root of the parent beacon block for the given execution
/// block (EIP-4788).
pub parent_beacon_block_root: Option<B256>,
}

Expand All @@ -159,16 +161,19 @@ impl From<B64Def> for B64 {
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct BlobGas {
/// The total amount of blob gas consumed by the transactions within the block.
/// The total amount of blob gas consumed by the transactions within the
/// block.
pub gas_used: u64,
/// The running total of blob gas consumed in excess of the target, prior to
/// the block. Blocks with above-target blob gas consumption increase this value,
/// blocks with below-target blob gas consumption decrease it (bounded at 0).
/// the block. Blocks with above-target blob gas consumption increase this
/// value, blocks with below-target blob gas consumption decrease it
/// (bounded at 0).
pub excess_gas: u64,
}

impl Header {
/// Constructs a header from the provided [`PartialHeader`], ommers' root hash, transactions' root hash, and withdrawals' root hash.
/// Constructs a header from the provided [`PartialHeader`], ommers' root
/// hash, transactions' root hash, and withdrawals' root hash.
pub fn new(partial_header: PartialHeader, ommers_hash: B256, transactions_root: B256) -> Self {
Self {
parent_hash: partial_header.parent_hash,
Expand Down Expand Up @@ -341,12 +346,14 @@ pub struct PartialHeader {
pub withdrawals_root: Option<B256>,
/// Blob gas was added by EIP-4844 and is ignored in older headers.
pub blob_gas: Option<BlobGas>,
/// The hash tree root of the parent beacon block for the given execution block (EIP-4788).
/// The hash tree root of the parent beacon block for the given execution
/// block (EIP-4788).
pub parent_beacon_block_root: Option<B256>,
}

impl PartialHeader {
/// Constructs a new instance based on the provided [`BlockOptions`] and parent [`Header`] for the given [`SpecId`].
/// Constructs a new instance based on the provided [`BlockOptions`] and
/// parent [`Header`] for the given [`SpecId`].
pub fn new(spec_id: SpecId, options: BlockOptions, parent: Option<&Header>) -> Self {
let timestamp = options.timestamp.unwrap_or_default();
let number = options.number.unwrap_or({
Expand Down Expand Up @@ -403,7 +410,8 @@ impl PartialHeader {
}),
blob_gas: if spec_id >= SpecId::CANCUN {
let excess_gas = parent.and_then(|parent| parent.blob_gas.as_ref()).map_or(
// For the first (post-fork) block, both parent.blob_gas_used and parent.excess_blob_gas are evaluated as 0.
// For the first (post-fork) block, both parent.blob_gas_used and
// parent.excess_blob_gas are evaluated as 0.
0,
|BlobGas {
gas_used,
Expand Down Expand Up @@ -485,9 +493,8 @@ mod tests {

use revm_primitives::ruint::aliases::U64;

use crate::trie::KECCAK_RLP_EMPTY_ARRAY;

use super::*;
use crate::trie::KECCAK_RLP_EMPTY_ARRAY;

#[test]
fn header_rlp_roundtrip() {
Expand Down
3 changes: 2 additions & 1 deletion crates/edr_eth/src/block/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct BlockOptions {
pub base_fee: Option<U256>,
/// The block's withdrawals root
pub withdrawals_root: Option<B256>,
/// The hash tree root of the parent beacon block for the given execution block (EIP-4788).
/// The hash tree root of the parent beacon block for the given execution
/// block (EIP-4788).
pub parent_beacon_block_root: Option<B256>,
}
Loading