From 0b962c615ebbe90711b5b2a4f01b9cff12d60878 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Thu, 26 Sep 2024 16:39:26 +0200 Subject: [PATCH] feat: replace std/hashbrown with alloy_primitives::map (#1384) * feat: replace std/hashbrown with alloy_primitives::map * feat: replace a few BTrees * feat: replace HashSets Co-Authored-By: dhruvmalik007 * fix: enable features * fix: more features --------- Co-authored-by: dhruvmalik007 --- crates/contract/Cargo.toml | 2 +- crates/contract/src/interface.rs | 16 +++++++++------- crates/json-rpc/Cargo.toml | 2 +- crates/json-rpc/src/packet.rs | 10 ++++------ crates/network/Cargo.toml | 2 +- crates/network/src/ethereum/wallet.rs | 6 +++--- crates/provider/src/heart.rs | 11 +++++++---- crates/pubsub/src/managers/req.rs | 4 ++-- crates/rpc-client/Cargo.toml | 4 ++-- crates/rpc-client/src/batch.rs | 12 ++++++------ crates/rpc-client/src/builtin.rs | 5 ++--- crates/rpc-types-debug/Cargo.toml | 2 +- crates/rpc-types-debug/src/debug.rs | 18 ++++++++++-------- crates/rpc-types-engine/src/jwt.rs | 13 ++++++++----- crates/rpc-types-engine/src/lib.rs | 2 ++ crates/rpc-types-eth/Cargo.toml | 17 ++++++++++------- crates/rpc-types-eth/src/erc4337.rs | 10 ++++++---- crates/rpc-types-eth/src/filter.rs | 20 +++++++++----------- crates/rpc-types-eth/src/lib.rs | 12 ------------ crates/rpc-types-eth/src/state.rs | 19 +++++++++++-------- crates/rpc-types-trace/src/filter.rs | 8 ++++---- crates/rpc-types-trace/src/geth/mux.rs | 4 ++-- crates/rpc-types-trace/src/tracerequest.rs | 4 ++-- crates/rpc-types/Cargo.toml | 7 ++++++- crates/rpc-types/src/rpc.rs | 5 +++-- crates/serde/src/other/arbitrary_.rs | 5 +---- crates/serde/src/storage.rs | 10 +++++----- crates/signer-local/Cargo.toml | 10 +++++++--- 28 files changed, 125 insertions(+), 115 deletions(-) diff --git a/crates/contract/Cargo.toml b/crates/contract/Cargo.toml index 4456055d5b2..f93159608f6 100644 --- a/crates/contract/Cargo.toml +++ b/crates/contract/Cargo.toml @@ -27,7 +27,7 @@ alloy-transport.workspace = true alloy-dyn-abi = { workspace = true, features = ["std"] } alloy-json-abi.workspace = true -alloy-primitives.workspace = true +alloy-primitives = { workspace = true, features = ["map"] } alloy-sol-types.workspace = true futures-util.workspace = true diff --git a/crates/contract/src/interface.rs b/crates/contract/src/interface.rs index 58859958233..50ec7ba3b96 100644 --- a/crates/contract/src/interface.rs +++ b/crates/contract/src/interface.rs @@ -1,14 +1,17 @@ use crate::{ContractInstance, Error, Result}; use alloy_dyn_abi::{DynSolValue, FunctionExt, JsonAbiExt}; use alloy_json_abi::{Function, JsonAbi}; -use alloy_primitives::{Address, Selector}; -use std::collections::{BTreeMap, HashMap}; +use alloy_primitives::{ + map::{FbHashMap, SelectorHashMap}, + Address, FixedBytes, Selector, +}; +use std::collections::BTreeMap; /// A smart contract interface. #[derive(Clone, Debug)] pub struct Interface { abi: JsonAbi, - functions: HashMap, + functions: SelectorHashMap<(String, usize)>, } // TODO: events/errors @@ -127,13 +130,12 @@ impl Interface { /// Utility function for creating a mapping between a unique signature and a /// name-index pair for accessing contract ABI items. -fn create_mapping( +fn create_mapping( elements: &BTreeMap>, signature: F, -) -> HashMap +) -> FbHashMap where - S: std::hash::Hash + Eq, - F: Fn(&T) -> S + Copy, + F: Fn(&T) -> FixedBytes + Copy, { elements .iter() diff --git a/crates/json-rpc/Cargo.toml b/crates/json-rpc/Cargo.toml index 79558bd1651..dfc18b79d22 100644 --- a/crates/json-rpc/Cargo.toml +++ b/crates/json-rpc/Cargo.toml @@ -19,7 +19,7 @@ rustdoc-args = ["--cfg", "docsrs"] workspace = true [dependencies] -alloy-primitives = { workspace = true, features = ["std", "serde"] } +alloy-primitives = { workspace = true, features = ["std", "serde", "map"] } serde.workspace = true serde_json = { workspace = true, features = ["std", "raw_value"] } thiserror.workspace = true diff --git a/crates/json-rpc/src/packet.rs b/crates/json-rpc/src/packet.rs index e3d7509aad8..10cf0aafc08 100644 --- a/crates/json-rpc/src/packet.rs +++ b/crates/json-rpc/src/packet.rs @@ -1,10 +1,11 @@ use crate::{ErrorPayload, Id, Response, SerializedRequest}; +use alloy_primitives::map::HashSet; use serde::{ de::{self, Deserializer, MapAccess, SeqAccess, Visitor}, Deserialize, Serialize, }; use serde_json::value::RawValue; -use std::{collections::HashSet, fmt, marker::PhantomData}; +use std::{fmt, marker::PhantomData}; /// A [`RequestPacket`] is a [`SerializedRequest`] or a batch of serialized /// request. @@ -58,11 +59,8 @@ impl RequestPacket { pub fn subscription_request_ids(&self) -> HashSet<&Id> { match self { Self::Single(single) => { - let mut hs = HashSet::with_capacity(1); - if single.method() == "eth_subscribe" { - hs.insert(single.id()); - } - hs + let id = (single.method() == "eth_subscribe").then(|| single.id()); + HashSet::from_iter(id) } Self::Batch(batch) => batch .iter() diff --git a/crates/network/Cargo.toml b/crates/network/Cargo.toml index 8a647bef2e5..21d7e9116eb 100644 --- a/crates/network/Cargo.toml +++ b/crates/network/Cargo.toml @@ -23,7 +23,7 @@ alloy-consensus = { workspace = true, features = ["std"] } alloy-eips = { workspace = true, features = ["serde"] } alloy-json-rpc.workspace = true alloy-network-primitives.workspace = true -alloy-primitives.workspace = true +alloy-primitives = { workspace = true, features = ["map"] } alloy-rpc-types-eth = { workspace = true, features = ["std", "serde"] } alloy-signer.workspace = true alloy-serde.workspace = true diff --git a/crates/network/src/ethereum/wallet.rs b/crates/network/src/ethereum/wallet.rs index aa358ffd884..98f234f0860 100644 --- a/crates/network/src/ethereum/wallet.rs +++ b/crates/network/src/ethereum/wallet.rs @@ -1,14 +1,14 @@ use crate::{Network, NetworkWallet, TxSigner}; use alloy_consensus::{SignableTransaction, TxEnvelope, TypedTransaction}; -use alloy_primitives::Address; +use alloy_primitives::{map::AddressHashMap, Address}; use alloy_signer::Signature; -use std::{collections::BTreeMap, sync::Arc}; +use std::sync::Arc; /// A wallet capable of signing any transaction for the Ethereum network. #[derive(Clone, Default)] pub struct EthereumWallet { default: Address, - signers: BTreeMap + Send + Sync>>, + signers: AddressHashMap + Send + Sync>>, } impl std::fmt::Debug for EthereumWallet { diff --git a/crates/provider/src/heart.rs b/crates/provider/src/heart.rs index 181fc2e7e05..81cfb10dc13 100644 --- a/crates/provider/src/heart.rs +++ b/crates/provider/src/heart.rs @@ -3,11 +3,14 @@ use crate::{Provider, RootProvider}; use alloy_json_rpc::RpcError; use alloy_network::{BlockResponse, HeaderResponse, Network}; -use alloy_primitives::{TxHash, B256}; +use alloy_primitives::{ + map::{B256HashMap, B256HashSet}, + TxHash, B256, +}; use alloy_transport::{utils::Spawnable, Transport, TransportError}; use futures::{stream::StreamExt, FutureExt, Stream}; use std::{ - collections::{BTreeMap, HashMap, HashSet, VecDeque}, + collections::{BTreeMap, VecDeque}, fmt, future::Future, time::{Duration, Instant}, @@ -434,10 +437,10 @@ pub(crate) struct Heartbeat { stream: futures::stream::Fuse, /// Lookbehind blocks in form of mapping block number -> vector of transaction hashes. - past_blocks: VecDeque<(u64, HashSet)>, + past_blocks: VecDeque<(u64, B256HashSet)>, /// Transactions to watch for. - unconfirmed: HashMap, + unconfirmed: B256HashMap, /// Ordered map of transactions waiting for confirmations. waiting_confs: BTreeMap>, diff --git a/crates/pubsub/src/managers/req.rs b/crates/pubsub/src/managers/req.rs index e21eb4f7c70..2acb9c43f54 100644 --- a/crates/pubsub/src/managers/req.rs +++ b/crates/pubsub/src/managers/req.rs @@ -1,11 +1,11 @@ use crate::managers::InFlight; use alloy_json_rpc::{Id, Response, SubId}; -use std::collections::BTreeMap; +use alloy_primitives::map::HashMap; /// Manages in-flight requests. #[derive(Debug, Default)] pub(crate) struct RequestManager { - reqs: BTreeMap, + reqs: HashMap, } impl RequestManager { diff --git a/crates/rpc-client/Cargo.toml b/crates/rpc-client/Cargo.toml index ef694848afb..db810b3011c 100644 --- a/crates/rpc-client/Cargo.toml +++ b/crates/rpc-client/Cargo.toml @@ -19,6 +19,7 @@ rustdoc-args = ["--cfg", "docsrs"] workspace = true [dependencies] +alloy-primitives = { workspace = true, features = ["map"] } alloy-json-rpc.workspace = true alloy-transport-http.workspace = true alloy-transport.workspace = true @@ -32,7 +33,6 @@ tokio-stream = { workspace = true, features = ["sync"] } tower.workspace = true tracing.workspace = true -alloy-primitives = { workspace = true, optional = true } alloy-pubsub = { workspace = true, optional = true } alloy-transport-ws = { workspace = true, optional = true } @@ -56,6 +56,6 @@ futures-util.workspace = true default = ["reqwest"] reqwest = ["dep:url", "dep:reqwest", "alloy-transport-http/reqwest"] hyper = ["dep:url", "alloy-transport-http/hyper"] -pubsub = ["dep:alloy-pubsub", "dep:alloy-primitives"] +pubsub = ["dep:alloy-pubsub"] ws = ["pubsub", "dep:alloy-transport-ws", "dep:url"] ipc = ["pubsub", "dep:alloy-transport-ipc"] diff --git a/crates/rpc-client/src/batch.rs b/crates/rpc-client/src/batch.rs index 0993d22825f..010d8ae65c2 100644 --- a/crates/rpc-client/src/batch.rs +++ b/crates/rpc-client/src/batch.rs @@ -3,13 +3,13 @@ use alloy_json_rpc::{ transform_response, try_deserialize_ok, Id, Request, RequestPacket, ResponsePacket, RpcParam, RpcReturn, SerializedRequest, }; +use alloy_primitives::map::HashMap; use alloy_transport::{Transport, TransportError, TransportErrorKind, TransportResult}; use futures::FutureExt; use pin_project::pin_project; use serde_json::value::RawValue; use std::{ borrow::Cow, - collections::HashMap, future::{Future, IntoFuture}, marker::PhantomData, pin::Pin, @@ -119,7 +119,7 @@ impl<'a, T> BatchRequest<'a, T> { Self { transport, requests: RequestPacket::Batch(Vec::with_capacity(10)), - channels: HashMap::with_capacity(10), + channels: HashMap::with_capacity_and_hasher(10, Default::default()), } } @@ -200,10 +200,10 @@ where return Poll::Ready(Err(e)); } - // We only have mut refs, and we want ownership, so we just replace - // with 0-capacity collections. - let channels = std::mem::replace(channels, HashMap::with_capacity(0)); - let req = std::mem::replace(requests, RequestPacket::Batch(Vec::with_capacity(0))); + // We only have mut refs, and we want ownership, so we just replace with 0-capacity + // collections. + let channels = std::mem::take(channels); + let req = std::mem::replace(requests, RequestPacket::Batch(Vec::new())); let fut = transport.call(req); self.set(Self::AwaitingResponse { channels, fut }); diff --git a/crates/rpc-client/src/builtin.rs b/crates/rpc-client/src/builtin.rs index 911e115ef86..f04265b91d7 100644 --- a/crates/rpc-client/src/builtin.rs +++ b/crates/rpc-client/src/builtin.rs @@ -1,9 +1,8 @@ -use std::str::FromStr; - use alloy_json_rpc::RpcError; use alloy_transport::{BoxTransport, BoxTransportConnect, TransportError, TransportErrorKind}; +use std::str::FromStr; -#[cfg(feature = "pubsub")] +#[cfg(any(feature = "ws", feature = "ipc"))] use alloy_pubsub::PubSubConnect; /// Connection string for built-in transports. diff --git a/crates/rpc-types-debug/Cargo.toml b/crates/rpc-types-debug/Cargo.toml index d8e80c2898a..0a052d47489 100644 --- a/crates/rpc-types-debug/Cargo.toml +++ b/crates/rpc-types-debug/Cargo.toml @@ -19,6 +19,6 @@ rustdoc-args = ["--cfg", "docsrs"] workspace = true [dependencies] -alloy-primitives = { workspace = true, features = ["serde", "std"] } +alloy-primitives = { workspace = true, features = ["serde", "std", "map"] } serde.workspace = true diff --git a/crates/rpc-types-debug/src/debug.rs b/crates/rpc-types-debug/src/debug.rs index 8b6dd044d30..80929a3110b 100644 --- a/crates/rpc-types-debug/src/debug.rs +++ b/crates/rpc-types-debug/src/debug.rs @@ -1,24 +1,26 @@ //! Types for the `debug` API. -use alloy_primitives::{Bytes, B256}; +use alloy_primitives::{map::B256HashMap, Bytes}; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; /// Represents the execution witness of a block. Contains an optional map of state preimages. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ExecutionWitness { /// Map of all hashed trie nodes to their preimages that were required during the execution of /// the block, including during state root recomputation. - /// keccak(rlp(node)) => rlp(node) - pub state: HashMap, + /// + /// `keccak(rlp(node)) => rlp(node)` + pub state: B256HashMap, /// Map of all contract codes (created / accessed) to their preimages that were required during /// the execution of the block, including during state root recomputation. - /// keccak(address) => bytecodes - pub codes: HashMap, + /// + /// `keccak(address) => bytecodes` + pub codes: B256HashMap, /// Map of all hashed account and storage keys (addresses and slots) to their preimages /// (unhashed account addresses and storage slots, respectively) that were required during /// the execution of the block. during the execution of the block. - /// keccak(address|slot) => address|slot + /// + /// `keccak(address|slot) => address|slot` #[serde(default)] - pub keys: Option>, + pub keys: Option>, } diff --git a/crates/rpc-types-engine/src/jwt.rs b/crates/rpc-types-engine/src/jwt.rs index b9b8e68862e..697b2d3136e 100644 --- a/crates/rpc-types-engine/src/jwt.rs +++ b/crates/rpc-types-engine/src/jwt.rs @@ -1,18 +1,20 @@ //! JWT (JSON Web Token) utilities for the Engine API. -use alloc::{format, string::String}; +use alloc::string::String; use alloy_primitives::hex; use core::{str::FromStr, time::Duration}; -use jsonwebtoken::{ - decode, errors::ErrorKind, get_current_timestamp, Algorithm, DecodingKey, Validation, -}; +use jsonwebtoken::get_current_timestamp; use rand::Rng; + #[cfg(feature = "std")] use std::{ fs, io, path::{Path, PathBuf}, }; +#[cfg(feature = "serde")] +use jsonwebtoken::{errors::ErrorKind, Algorithm, DecodingKey, Validation}; + /// Errors returned by the [`JwtSecret`] #[derive(Debug, derive_more::Display)] pub enum JwtError { @@ -106,6 +108,7 @@ const JWT_SECRET_LEN: usize = 64; const JWT_MAX_IAT_DIFF: Duration = Duration::from_secs(60); /// The execution layer client MUST support at least the following alg HMAC + SHA256 (HS256) +#[cfg(feature = "serde")] const JWT_SIGNATURE_ALGO: Algorithm = Algorithm::HS256; /// Claims in JWT are used to represent a set of information about an entity. @@ -223,7 +226,7 @@ impl JwtSecret { validation.set_required_spec_claims(&["iat"]); let bytes = &self.0; - match decode::(jwt, &DecodingKey::from_secret(bytes), &validation) { + match jsonwebtoken::decode::(jwt, &DecodingKey::from_secret(bytes), &validation) { Ok(token) => { if !token.claims.is_within_time_window() { Err(JwtError::InvalidIssuanceTimestamp)? diff --git a/crates/rpc-types-engine/src/lib.rs b/crates/rpc-types-engine/src/lib.rs index aff1c62d518..3c8ae1b5d2e 100644 --- a/crates/rpc-types-engine/src/lib.rs +++ b/crates/rpc-types-engine/src/lib.rs @@ -7,6 +7,8 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] #![cfg_attr(not(feature = "std"), no_std)] +#[macro_use] +#[allow(unused_imports)] extern crate alloc; mod cancun; diff --git a/crates/rpc-types-eth/Cargo.toml b/crates/rpc-types-eth/Cargo.toml index cad5e6a788b..ab2af043485 100644 --- a/crates/rpc-types-eth/Cargo.toml +++ b/crates/rpc-types-eth/Cargo.toml @@ -23,7 +23,7 @@ alloy-eips.workspace = true alloy-consensus.workspace = true alloy-network-primitives.workspace = true alloy-rlp = { workspace = true, features = ["arrayvec", "derive"] } -alloy-primitives = { workspace = true, features = ["rlp"] } +alloy-primitives = { workspace = true, features = ["rlp", "map"] } itertools.workspace = true derive_more = { workspace = true, features = ["display"] } @@ -33,10 +33,6 @@ alloy-serde = { workspace = true, optional = true } serde = { workspace = true, features = ["derive"], optional = true } serde_json = { workspace = true, optional = true } -# `no_std` compatibility -cfg-if.workspace = true -hashbrown = { workspace = true, features = ["serde"] } - # arbitrary arbitrary = { version = "1.3", features = ["derive"], optional = true } @@ -62,12 +58,19 @@ assert_matches.workspace = true [features] default = ["std", "serde"] std = ["alloy-primitives/std", "alloy-consensus/std", "alloy-eips/std"] -serde = ["dep:serde", "dep:serde_json", "dep:alloy-serde", "alloy-primitives/serde", "alloy-consensus/serde", "alloy-eips/serde"] +serde = [ + "dep:serde", + "dep:serde_json", + "dep:alloy-serde", + "alloy-primitives/serde", + "alloy-consensus/serde", + "alloy-eips/serde", +] arbitrary = [ "std", "dep:arbitrary", "alloy-primitives/arbitrary", - "alloy-serde/arbitrary", + "alloy-serde?/arbitrary", "alloy-eips/arbitrary", ] jsonrpsee-types = ["dep:jsonrpsee-types"] diff --git a/crates/rpc-types-eth/src/erc4337.rs b/crates/rpc-types-eth/src/erc4337.rs index c89f8761285..728bf56c9e0 100644 --- a/crates/rpc-types-eth/src/erc4337.rs +++ b/crates/rpc-types-eth/src/erc4337.rs @@ -1,7 +1,9 @@ -use crate::{collections::HashMap, Log, TransactionReceipt}; -use alloy_primitives::{Address, BlockNumber, Bytes, B256, U256}; - +use crate::{Log, TransactionReceipt}; use alloc::vec::Vec; +use alloy_primitives::{ + map::{AddressHashMap, HashMap}, + Address, BlockNumber, Bytes, B256, U256, +}; /// Options for conditional raw transaction submissions. // reference for the implementation @@ -13,7 +15,7 @@ pub struct ConditionalOptions { /// A map of account addresses to their expected storage states. /// Each account can have a specified storage root or explicit slot-value pairs. #[cfg_attr(feature = "serde", serde(default))] - pub known_accounts: HashMap, + pub known_accounts: AddressHashMap, /// The minimal block number at which the transaction can be included. /// `None` indicates no minimum block number constraint. #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))] diff --git a/crates/rpc-types-eth/src/filter.rs b/crates/rpc-types-eth/src/filter.rs index 15eeac71c48..e1acdb707ee 100644 --- a/crates/rpc-types-eth/src/filter.rs +++ b/crates/rpc-types-eth/src/filter.rs @@ -1,17 +1,15 @@ use crate::{BlockNumberOrTag, Log as RpcLog, Transaction}; use alloc::{string::String, vec::Vec}; -use alloy_primitives::{keccak256, Address, BlockHash, Bloom, BloomInput, B256, U256, U64}; -use itertools::{EitherOrBoth::*, Itertools}; - -use crate::collections::{ - hash_set::{IntoIter, Iter}, - HashSet, +use alloy_primitives::{ + keccak256, + map::{hash_set, HashSet}, + Address, BlockHash, Bloom, BloomInput, B256, U256, U64, }; use core::{ hash::Hash, - iter::{FromIterator, IntoIterator}, ops::{RangeFrom, RangeInclusive, RangeToInclusive}, }; +use itertools::{EitherOrBoth::*, Itertools}; /// Helper type to represent a bloom filter used for matching logs. #[derive(Debug, Default)] @@ -32,14 +30,14 @@ impl BloomFilter { } } +/// FilterSet is a set of values that will be used to filter logs. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Deserialize))] -/// FilterSet is a set of values that will be used to filter logs pub struct FilterSet(HashSet); impl From for FilterSet { fn from(src: T) -> Self { - Self([src].into()) + Self(FromIterator::from_iter(core::iter::once(src))) } } @@ -88,7 +86,7 @@ impl From>> for FilterSet { impl IntoIterator for FilterSet { type Item = T; - type IntoIter = IntoIter; + type IntoIter = hash_set::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -115,7 +113,7 @@ impl FilterSet { /// Returns an iterator over the underlying HashSet. Values are visited /// in an arbitrary order. - pub fn iter(&self) -> Iter<'_, T> { + pub fn iter(&self) -> hash_set::Iter<'_, T> { self.0.iter() } } diff --git a/crates/rpc-types-eth/src/lib.rs b/crates/rpc-types-eth/src/lib.rs index 1351f3412a9..1d81880413b 100644 --- a/crates/rpc-types-eth/src/lib.rs +++ b/crates/rpc-types-eth/src/lib.rs @@ -11,18 +11,6 @@ #[allow(unused_imports)] extern crate alloc; -/// Standardized collections across `std` and `no_std` environments. -pub mod collections { - cfg_if::cfg_if! { - if #[cfg(feature = "std")] { - pub use std::collections::{hash_set, HashMap, HashSet}; - use hashbrown as _; - } else { - pub use hashbrown::{hash_set, HashMap, HashSet}; - } - } -} - pub use alloy_eips::eip4895::Withdrawal; mod account; diff --git a/crates/rpc-types-eth/src/state.rs b/crates/rpc-types-eth/src/state.rs index 8843edb06cf..4c53d664139 100644 --- a/crates/rpc-types-eth/src/state.rs +++ b/crates/rpc-types-eth/src/state.rs @@ -1,11 +1,14 @@ //! bindings for state overrides in eth_call -use crate::{collections::HashMap, BlockOverrides}; +use crate::BlockOverrides; use alloc::boxed::Box; -use alloy_primitives::{Address, Bytes, B256, U256}; +use alloy_primitives::{ + map::{AddressHashMap, B256HashMap}, + Address, Bytes, B256, U256, +}; /// A set of account overrides -pub type StateOverride = HashMap; +pub type StateOverride = AddressHashMap; /// Custom account override used in call #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -31,11 +34,11 @@ pub struct AccountOverride { /// Fake key-value mapping to override all slots in the account storage before executing the /// call. #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))] - pub state: Option>, + pub state: Option>, /// Fake key-value mapping to override individual slots in the account storage before executing /// the call. #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))] - pub state_diff: Option>, + pub state_diff: Option>, /// Moves addresses precompile into the specified address. This move is done before the 'code' /// override is set. When the specified address is not a precompile, the behaviour is undefined /// and different clients might behave differently. @@ -183,7 +186,7 @@ mod tests { #[test] fn test_evm_overrides_new() { - let state: StateOverride = HashMap::new(); + let state = StateOverride::default(); let block: Box = Box::default(); let evm_overrides = EvmOverrides::new(Some(state.clone()), Some(block.clone())); @@ -196,7 +199,7 @@ mod tests { #[test] fn test_evm_overrides_state() { - let state: StateOverride = HashMap::new(); + let state = StateOverride::default(); let evm_overrides = EvmOverrides::state(Some(state.clone())); assert!(evm_overrides.has_state()); @@ -216,7 +219,7 @@ mod tests { #[test] fn test_evm_overrides_with_state() { - let state: StateOverride = HashMap::new(); + let state = StateOverride::default(); let mut evm_overrides = EvmOverrides::default(); assert!(!evm_overrides.has_state()); diff --git a/crates/rpc-types-trace/src/filter.rs b/crates/rpc-types-trace/src/filter.rs index dfa56916301..3f6e64c178d 100644 --- a/crates/rpc-types-trace/src/filter.rs +++ b/crates/rpc-types-trace/src/filter.rs @@ -1,11 +1,11 @@ -//! `trace_filter` types and support +//! `trace_filter` types and support. + use crate::parity::{ Action, CallAction, CreateAction, CreateOutput, RewardAction, SelfdestructAction, TraceOutput, TransactionTrace, }; -use alloy_primitives::Address; +use alloy_primitives::{map::AddressHashSet, Address}; use serde::{Deserialize, Serialize}; -use std::collections::HashSet; /// Trace filter. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -101,7 +101,7 @@ pub enum TraceFilterMode { /// This is a set of addresses to match against. /// An empty set matches all addresses. #[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct AddressFilter(pub HashSet
); +pub struct AddressFilter(pub AddressHashSet); impl FromIterator
for AddressFilter { fn from_iter>(iter: I) -> Self { diff --git a/crates/rpc-types-trace/src/geth/mux.rs b/crates/rpc-types-trace/src/geth/mux.rs index 30da80c1ae4..fd79900c4a3 100644 --- a/crates/rpc-types-trace/src/geth/mux.rs +++ b/crates/rpc-types-trace/src/geth/mux.rs @@ -1,8 +1,8 @@ //! Geth `muxTracer` types. use crate::geth::{GethDebugBuiltInTracerType, GethDebugTracerConfig, GethTrace}; +use alloy_primitives::map::HashMap; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; /// A `muxTracer` config that contains the configuration for running multiple tracers in one go. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -61,7 +61,7 @@ mod tests { let call_config = CallConfig { only_top_call: Some(true), with_log: Some(true) }; let prestate_config = PreStateConfig { diff_mode: Some(true) }; - opts.tracing_options.tracer_config = MuxConfig(HashMap::from([ + opts.tracing_options.tracer_config = MuxConfig(HashMap::from_iter([ (GethDebugBuiltInTracerType::FourByteTracer, None), (GethDebugBuiltInTracerType::CallTracer, Some(call_config.into())), (GethDebugBuiltInTracerType::PreStateTracer, Some(prestate_config.into())), diff --git a/crates/rpc-types-trace/src/tracerequest.rs b/crates/rpc-types-trace/src/tracerequest.rs index c147c1c66fe..f0024b1dba3 100644 --- a/crates/rpc-types-trace/src/tracerequest.rs +++ b/crates/rpc-types-trace/src/tracerequest.rs @@ -1,11 +1,11 @@ //! Builder style functions for `trace_call` use crate::parity::TraceType; +use alloy_primitives::map::HashSet; use alloy_rpc_types_eth::{ request::TransactionRequest, state::StateOverride, BlockId, BlockOverrides, }; use serde::{Deserialize, Serialize}; -use std::collections::HashSet; /// Container type for `trace_call` arguments #[derive(Debug, Default, Serialize, Deserialize)] @@ -27,7 +27,7 @@ impl TraceCallRequest { pub fn new(call: TransactionRequest) -> Self { Self { call, - trace_types: HashSet::new(), + trace_types: HashSet::default(), block_id: None, state_overrides: None, block_overrides: None, diff --git a/crates/rpc-types/Cargo.toml b/crates/rpc-types/Cargo.toml index 0027917ddc5..56a85a64d8d 100644 --- a/crates/rpc-types/Cargo.toml +++ b/crates/rpc-types/Cargo.toml @@ -19,6 +19,7 @@ rustdoc-args = ["--cfg", "docsrs"] workspace = true [dependencies] +alloy-primitives = { workspace = true, features = ["map"] } alloy-serde.workspace = true alloy-rpc-types-admin = { workspace = true, optional = true } alloy-rpc-types-anvil = { workspace = true, optional = true } @@ -35,7 +36,11 @@ serde = { workspace = true, features = ["derive", "std"] } serde_json.workspace = true [features] -default = ["eth", "alloy-rpc-types-engine?/default", "alloy-rpc-types-eth?/default"] +default = [ + "eth", + "alloy-rpc-types-engine?/default", + "alloy-rpc-types-eth?/default", +] admin = ["dep:alloy-rpc-types-admin"] anvil = ["dep:alloy-rpc-types-anvil"] beacon = ["dep:alloy-rpc-types-beacon"] diff --git a/crates/rpc-types/src/rpc.rs b/crates/rpc-types/src/rpc.rs index c6f062cfa5e..07da2c09c16 100644 --- a/crates/rpc-types/src/rpc.rs +++ b/crates/rpc-types/src/rpc.rs @@ -1,6 +1,7 @@ //! Types for the `rpc` API. + +use alloy_primitives::map::HashMap; use serde::{Deserialize, Serialize}; -use std::collections::HashMap; /// Represents the `rpc_modules` response, which returns the /// list of all available modules on that transport and their version @@ -28,7 +29,7 @@ mod tests { #[test] fn test_parse_module_versions_roundtrip() { let s = r#"{"txpool":"1.0","trace":"1.0","eth":"1.0","web3":"1.0","net":"1.0"}"#; - let module_map = HashMap::from([ + let module_map = HashMap::from_iter([ ("txpool".to_owned(), "1.0".to_owned()), ("trace".to_owned(), "1.0".to_owned()), ("eth".to_owned(), "1.0".to_owned()), diff --git a/crates/serde/src/other/arbitrary_.rs b/crates/serde/src/other/arbitrary_.rs index 1b437780121..7239b5c3d63 100644 --- a/crates/serde/src/other/arbitrary_.rs +++ b/crates/serde/src/other/arbitrary_.rs @@ -1,8 +1,5 @@ use crate::OtherFields; -use alloc::collections::BTreeMap; - -#[cfg(not(feature = "std"))] -use alloc::{string::String, vec::Vec}; +use alloc::{collections::BTreeMap, string::String, vec::Vec}; impl arbitrary::Arbitrary<'_> for OtherFields { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result { diff --git a/crates/serde/src/storage.rs b/crates/serde/src/storage.rs index 1d32a6becc1..a719437f813 100644 --- a/crates/serde/src/storage.rs +++ b/crates/serde/src/storage.rs @@ -94,13 +94,13 @@ where Ok(B256::from_slice(&padded)) } -/// Deserializes the input into an Option>, using [from_bytes_to_b256] which -/// allows cropped values: +/// Deserializes the input into a storage map, using [from_bytes_to_b256] which allows cropped +/// values: /// /// ```json -/// { -/// "0x0000000000000000000000000000000000000000000000000000000000000001": "0x22" -/// } +/// { +/// "0x0000000000000000000000000000000000000000000000000000000000000001": "0x22" +/// } /// ``` pub fn deserialize_storage_map<'de, D>( deserializer: D, diff --git a/crates/signer-local/Cargo.toml b/crates/signer-local/Cargo.toml index f0ff36c73d8..e5d41c93729 100644 --- a/crates/signer-local/Cargo.toml +++ b/crates/signer-local/Cargo.toml @@ -30,7 +30,6 @@ thiserror.workspace = true async-trait.workspace = true # keystore -elliptic-curve = { workspace = true, optional = true } eth-keystore = { version = "0.5.0", default-features = false, optional = true } # mnemonic @@ -40,7 +39,12 @@ coins-bip39 = { version = "0.12", default-features = false, features = [ ], optional = true } # yubi -yubihsm = { version = "0.42", features = ["secp256k1", "http", "usb"], optional = true } +elliptic-curve = { workspace = true, optional = true } +yubihsm = { version = "0.42", features = [ + "secp256k1", + "http", + "usb", +], optional = true } [dev-dependencies] alloy-dyn-abi.workspace = true @@ -57,7 +61,7 @@ tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } yubihsm = { version = "0.42", features = ["mockhsm"] } [features] -keystore = ["dep:eth-keystore", "dep:elliptic-curve"] +keystore = ["dep:eth-keystore"] keystore-geth-compat = ["keystore", "eth-keystore?/geth-compat"] mnemonic = ["dep:coins-bip32", "dep:coins-bip39"] mnemonic-all-languages = ["mnemonic", "coins-bip39?/all-langs"]