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

add no-std #25

Merged
merged 46 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from 45 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
fa609b9
Started with no-std feature
Mar 15, 2022
ce34b54
Changes to make crate std compatible.
Mar 17, 2022
ca69391
Cleanup and improvements.
Mar 17, 2022
ca2b412
Unreachable code warning fixed.
Mar 17, 2022
fac4bf0
Downgrades edition.
Mar 18, 2022
f71b8b5
Reverts downgrades edition.
Mar 18, 2022
84e4a03
Adds default features flag = false to dependency crates.
Apr 19, 2022
6fab3ce
Fixes some errors in the new deserialize mod.
ralexstokes Jan 22, 2023
cd94963
Adds missing vec dependency for no-std version.
May 23, 2022
b677cab
Removes Rust version constraint, Cargo metadata.
May 25, 2022
89a4a94
Adds no-std for depedencies.
May 25, 2022
2b2bb75
Replaces std imports with mod std imports.
May 26, 2022
8d6ac86
Cleanup and improvements (#4)
claravanstaden Nov 17, 2022
a82a9f3
Fixes failure tests resulting in stack overflow error. (#5)
claravanstaden Nov 17, 2022
a7eda87
Reverts changes that should be reverted before contributing back.
Nov 17, 2022
a231367
Change error messages back to what they were. (#6)
claravanstaden Nov 17, 2022
a2df26b
Fixes missed merge-conflict change.
Nov 22, 2022
e402ea1
Update ssz-rs/Cargo.toml
claravanstaden Nov 23, 2022
2fc2ea2
Removes spin std from std feature.
Nov 23, 2022
9a706f1
Use std lib for tests so crate std mod doesn't have to be public.
Nov 23, 2022
7d636e7
Removes unnecessary license comment.
Nov 23, 2022
ae37fa7
Removes incorrect serde feature.
Nov 23, 2022
25c49d9
Std module improvement.
Nov 23, 2022
8c0082d
cargo fmt
Nov 23, 2022
897aeef
Removes exposing std crate publicly. Adds back Vector export.
Dec 14, 2022
ae17a5c
Implements From impl from SerializeError to MerkleizationError::Seria…
Dec 14, 2022
4a27c1f
Removes std mod and moves imports into lib.
Dec 14, 2022
97e6124
Adds Display implementation for SimpleSerializeError.
Dec 14, 2022
e53d213
enable `serde` feature in no_std (#8)
bluele Jan 16, 2023
f47e492
Several cleanup changes related PR comments.
Jan 17, 2023
aaf8649
Cargo fmt
Jan 17, 2023
e8fafc8
Fix clippy warning
Jan 18, 2023
0da9dae
Error and display implementations cleanup.
Jan 19, 2023
8545f60
Error cleanup.
Jan 19, 2023
090e913
Adds lib dependency for utils.
Jan 19, 2023
832d40b
Removes comment.
Jan 19, 2023
945c827
Revert import.
Jan 19, 2023
1392dbc
Cargo.toml cleanup.
Jan 19, 2023
4f19253
integrate new errors into `no-std` world
ralexstokes Jan 22, 2023
0a451ae
formatting
ralexstokes Jan 23, 2023
3effc83
remove redundant flag
ralexstokes Jan 23, 2023
6e2c844
Merge branch 'main' into no-std
ralexstokes Jan 23, 2023
7574018
clean up error refactor
ralexstokes Jan 23, 2023
1a2c446
clean up `prelude` export
ralexstokes Jan 23, 2023
3bd2990
misc cleanups
ralexstokes Jan 23, 2023
64fed64
Update ssz-rs/src/merkleization/mod.rs
ralexstokes Jan 23, 2023
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: 2 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ jobs:
run: cargo build --all-features --verbose
- name: Run tests
run: cargo test --all-features --verbose
- name: Build no-std
run: cargo build --no-default-features --verbose
ralexstokes marked this conversation as resolved.
Show resolved Hide resolved
13 changes: 9 additions & 4 deletions ssz-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,22 @@ exclude = [
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["serde"]
default = ["serde", "std"]
std = [
"bitvec/default",
"sha2/default",
"num-bigint/default",
]
serde = ["dep:serde", "dep:hex"]

[dependencies]
thiserror = "1.0.25"
bitvec = "1.0.0"
bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] }
ssz-rs-derive = { path = "../ssz-rs-derive"}
sha2 = "0.9.8"
sha2 = { version ="0.9.8", default-features = false}
serde = { version = "1.0", features = ["derive"], optional = true }
hex = {version = "0.4.3", optional = true }
num-bigint = "0.4.3"
num-bigint = { version ="0.4.3", default-features = false}

[dev-dependencies]
hex-literal = "0.3.3"
Expand Down
1 change: 1 addition & 0 deletions ssz-rs/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! can likely be simplified to a definition over `const N: usize`.
use crate::de::{deserialize_homogeneous_composite, Deserialize, DeserializeError};
use crate::error::{InstanceError, TypeError};
use crate::lib::*;
use crate::merkleization::{
merkleize, pack, MerkleizationError, Merkleized, Node, BYTES_PER_CHUNK,
};
Expand Down
3 changes: 1 addition & 2 deletions ssz-rs/src/bitlist.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use crate::de::{Deserialize, DeserializeError};
use crate::error::InstanceError;
use crate::lib::*;
use crate::merkleization::{
merkleize, mix_in_length, pack_bytes, MerkleizationError, Merkleized, Node,
};
use crate::ser::{Serialize, SerializeError};
use crate::{SimpleSerialize, Sized};
use bitvec::prelude::{BitVec, Lsb0};
use std::fmt;
use std::ops::{Deref, DerefMut};

// +1 for length bit
fn byte_length(bound: usize) -> usize {
Expand Down
3 changes: 1 addition & 2 deletions ssz-rs/src/bitvector.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use crate::de::{Deserialize, DeserializeError};
use crate::error::TypeError;
use crate::lib::*;
use crate::merkleization::{merkleize, pack_bytes, MerkleizationError, Merkleized, Node};
use crate::ser::{Serialize, SerializeError};
use crate::{SimpleSerialize, Sized};
use bitvec::field::BitField;
use bitvec::prelude::{BitVec, Lsb0};
use std::fmt;
use std::ops::{Deref, DerefMut};

fn byte_length(bound: usize) -> usize {
(bound + 7) / 8
Expand Down
1 change: 1 addition & 0 deletions ssz-rs/src/boolean.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::de::{Deserialize, DeserializeError};
use crate::lib::*;
use crate::merkleization::{MerkleizationError, Merkleized, Node};
use crate::ser::{Serialize, SerializeError};
use crate::{SimpleSerialize, Sized};
Expand Down
40 changes: 31 additions & 9 deletions ssz-rs/src/de.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,42 @@
use crate::error::{InstanceError, TypeError};
use crate::lib::*;
use crate::ser::BYTES_PER_LENGTH_OFFSET;
use crate::SimpleSerialize;
use thiserror::Error;

#[derive(Error, Debug)]
#[derive(Debug)]
pub enum DeserializeError {
#[error("expected at least {expected} bytes when decoding but provided only {provided} bytes")]
ExpectedFurtherInput { provided: usize, expected: usize },
#[error("{provided} bytes given but only expected {expected} bytes")]
AdditionalInput { provided: usize, expected: usize },
#[error("invalid byte {0:x} when decoding data of the expected type")]
InvalidByte(u8),
#[error("invalid instance: {0}")]
InvalidInstance(#[from] InstanceError),
#[error("invalid type: {0}")]
InvalidType(#[from] TypeError),
InvalidInstance(InstanceError),
InvalidType(TypeError),
}

impl From<InstanceError> for DeserializeError {
fn from(err: InstanceError) -> Self {
Self::InvalidInstance(err)
}
}

impl From<TypeError> for DeserializeError {
fn from(err: TypeError) -> Self {
Self::InvalidType(err)
}
}

impl Display for DeserializeError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
DeserializeError::ExpectedFurtherInput { provided, expected } => write!(f, "expected at least {expected} bytes when decoding but provided only {provided} bytes"),
DeserializeError::AdditionalInput { provided, expected } => write!(f, "{provided} bytes given but only expected {expected} bytes"),
DeserializeError::InvalidByte(b) => write!(
f,
"invalid byte {b:x} when decoding data of the expected type"
),
DeserializeError::InvalidInstance(err) => write!(f, "invalid instance: {err}"),
DeserializeError::InvalidType(err) => write!(f, "invalid type: {err}"),
}
}
}

pub trait Deserialize {
Expand Down
73 changes: 60 additions & 13 deletions ssz-rs/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,76 @@
use crate::de::DeserializeError;
use crate::lib::*;
use crate::merkleization::MerkleizationError;
use crate::ser::SerializeError;
use thiserror::Error;

// Top-level error to wrap all child errors in crate
#[derive(Debug, Error)]
#[derive(Debug)]
pub enum Error {
#[error("could not serialize: {0}")]
Serialize(#[from] SerializeError),
#[error("could not deserialize: {0}")]
Deserialize(#[from] DeserializeError),
#[error("merkleization error: {0}")]
Merkleization(#[from] MerkleizationError),
Serialize(SerializeError),
Deserialize(DeserializeError),
Merkleization(MerkleizationError),
}

#[derive(Error, Debug)]
impl From<SerializeError> for Error {
fn from(err: SerializeError) -> Self {
Self::Serialize(err)
}
}

impl From<DeserializeError> for Error {
fn from(err: DeserializeError) -> Self {
Self::Deserialize(err)
}
}

impl From<MerkleizationError> for Error {
fn from(err: MerkleizationError) -> Self {
Self::Merkleization(err)
}
}

impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Serialize(err) => write!(f, "could not serialize: {err}"),
Self::Deserialize(err) => write!(f, "could not deserialize: {err}"),
Self::Merkleization(err) => write!(f, "merkleization error: {err}"),
}
}
}

#[derive(Debug)]
pub enum TypeError {
#[error("the type for this value is invalid with bound {0}")]
InvalidBound(usize),
}

#[derive(Error, Debug)]
impl Display for TypeError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidBound(size) => {
write!(f, "the type for this value is invalid with bound {size}")
}
}
}
}

#[derive(Debug)]
pub enum InstanceError {
#[error("required {required} elements for this type but {provided} elements given")]
Exact { required: usize, provided: usize },
#[error("{provided} elements given for a type with (inclusive) upper bound {bound}")]
Bounded { bound: usize, provided: usize },
}

impl Display for InstanceError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Exact { required, provided } => write!(
f,
"required {required} elements for this type but {provided} elements given"
),
Self::Bounded { bound, provided } => write!(
f,
"{provided} elements given for a type with (inclusive) upper bound {bound}"
),
}
}
}
33 changes: 31 additions & 2 deletions ssz-rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;
ralexstokes marked this conversation as resolved.
Show resolved Hide resolved

