Skip to content

Commit

Permalink
ergotree_ir no_std
Browse files Browse the repository at this point in the history
  • Loading branch information
SethDusek committed Nov 15, 2024
1 parent 27b8884 commit e5dd219
Show file tree
Hide file tree
Showing 133 changed files with 642 additions and 256 deletions.
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ edition = "2021"
sigma-util = { version = "^0.18.0", path = "./sigma-util" }
sigma-ser = { version = "^0.19.0", path = "./sigma-ser", default-features = false }
ergotree-ir = { version = "^0.28.0", path = "./ergotree-ir" }
ergo-chain-types = { version = "^0.15.0", path = "./ergo-chain-types" }
ergo-chain-types = { version = "^0.15.0", path = "./ergo-chain-types", default-features = false }
sigma-test-util = { version = "^0.3.0", path = "./sigma-test-util" }
ergoscript-compiler = { version = "^0.24.0", path = "./ergoscript-compiler" }
ergotree-interpreter = { version = "^0.28.0", path = "./ergotree-interpreter" }
Expand Down Expand Up @@ -60,10 +60,10 @@ bitvec = { version = "1.0.1", default-features = false, features = ["alloc"] }
blake2 = { version = "0.10.6", default-features = false }
sha2 = { version = "0.10", default-features = false }
num-traits = { version = "0.2.14", default-features = false }
num-integer = "0.1.44"
num-integer = { version = "0.1.44", default-features = false }
num-bigint = { version = "0.4.0", default-features = false }
lazy_static = "1.4"
bs58 = "0.4.0"
lazy_static = { version = "1.4", features = ["spin_no_std"] } # TODO: add no_std feature, so spin_no_std is only enabled if std is not available
bs58 = { version = "0.4.0", default-features = false, features = ["alloc"] }
base16 = { version = "0.2.1", default-features = false, features = ["alloc"] }
base64 = { version = "0.13.0", default-features = false, features = ["alloc"] }
indexmap = { version = "2.6.0", default-features = false } #TODO: enable std conditionally
Expand Down
6 changes: 2 additions & 4 deletions ergo-chain-types/src/peer_addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@ use std::{

use derive_more::FromStr;
use derive_more::{Display, From, Into};
use serde::{Deserialize, Serialize};
use sigma_ser::{ScorexSerializable, ScorexSerializationError};
use url::Url;

/// Peer address
#[derive(
PartialEq, Eq, Debug, Copy, Clone, From, Into, Hash, Display, FromStr, Deserialize, Serialize,
)]
#[derive(PartialEq, Eq, Debug, Copy, Clone, From, Into, Hash, Display, FromStr)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
pub struct PeerAddr(pub SocketAddr);

