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: replace std/hashbrown with alloy_primitives::map #1384

Merged
merged 5 commits into from
Sep 26, 2024
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 crates/contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 9 additions & 7 deletions crates/contract/src/interface.rs
Original file line number Diff line number Diff line change
@@ -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<Selector, (String, usize)>,
functions: SelectorHashMap<(String, usize)>,
}

// TODO: events/errors
Expand Down Expand Up @@ -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<T, S, F>(
fn create_mapping<const N: usize, T, F>(
elements: &BTreeMap<String, Vec<T>>,
signature: F,
) -> HashMap<S, (String, usize)>
) -> FbHashMap<N, (String, usize)>
where
S: std::hash::Hash + Eq,
F: Fn(&T) -> S + Copy,
F: Fn(&T) -> FixedBytes<N> + Copy,
{
elements
.iter()
Expand Down
2 changes: 1 addition & 1 deletion crates/json-rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 4 additions & 6 deletions crates/json-rpc/src/packet.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion crates/network/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions crates/network/src/ethereum/wallet.rs
Original file line number Diff line number Diff line change
@@ -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<Address, Arc<dyn TxSigner<Signature> + Send + Sync>>,
signers: AddressHashMap<Arc<dyn TxSigner<Signature> + Send + Sync>>,
}

impl std::fmt::Debug for EthereumWallet {
Expand Down
11 changes: 7 additions & 4 deletions crates/provider/src/heart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -434,10 +437,10 @@ pub(crate) struct Heartbeat<N, S> {
stream: futures::stream::Fuse<S>,

/// Lookbehind blocks in form of mapping block number -> vector of transaction hashes.
past_blocks: VecDeque<(u64, HashSet<B256>)>,
past_blocks: VecDeque<(u64, B256HashSet)>,

/// Transactions to watch for.
unconfirmed: HashMap<B256, TxWatcher>,
unconfirmed: B256HashMap<TxWatcher>,

/// Ordered map of transactions waiting for confirmations.
waiting_confs: BTreeMap<u64, Vec<TxWatcher>>,
Expand Down
4 changes: 2 additions & 2 deletions crates/pubsub/src/managers/req.rs
Original file line number Diff line number Diff line change
@@ -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<Id, InFlight>,
reqs: HashMap<Id, InFlight>,
}

impl RequestManager {
Expand Down
4 changes: 2 additions & 2 deletions crates/rpc-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 }

Expand All @@ -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"]
12 changes: 6 additions & 6 deletions crates/rpc-client/src/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()),
}
}

Expand Down Expand Up @@ -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 });
Expand Down
5 changes: 2 additions & 3 deletions crates/rpc-client/src/builtin.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc-types-debug/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
18 changes: 10 additions & 8 deletions crates/rpc-types-debug/src/debug.rs
Original file line number Diff line number Diff line change
@@ -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<B256, Bytes>,
///
/// `keccak(rlp(node)) => rlp(node)`
pub state: B256HashMap<Bytes>,
/// 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<B256, Bytes>,
///
/// `keccak(address) => bytecodes`
pub codes: B256HashMap<Bytes>,
/// 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<HashMap<B256, Bytes>>,
pub keys: Option<B256HashMap<Bytes>>,
}
13 changes: 8 additions & 5 deletions crates/rpc-types-engine/src/jwt.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -223,7 +226,7 @@ impl JwtSecret {
validation.set_required_spec_claims(&["iat"]);
let bytes = &self.0;

match decode::<Claims>(jwt, &DecodingKey::from_secret(bytes), &validation) {
match jsonwebtoken::decode::<Claims>(jwt, &DecodingKey::from_secret(bytes), &validation) {
Ok(token) => {
if !token.claims.is_within_time_window() {
Err(JwtError::InvalidIssuanceTimestamp)?
Expand Down
2 changes: 2 additions & 0 deletions crates/rpc-types-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
17 changes: 10 additions & 7 deletions crates/rpc-types-eth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand All @@ -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 }

Expand All @@ -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"]
Expand Down
10 changes: 6 additions & 4 deletions crates/rpc-types-eth/src/erc4337.rs
Original file line number Diff line number Diff line change
@@ -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 <https://notes.ethereum.org/@yoav/SkaX2lS9j#>
Expand All @@ -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<Address, AccountStorage>,
pub known_accounts: AddressHashMap<AccountStorage>,
/// 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"))]
Expand Down
Loading