miden_objects/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#![no_std]

#[macro_use]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

pub mod account;
pub mod asset;
pub mod batch;
pub mod block;
pub mod note;
pub mod transaction;

#[cfg(any(feature = "testing", test))]
pub mod testing;

mod constants;
mod errors;

// RE-EXPORTS
// ================================================================================================

pub use constants::*;
pub use errors::{
    AccountDeltaError, AccountError, AccountIdError, AssetError, AssetVaultError, BlockError,
    ChainMmrError, NoteError, ProvenTransactionError, TransactionInputError,
    TransactionOutputError, TransactionScriptError,
};
pub use miden_crypto::hash::rpo::{Rpo256 as Hasher, RpoDigest as Digest};
pub use vm_core::{Felt, FieldElement, StarkField, Word, EMPTY_WORD, ONE, WORD_SIZE, ZERO};

pub mod assembly {
    pub use assembly::{
        mast, Assembler, AssemblyError, DefaultSourceManager, KernelLibrary, Library,
        LibraryNamespace, LibraryPath, SourceManager, Version,
    };
}

pub mod crypto {
    pub use miden_crypto::{dsa, hash, merkle, rand, utils};
}

pub mod utils {
    use alloc::string::{String, ToString};

    pub use miden_crypto::utils::{bytes_to_hex_string, collections, hex_to_bytes, HexParseError};
    pub use vm_core::utils::*;
    use vm_core::{Felt, StarkField};

    pub mod serde {
        pub use miden_crypto::utils::{
            ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
        };
    }

    pub const fn parse_hex_string_as_word(hex: &str) -> Result<[Felt; 4], &'static str> {
        const fn parse_hex_digit(digit: u8) -> Result<u8, &'static str> {
            match digit {
                b'0'..=b'9' => Ok(digit - b'0'),
                b'A'..=b'F' => Ok(digit - b'A' + 0x0a),
                b'a'..=b'f' => Ok(digit - b'a' + 0x0a),
                _ => Err("Invalid hex character"),
            }
        }
        // Enforce and skip the '0x' prefix.
        let hex_bytes = match hex.as_bytes() {
            [b'0', b'x', rest @ ..] => rest,
            _ => return Err("Hex string must have a \"0x\" prefix"),
        };

        if hex_bytes.len() > 64 {
            return Err("Hex string has more than 64 characters");
        }

        let mut felts = [0u64; 4];
        let mut i = 0;
        while i < hex_bytes.len() {
            let hex_digit = match parse_hex_digit(hex_bytes[i]) {
                // SAFETY: u8 cast to u64 is safe. We cannot use u64::from in const context so we
                // are forced to cast.
                Ok(v) => v as u64,
                Err(e) => return Err(e),
            };

            // This digit's nibble offset within the felt. We need to invert the nibbles per
            // byte for endianess reasons i.e. ABCD -> BADC.
            let inibble = if i % 2 == 0 { (i + 1) % 16 } else { (i - 1) % 16 };

            let value = hex_digit << (inibble * 4);
            felts[i / 2 / 8] += value;

            i += 1;
        }

        // Ensure each felt is within bounds as `Felt::new` silently wraps around.
        // This matches the behaviour of `Digest::try_from(String)`.
        let mut idx = 0;
        while idx < felts.len() {
            if felts[idx] > Felt::MODULUS {
                return Err("Felt overflow");
            }
            idx += 1;
        }

        Ok([
            Felt::new(felts[0]),
            Felt::new(felts[1]),
            Felt::new(felts[2]),
            Felt::new(felts[3]),
        ])
    }

    /// Construct a new `Digest` from a hex value.
    ///
    /// Expects a '0x' prefixed hex string followed by up to 64 hex digits.
    #[macro_export]
    macro_rules! digest {
        ($hex:expr) => {{
            let felts: [$crate::Felt; 4] = match $crate::utils::parse_hex_string_as_word($hex) {
                Ok(v) => v,
                Err(e) => panic!("{}", e),
            };

            $crate::Digest::new(felts)
        }};
    }

    pub fn parse_hex_to_felts(hex: &str) -> Result<[Felt; 4], String> {
        match parse_hex_string_as_word(hex) {
            Ok(felts) => Ok(felts),
            Err(e) => Err(e.to_string()),
        }
    }

    #[cfg(test)]
    mod tests {
        #[rstest::rstest]
        #[case::missing_prefix("1234")]
        #[case::invalid_character("1234567890abcdefg")]
        #[case::too_long("0xx00000000000000000000000000000000000000000000000000000000000000001")]
        #[case::overflow_felt0(
            "0xffffffffffffffff000000000000000000000000000000000000000000000000"
        )]
        #[case::overflow_felt1(
            "0x0000000000000000ffffffffffffffff00000000000000000000000000000000"
        )]
        #[case::overflow_felt2(
            "0x00000000000000000000000000000000ffffffffffffffff0000000000000000"
        )]
        #[case::overflow_felt3(
            "0x000000000000000000000000000000000000000000000000ffffffffffffffff"
        )]
        #[should_panic]
        fn digest_macro_invalid(#[case] bad_input: &str) {
            digest!(bad_input);
        }

        #[rstest::rstest]
        #[case::each_digit("0x1234567890abcdef")]
        #[case::empty("0x")]
        #[case::zero("0x0")]
        #[case::zero_full("0x0000000000000000000000000000000000000000000000000000000000000000")]
        #[case::one_lsb("0x1")]
        #[case::one_msb("0x0000000000000000000000000000000000000000000000000000000000000001")]
        #[case::one_partial("0x0001")]
        #[case::odd("0x123")]
        #[case::even("0x1234")]
        #[case::touch_each_felt(
            "0x00000000000123450000000000067890000000000000abcd00000000000000ef"
        )]
        #[case::unique_felt("0x111111111111111155555555555555559999999999999999cccccccccccccccc")]
        #[case::digits_on_repeat(
            "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
        )]
        fn digest_macro(#[case] input: &str) {
            let uut = digest!(input);

            // Right pad to 64 hex digits (66 including prefix). This is required by the
            // Digest::try_from(String) implementation.
            let padded_input = format!("{input:<66}").replace(" ", "0");
            let expected = crate::Digest::try_from(std::dbg!(padded_input)).unwrap();

            assert_eq!(uut, expected);
        }
    }
}

pub mod vm {
    pub use miden_verifier::ExecutionProof;
    pub use vm_core::{sys_events::SystemEvent, AdviceMap, Program, ProgramInfo};
    pub use vm_processor::{AdviceInputs, RowIndex, StackInputs, StackOutputs};
}