Skip to content
Open
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
8 changes: 8 additions & 0 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ rustdoc-args = [
workspace = true

[dependencies]
arrayvec.workspace=true
bytes.workspace = true
hex.workspace = true
itoa.workspace = true
Expand Down Expand Up @@ -114,6 +115,7 @@ serde_json.workspace = true
[features]
default = ["std", "map", "map-foldhash"]
std = [
"alloc",
"bytes/std",
"hex/std",
"ruint/std",
Expand All @@ -129,6 +131,12 @@ std = [
"serde?/std",
"sha3?/std",
]
alloc = [
"proptest?/alloc",
"ruint/alloc",
"serde?/alloc",
"hex/alloc",
]
nightly = [
"foldhash?/nightly",
"hashbrown?/nightly",
Expand Down
4 changes: 3 additions & 1 deletion crates/primitives/src/bits/address.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{FixedBytes, aliases::U160, utils::keccak256};
use core::borrow::Borrow;
#[cfg(feature = "alloc")]
use alloc::{
borrow::Borrow,
string::{String, ToString},
};
use core::{fmt, mem::MaybeUninit, str};
Expand Down Expand Up @@ -579,6 +580,7 @@ impl AddressChecksumBuffer {
}

/// Returns the checksum of a formatted address.
#[cfg(feature = "alloc")]
#[inline]
#[allow(clippy::inherent_to_string_shadow_display)]
pub fn to_string(&self) -> String {
Expand Down
10 changes: 9 additions & 1 deletion crates/primitives/src/bits/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,15 @@ impl<'de, const N: usize> Deserialize<'de> for FixedBytes<N> {

fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let len_error =
|i| de::Error::invalid_length(i, &format!("exactly {N} bytes").as_str());
|i| {
// "exactly N bytes" string has len of 15, so we handle N up to 10**17 here safely. Should cover all reasonable N.
let mut string = arrayvec::ArrayString::<32>::new();
if fmt::write(&mut string, format_args!("exactly {N} bytes")).is_ok() {
de::Error::invalid_length(i, &string.as_str())
} else {
de::Error::invalid_length(i, &"exactly N bytes")
}
};
let mut bytes = [0u8; N];

for (i, byte) in bytes.iter_mut().enumerate() {
Expand Down
2 changes: 2 additions & 0 deletions crates/primitives/src/bytes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg(feature = "alloc")]

use crate::FixedBytes;
use alloc::{boxed::Box, vec::Vec};
use core::{
Expand Down
4 changes: 4 additions & 0 deletions crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#![cfg_attr(feature = "nightly", feature(hasher_prefixfree_extras))]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "alloc")]
#[allow(unused_imports)]
#[macro_use]
extern crate alloc;

Expand Down Expand Up @@ -70,6 +72,7 @@ pub use signature::PrimitiveSignature;
pub use signature::{Signature, SignatureError, normalize_v, to_eip155_v};

pub mod utils;
#[cfg(feature = "alloc")]
pub use utils::{KECCAK256_EMPTY, Keccak256, eip191_hash_message, keccak256};

#[doc(hidden)] // Use `hex` directly instead!
Expand Down Expand Up @@ -107,6 +110,7 @@ pub type B160 = FixedBytes<20>;
// Not public API.
#[doc(hidden)]
pub mod private {
#[cfg(feature = "alloc")]
pub use alloc::vec::Vec;
pub use core::{
self,
Expand Down
2 changes: 2 additions & 0 deletions crates/primitives/src/log/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg(feature = "alloc")] // logs are a wrapper over Vec basically, so there is no point in having them without alloc

use crate::{Address, B256, Bloom, Bytes};
use alloc::vec::Vec;

Expand Down
3 changes: 3 additions & 0 deletions crates/primitives/src/signature/sig.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![allow(clippy::missing_const_for_fn)] // On purpose for forward compatibility.

use crate::{B256, U256, hex, normalize_v, signature::SignatureError, uint};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::{fmt::Display, str::FromStr};

Expand Down Expand Up @@ -60,13 +61,15 @@ impl From<Signature> for [u8; 65] {
}
}

#[cfg(feature = "alloc")]
impl From<&Signature> for Vec<u8> {
#[inline]
fn from(value: &Signature) -> Self {
value.as_bytes().to_vec()
}
}

#[cfg(feature = "alloc")]
impl From<Signature> for Vec<u8> {
#[inline]
fn from(value: Signature) -> Self {
Expand Down
3 changes: 3 additions & 0 deletions crates/primitives/src/signed/conversions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::{BigIntConversionError, ParseSignedError, Sign, Signed, utils::twos_complement};
#[cfg(feature = "alloc")]
use alloc::string::String;
use core::str::FromStr;
use ruint::{ToUintError, Uint, UintTryFrom};
Expand Down Expand Up @@ -95,6 +96,7 @@ impl<const BITS: usize, const LIMBS: usize> TryFrom<&str> for Signed<BITS, LIMBS
}
}

#[cfg(feature = "alloc")]
impl<const BITS: usize, const LIMBS: usize> TryFrom<&String> for Signed<BITS, LIMBS> {
type Error = ParseSignedError;

Expand All @@ -104,6 +106,7 @@ impl<const BITS: usize, const LIMBS: usize> TryFrom<&String> for Signed<BITS, LI
}
}

#[cfg(feature = "alloc")]
impl<const BITS: usize, const LIMBS: usize> TryFrom<String> for Signed<BITS, LIMBS> {
type Error = ParseSignedError;

Expand Down
3 changes: 3 additions & 0 deletions crates/primitives/src/signed/int.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::{ParseSignedError, Sign, utils::*};
#[cfg(feature = "alloc")]
use alloc::string::String;
use core::fmt;
use ruint::{BaseConvertError, Uint, UintTryFrom, UintTryTo};
Expand Down Expand Up @@ -367,6 +368,7 @@ impl<const BITS: usize, const LIMBS: usize> Signed<BITS, LIMBS> {
}

/// Convert to a decimal string.
#[cfg(feature = "alloc")]
pub fn to_dec_string(&self) -> String {
let sign = self.sign();
let abs = self.unsigned_abs();
Expand All @@ -393,6 +395,7 @@ impl<const BITS: usize, const LIMBS: usize> Signed<BITS, LIMBS> {
}

/// Convert to a hex string.
#[cfg(feature = "alloc")]
pub fn to_hex_string(&self) -> String {
let sign = self.sign();
let abs = self.unsigned_abs();
Expand Down
2 changes: 2 additions & 0 deletions crates/primitives/src/signed/serde.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::Signed;
#[cfg(feature = "alloc")]
use alloc::string::String;
use core::{fmt, str};
use ruint::Uint;
Expand Down Expand Up @@ -55,6 +56,7 @@ fn deserialize<'de, const BITS: usize, const LIMBS: usize, D: Deserializer<'de>>
v.parse().map_err(serde::de::Error::custom)
}

#[cfg(feature = "alloc")]
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
Expand Down
16 changes: 14 additions & 2 deletions crates/primitives/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
//! Common Ethereum utilities.

use crate::B256;

#[cfg(feature = "alloc")]
use alloc::{boxed::Box, collections::TryReserveError, vec::Vec};
use cfg_if::cfg_if;
use core::{
fmt,
mem::{ManuallyDrop, MaybeUninit},
mem::MaybeUninit,
};

mod units;
#[cfg(feature = "alloc")]
pub use units::{
DecimalSeparator, ParseUnits, Unit, UnitsError, format_ether, format_units, format_units_with,
parse_ether, parse_units,
};

#[cfg(feature = "alloc")]
#[doc(hidden)]
#[deprecated(since = "0.5.0", note = "use `Unit::ETHER.wei()` instead")]
pub const WEI_IN_ETHER: crate::U256 = Unit::ETHER.wei_const();

#[cfg(feature = "alloc")]
#[doc(hidden)]
#[deprecated(since = "0.5.0", note = "use `Unit` instead")]
pub type Units = Unit;
Expand Down Expand Up @@ -51,6 +56,7 @@ macro_rules! try_vec {
///
/// Stable version of `Box::try_new`.
#[inline]
#[cfg(feature = "alloc")]
pub fn box_try_new<T>(value: T) -> Result<Box<T>, TryReserveError> {
let mut boxed = box_try_new_uninit::<T>()?;
unsafe {
Expand All @@ -64,6 +70,7 @@ pub fn box_try_new<T>(value: T) -> Result<Box<T>, TryReserveError> {
/// allocation fails.
///
/// Stable version of `Box::try_new_uninit`.
#[cfg(feature = "alloc")]
#[inline]
pub fn box_try_new_uninit<T>() -> Result<Box<MaybeUninit<T>>, TryReserveError> {
let mut vec = Vec::<MaybeUninit<T>>::new();
Expand All @@ -75,13 +82,14 @@ pub fn box_try_new_uninit<T>() -> Result<Box<MaybeUninit<T>>, TryReserveError> {
// Make sure we got exactly 1 element.
vec.shrink_to(1);

let mut vec = ManuallyDrop::new(vec);
let mut vec = core::mem::ManuallyDrop::new(vec);

// SAFETY: `vec` is exactly one element long and has not been deallocated.
Ok(unsafe { Box::from_raw(vec.as_mut_ptr()) })
}

/// Tries to collect the elements of an iterator into a `Vec`.
#[cfg(feature = "alloc")]
pub fn try_collect_vec<I: Iterator<Item = T>, T>(iter: I) -> Result<Vec<T>, TryReserveError> {
let mut vec = Vec::new();
if let Some(size_hint) = iter.size_hint().1 {
Expand All @@ -92,6 +100,7 @@ pub fn try_collect_vec<I: Iterator<Item = T>, T>(iter: I) -> Result<Vec<T>, TryR
}

/// Tries to create a `Vec` with the given capacity.
#[cfg(feature = "alloc")]
#[inline]
pub fn vec_try_with_capacity<T>(capacity: usize) -> Result<Vec<T>, TryReserveError> {
let mut vec = Vec::new();
Expand All @@ -100,6 +109,7 @@ pub fn vec_try_with_capacity<T>(capacity: usize) -> Result<Vec<T>, TryReserveErr

/// Tries to create a `Vec` of `n` elements, each initialized to `elem`.
// Not public API. Use `try_vec!` instead.
#[cfg(feature = "alloc")]
#[doc(hidden)]
pub fn vec_try_from_elem<T: Clone>(elem: T, n: usize) -> Result<Vec<T>, TryReserveError> {
let mut vec = Vec::new();
Expand All @@ -116,6 +126,7 @@ pub fn vec_try_from_elem<T: Clone>(elem: T, n: usize) -> Result<Vec<T>, TryReser
/// This message is then hashed using [Keccak-256](keccak256).
///
/// [EIP-191]: https://eips.ethereum.org/EIPS/eip-191
#[cfg(feature = "alloc")]
pub fn eip191_hash_message<T: AsRef<[u8]>>(message: T) -> B256 {
keccak256(eip191_message(message))
}
Expand All @@ -126,6 +137,7 @@ pub fn eip191_hash_message<T: AsRef<[u8]>>(message: T) -> B256 {
/// `"\x19Ethereum Signed Message:\n" + message.length + message`
///
/// [EIP-191]: https://eips.ethereum.org/EIPS/eip-191
#[cfg(feature = "alloc")]
pub fn eip191_message<T: AsRef<[u8]>>(message: T) -> Vec<u8> {
fn eip191_message(message: &[u8]) -> Vec<u8> {
let len = message.len();
Expand Down
2 changes: 2 additions & 0 deletions crates/primitives/src/utils/units.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![cfg(feature = "alloc")]

use crate::{I256, ParseSignedError, U256};
use alloc::string::{String, ToString};
use core::fmt;
Expand Down