mod array;
mod bitlist;
mod bitvector;
Expand All @@ -20,12 +25,36 @@ pub use bitvector::Bitvector;
pub use de::{Deserialize, DeserializeError};
pub use error::Error;
pub use list::List;
pub use merkleization::{Context as MerkleizationContext, MerkleizationError, Merkleized, Node};
pub use merkleization::{MerkleizationError, Merkleized, Node};
pub use ser::{Serialize, SerializeError};
pub use uint::U256;
pub use utils::*;
pub use vector::Vector;
ralexstokes marked this conversation as resolved.
Show resolved Hide resolved

mod lib {
mod core {
#[cfg(not(feature = "std"))]
pub use core::*;
#[cfg(feature = "std")]
pub use std::*;
}

pub use self::core::{any, cmp, fmt, iter, slice};

pub use self::cmp::Ordering;
pub use self::core::array::TryFromSliceError;
pub use self::core::fmt::{Debug, Display, Formatter};
pub use self::core::ops::{Deref, DerefMut, Index, IndexMut};
pub use self::core::slice::{IterMut, SliceIndex};
pub use self::iter::Enumerate;

#[cfg(not(feature = "std"))]
pub use alloc::{format, string::String, vec, vec::Vec};

#[cfg(feature = "std")]
pub use std::vec::Vec;
}