impl PeerAddr {
Expand Down
2 changes: 1 addition & 1 deletion ergotree-interpreter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ proptest = { workspace = true, optional = true }
ergo_avltree_rust = "0.1.0"
gf2_192 = { version = "^0.28.0", path = "../gf2_192" }
miette = { workspace = true }
hashbrown = "0.14.3"
hashbrown = { workspace = true }

[features]
default = ["json"]
Expand Down
15 changes: 9 additions & 6 deletions ergotree-ir/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,17 @@ serde_json = { workspace = true, optional = true }
serde_with = { workspace = true, optional = true }
bnum = { version = "0.12.0", features = ["numtraits"] }
impl-trait-for-tuples = "0.2.0"
strum = "0.21"
strum_macros = "0.21"
miette = { workspace = true }

strum = { version = "0.26.2", default-features = false, features = ["derive"] }
strum_macros = { version = "0.26.4", default-features = false }
miette = { workspace = true, optional = true }
hashbrown = { workspace = true }
core2 = { workspace = true }
foldhash = { version = "0.1.3", default-features = false }
[features]
default = ["json"]
default = ["json", "std"]
arbitrary = ["proptest", "proptest-derive", "ergo-chain-types/arbitrary"]
json = ["serde", "serde_json", "serde_with", "bounded-vec/serde"]
json = ["serde", "serde_json", "serde_with", "bounded-vec/serde", "std", "ergo-chain-types/json"]
std = ["core2/std", "dep:miette", "ergo-chain-types/std", "sigma-ser/std"]

[dev-dependencies]
sigma-test-util = { workspace = true }
Expand Down
1 change: 1 addition & 0 deletions ergotree-ir/src/base16_str.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Trait for base16-encoded serialized bytes
use crate::serialization::SigmaSerializationError;
use alloc::string::String;

/// Encodes serialized bytes as Base16
pub trait Base16Str {
Expand Down
5 changes: 4 additions & 1 deletion ergotree-ir/src/bigint256.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! 256-bit signed integer type
use std::ops::{Div, Mul, Neg, Rem};
use alloc::string::String;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::ops::{Div, Mul, Neg, Rem};

use bnum::cast::As;
use bnum::types::I256;
Expand Down
3 changes: 3 additions & 0 deletions ergotree-ir/src/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ pub mod ergo_box;
pub mod json;
pub mod token;
pub mod tx_id;

pub(self) type IndexMap<K, V> = indexmap::IndexMap<K, V, foldhash::fast::RandomState>;
pub(self) type IndexSet<T> = indexmap::IndexSet<T, foldhash::fast::RandomState>;
12 changes: 10 additions & 2 deletions ergotree-ir/src/chain/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,18 @@ use crate::sigma_protocol::sigma_boolean::SigmaProofOfKnowledgeTree;
use crate::sigma_protocol::sigma_boolean::SigmaProp;
use crate::source_span::Spanned;
use crate::types::stype::SType;

use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;

use ergo_chain_types::EcPoint;

use core::convert::{TryFrom, TryInto};
use sigma_util::hash::blake2b256_hash;
use sigma_util::AsVecU8;
use std::convert::{TryFrom, TryInto};
use std::sync::Arc;
use thiserror::Error;

/**
Expand Down Expand Up @@ -585,8 +591,10 @@ pub(crate) mod arbitrary {
mod tests {

use super::*;

use proptest::prelude::*;

#[cfg(feature = "std")]
proptest! {

#[test]
Expand Down
21 changes: 13 additions & 8 deletions ergotree-ir/src/chain/context_extension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ use crate::serialization::sigma_byte_writer::SigmaByteWrite;
use crate::serialization::SigmaParsingError;
use crate::serialization::SigmaSerializable;
use crate::serialization::SigmaSerializeResult;
use indexmap::IndexMap;
use std::convert::TryFrom;
use std::fmt;
use alloc::string::String;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::fmt;
use core::hash::Hasher;
use thiserror::Error;

use super::IndexMap;

/// User-defined variables to be put into context
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ContextExtension {
Expand All @@ -21,7 +25,7 @@ impl ContextExtension {
/// Returns an empty ContextExtension
pub fn empty() -> Self {
Self {
values: IndexMap::new(),
values: IndexMap::with_hasher(Default::default()),
}
}
}
Expand All @@ -45,7 +49,8 @@ impl SigmaSerializable for ContextExtension {

fn sigma_parse<R: SigmaByteRead>(r: &mut R) -> Result<Self, SigmaParsingError> {
let values_count = r.get_u8()?;
let mut values: IndexMap<u8, Constant> = IndexMap::with_capacity(values_count as usize);
let mut values: IndexMap<u8, Constant> =
IndexMap::with_capacity_and_hasher(values_count as usize, Default::default());
for _ in 0..values_count {
let idx = r.get_u8()?;
values.insert(idx, Constant::sigma_parse(r)?);
Expand All @@ -60,11 +65,11 @@ impl SigmaSerializable for ContextExtension {
pub struct ConstantParsingError(pub String);

// for JSON encoding in ergo-lib
impl TryFrom<IndexMap<String, String>> for ContextExtension {
impl<H: Hasher> TryFrom<indexmap::IndexMap<String, String, H>> for ContextExtension {
type Error = ConstantParsingError;
fn try_from(values_str: IndexMap<String, String>) -> Result<Self, Self::Error> {
fn try_from(values_str: indexmap::IndexMap<String, String, H>) -> Result<Self, Self::Error> {
let values = values_str.iter().try_fold(
IndexMap::with_capacity(values_str.len()),
IndexMap::with_capacity_and_hasher(values_str.len(), Default::default()),
|mut acc, pair| {
let idx: u8 = pair.0.parse().map_err(|_| {
ConstantParsingError(format!("cannot parse index from {0:?}", pair.0))
Expand Down
11 changes: 7 additions & 4 deletions ergotree-ir/src/chain/ergo_box.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,19 @@ use crate::serialization::SigmaSerializable;
use crate::serialization::SigmaSerializationError;
use crate::serialization::SigmaSerializeResult;

use alloc::string::ToString;
use alloc::vec::Vec;
pub use box_id::*;
use ergo_chain_types::Digest32;
pub use register::*;

use super::IndexSet;
use bounded_vec::BoundedVec;
use indexmap::IndexSet;
use core::convert::TryFrom;
use sigma_util::hash::blake2b256_hash;
use sigma_util::AsVecI8;
use std::convert::TryFrom;

use std::convert::TryInto;
use core::convert::TryInto;

use self::box_value::BoxValue;

Expand Down Expand Up @@ -403,7 +405,7 @@ pub mod arbitrary {
pub creation_height: BoxedStrategy<u32>,
pub registers: BoxedStrategy<NonMandatoryRegisters>,
}
impl std::default::Default for ArbBoxParameters {
impl core::default::Default for ArbBoxParameters {
fn default() -> Self {
Self {
value_range: ArbBoxValueRange::default(),
Expand Down Expand Up @@ -482,6 +484,7 @@ mod tests {
use super::*;
use crate::chain::token::arbitrary::ArbTokenIdParam;
use crate::serialization::sigma_serialize_roundtrip;

use proptest::collection::SizeRange;
use proptest::prelude::*;
use sigma_test_util::force_any_val;
Expand Down
9 changes: 6 additions & 3 deletions ergotree-ir/src/chain/ergo_box/box_id.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Box id type
use std::convert::TryFrom;
use core::convert::TryFrom;

use crate::serialization::SigmaSerializeResult;
use alloc::string::String;
use alloc::vec::Vec;
use sigma_ser::ScorexSerializable;

use crate::serialization::{
Expand Down Expand Up @@ -56,8 +58,8 @@ impl From<BoxId> for Vec<i8> {
}
}

impl std::fmt::Display for BoxId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for BoxId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
Expand All @@ -78,6 +80,7 @@ impl SigmaSerializable for BoxId {
mod tests {
use super::*;
use crate::serialization::sigma_serialize_roundtrip;

use proptest::prelude::*;

proptest! {
Expand Down
11 changes: 7 additions & 4 deletions ergotree-ir/src/chain/ergo_box/box_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use crate::serialization::SigmaSerializeResult;
use crate::serialization::{
sigma_byte_reader::SigmaByteRead, SigmaParsingError, SigmaSerializable,
};

use core::convert::TryFrom;
use derive_more::FromStr;
use std::convert::TryFrom;
use thiserror::Error;

#[cfg(not(feature = "json"))]
Expand Down Expand Up @@ -114,7 +115,7 @@ impl BoxValue {
}

impl PartialOrd for BoxValue {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
self.0.partial_cmp(other.as_u64())
}
}
Expand Down Expand Up @@ -211,9 +212,9 @@ pub fn checked_sum<I: Iterator<Item = BoxValue>>(mut iter: I) -> Result<BoxValue
/// Arbitrary
#[cfg(feature = "arbitrary")]
pub mod arbitrary {
use core::ops::Range;
use derive_more::{From, Into};
use proptest::{arbitrary::Arbitrary, prelude::*};
use std::ops::Range;

use super::*;

Expand All @@ -240,9 +241,11 @@ pub mod arbitrary {
#[allow(clippy::unwrap_used)]
#[cfg(test)]
pub mod tests {
use std::convert::TryInto;
use core::convert::TryInto;

use super::*;
use alloc::vec;
use alloc::vec::Vec;
use proptest::{collection::vec, prelude::*};

extern crate derive_more;
Expand Down
34 changes: 32 additions & 2 deletions ergotree-ir/src/chain/ergo_box/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ use crate::serialization::SigmaParsingError;
use crate::serialization::SigmaSerializable;
use crate::serialization::SigmaSerializationError;
use crate::serialization::SigmaSerializeResult;

use alloc::string::ToString;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::convert::TryInto;
use ergo_chain_types::Base16EncodedBytes;
use std::convert::TryInto;
use std::{collections::HashMap, convert::TryFrom};
use hashbrown::HashMap;
use thiserror::Error;

mod id;
Expand Down Expand Up @@ -217,6 +222,31 @@ impl TryFrom<HashMap<NonMandatoryRegisterId, RegisterValue>> for NonMandatoryReg
}
}

#[cfg(feature = "std")]
impl TryFrom<std::collections::HashMap<NonMandatoryRegisterId, RegisterValue>>
for NonMandatoryRegisters
{
type Error = NonMandatoryRegistersError;
fn try_from(
reg_map: std::collections::HashMap<NonMandatoryRegisterId, RegisterValue>,
) -> Result<Self, Self::Error> {
let regs_num = reg_map.len();
if regs_num > NonMandatoryRegisters::MAX_SIZE {
Err(NonMandatoryRegistersError::InvalidSize(regs_num))
} else {
let mut res: Vec<RegisterValue> = vec![];
NonMandatoryRegisterId::REG_IDS
.iter()
.take(regs_num)
.try_for_each(|reg_id| match reg_map.get(reg_id) {
Some(v) => Ok(res.push(v.clone())),
None => Err(NonMandatoryRegistersError::NonDenselyPacked(*reg_id as u8)),
})?;
Ok(NonMandatoryRegisters(res))
}
}
}

#[cfg(feature = "json")]
impl TryFrom<HashMap<NonMandatoryRegisterId, crate::chain::json::ergo_box::ConstantHolder>>
for NonMandatoryRegisters
Expand Down
5 changes: 3 additions & 2 deletions ergotree-ir/src/chain/ergo_box/register/id.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::fmt::Display;
use core::fmt::Display;

use alloc::{format, string::String};
use derive_more::From;
use thiserror::Error;

Expand Down Expand Up @@ -66,7 +67,7 @@ impl From<RegisterId> for u8 {
}

impl Display for RegisterId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
RegisterId::MandatoryRegisterId(id) => write!(f, "{}", id),
RegisterId::NonMandatoryRegisterId(id) => write!(f, "{}", id),
Expand Down
4 changes: 4 additions & 0 deletions ergotree-ir/src/chain/ergo_box/register/value.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@

use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use derive_more::From;
use thiserror::Error;

Expand Down
Loading

0 comments on commit e5dd219

Please sign in to comment.