/// `Sized` is a trait for types that can
/// provide sizing information relevant for the SSZ spec.
pub trait Sized {
Expand All @@ -51,6 +80,7 @@ pub mod prelude {
pub use crate::bitvector::Bitvector;
pub use crate::de::Deserialize;
pub use crate::de::DeserializeError;
pub use crate::error::{InstanceError, TypeError};
pub use crate::list::List;
pub use crate::merkleization::{
is_valid_merkle_branch, merkleize, mix_in_selector, pack, pack_bytes, MerkleizationError,
Expand All @@ -61,7 +91,6 @@ pub mod prelude {
pub use crate::utils::{deserialize, serialize};
pub use crate::vector::Vector;
pub use crate::Error as SimpleSerializeError;
pub use crate::MerkleizationContext;
pub use crate::SimpleSerialize;
pub use crate::Sized;
pub use ssz_rs_derive::SimpleSerialize;
Expand Down
9 changes: 3 additions & 6 deletions ssz-rs/src/list.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::de::{deserialize_homogeneous_composite, Deserialize, DeserializeError};
use crate::error::InstanceError;
use crate::lib::*;
use crate::merkleization::{
merkleize, mix_in_length, pack, MerkleCache, MerkleizationError, Merkleized, Node,
BYTES_PER_CHUNK,
Expand All @@ -8,12 +9,8 @@ use crate::ser::{serialize_composite, Serialize, SerializeError};
use crate::{SimpleSerialize, Sized};
#[cfg(feature = "serde")]
use serde::ser::SerializeSeq;
use std::iter::Enumerate;
#[cfg(feature = "serde")]
use std::marker::PhantomData;
use std::ops::{Deref, Index, IndexMut};
use std::slice::SliceIndex;
use std::{fmt, slice};

/// A homogenous collection of a variable number of values.
#[derive(Clone, Default)]
Expand Down Expand Up @@ -84,7 +81,7 @@ where
write!(
f,
"List<{}, {}>(len={}){:#?}",
std::any::type_name::<T>(),
any::type_name::<T>(),
N,
self.len(),
self.data
Expand All @@ -93,7 +90,7 @@ where
write!(
f,
"List<{}, {}>(len={}){:?}",
std::any::type_name::<T>(),
any::type_name::<T>(),
N,
self.len(),
self.data
Expand Down
30 changes: 21 additions & 9 deletions ssz-rs/src/merkleization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ mod cache;
mod node;
mod proofs;

use crate::lib::*;
use crate::ser::{Serialize, SerializeError};
use sha2::{Digest, Sha256};
use std::cmp::Ordering;
use std::fmt::Debug;
use std::ops::Index;
use thiserror::Error;

pub use cache::Cache as MerkleCache;
pub use node::Node;
Expand All @@ -20,14 +17,29 @@ pub trait Merkleized {
fn hash_tree_root(&mut self) -> Result<Node, MerkleizationError>;
}

#[derive(Error, Debug)]
#[derive(Debug)]
pub enum MerkleizationError {
#[error("failed to serialize value: {0}")]
SerializationError(#[from] SerializeError),
#[error("cannot merkleize data that exceeds the declared limit {0}")]
SerializationError(SerializeError),
InputExceedsLimit(usize),
}

impl From<SerializeError> for MerkleizationError {
fn from(e: SerializeError) -> Self {
MerkleizationError::SerializationError(e)
ralexstokes marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl Display for MerkleizationError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ralexstokes marked this conversation as resolved.
Show resolved Hide resolved
Self::SerializationError(err) => {
write!(f, "failed to serialize value: {err}")
}
Self::InputExceedsLimit(size) => write!(f, "data exceeds the declared limit {size}"),
}
}
}

pub fn pack_bytes(buffer: &mut Vec<u8>) {
let data_len = buffer.len();
if data_len % BYTES_PER_CHUNK != 0 {
Expand Down Expand Up @@ -60,7 +72,7 @@ fn hash_nodes(hasher: &mut Sha256, a: &[u8], b: &[u8], out: &mut [u8]) {
const MAX_MERKLE_TREE_DEPTH: usize = 64;

#[derive(Debug)]
pub struct Context {
struct Context {
zero_hashes: [u8; MAX_MERKLE_TREE_DEPTH * BYTES_PER_CHUNK],
}

Expand Down
5 changes: 1 addition & 4 deletions ssz-rs/src/merkleization/node.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use crate::lib::*;
use crate::prelude::*;
use std::array::TryFromSliceError;
use std::convert::AsRef;
use std::fmt;
use std::ops::{Index, IndexMut};

#[derive(Default, Clone, Copy, PartialEq, Eq, SimpleSerialize)]
pub struct Node(pub(crate) [u8; 32]);
Expand Down
Loading