Skip to main content

miden_mast_package/package/
section.rs

1#[cfg(feature = "arbitrary")]
2use alloc::vec;
3use alloc::{
4    borrow::{Cow, ToOwned},
5    format,
6    string::{String, ToString},
7};
8use core::{fmt, str::FromStr};
9
10use miden_assembly_syntax::DisplayHex;
11use miden_core::serde::{
12    ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
13};
14#[cfg(feature = "arbitrary")]
15use proptest::prelude::*;
16
17/// A unique identifier for optional sections of the Miden package format
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[repr(transparent)]
20#[cfg_attr(
21    all(feature = "arbitrary", test),
22    miden_test_serialization_macros::serialization_test
23)]
24pub struct SectionId(Cow<'static, str>);
25
26impl SectionId {
27    /// The section containing a serialized [`crate::debug_info::PackageDebugInfo`] struct
28    pub const DEBUG_INFO: Self = Self(Cow::Borrowed("debug_info"));
29    /// This section provides the encoded metadata for a compiled account component
30    ///
31    /// Currently, this corresponds to the serialized representation of
32    /// `miden-protocol::account::AccountComponentMetadata`, i.e. name, descrioption, storage, that
33    /// is associated with this package.
34    pub const ACCOUNT_COMPONENT_METADATA: Self = Self(Cow::Borrowed("account_component_metadata"));
35    /// This section contains provenance metadata for packages assembled from project sources.
36    pub const PROJECT_SOURCE_PROVENANCE: Self = Self(Cow::Borrowed("project_source_provenance"));
37    /// This section contains the serialized kernel package linked against by an executable package.
38    pub const KERNEL: Self = Self(Cow::Borrowed("kernel"));
39    /// This section contains a Wasm module with custom event handlers plus its manifest; see
40    /// [`crate::EventHandlerSection`].
41    pub const EVENT_HANDLERS: Self = Self(Cow::Borrowed("event_handlers"));
42
43    /// Construct a user-defined (i.e. "custom") section identifier
44    ///
45    /// Section identifiers must be either an ASCII alphanumeric, or one of the following
46    /// characters: `.`, `_`, `-`. Additionally, the identifier must start with an ASCII alphabetic
47    /// character or `_`.
48    pub fn custom(name: impl AsRef<str>) -> Result<Self, InvalidSectionIdError> {
49        let name = name.as_ref();
50        if !name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
51            return Err(InvalidSectionIdError::InvalidStart);
52        }
53        if name.contains(|c: char| !c.is_ascii_alphanumeric() && !matches!(c, '.' | '_' | '-')) {
54            return Err(InvalidSectionIdError::InvalidCharacter);
55        }
56        Ok(Self(name.to_string().into()))
57    }
58
59    /// Get this section identifier as a string
60    #[inline]
61    pub fn as_str(&self) -> &str {
62        self.0.as_ref()
63    }
64
65    /// Returns true if this section contains package debug metadata.
66    pub fn is_debug(&self) -> bool {
67        self == &Self::DEBUG_INFO
68    }
69}
70
71#[derive(Debug, thiserror::Error)]
72pub enum InvalidSectionIdError {
73    #[error("invalid section id: cannot be empty")]
74    Empty,
75    #[error(
76        "invalid section id: contains invalid characters, only the set [a-z0-9._-] are allowed"
77    )]
78    InvalidCharacter,
79    #[error("invalid section id: must start with a character in the set [a-z_]")]
80    InvalidStart,
81}
82
83impl FromStr for SectionId {
84    type Err = InvalidSectionIdError;
85    fn from_str(s: &str) -> Result<Self, Self::Err> {
86        match s {
87            "debug_info" => Ok(Self::DEBUG_INFO),
88            "account_component_metadata" => Ok(Self::ACCOUNT_COMPONENT_METADATA),
89            "project_source_provenance" => Ok(Self::PROJECT_SOURCE_PROVENANCE),
90            "kernel" => Ok(Self::KERNEL),
91            "event_handlers" => Ok(Self::EVENT_HANDLERS),
92            custom => Self::custom(custom),
93        }
94    }
95}
96
97impl fmt::Display for SectionId {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str(self.as_str())
100    }
101}
102
103impl Serializable for SectionId {
104    fn write_into<W: ByteWriter>(&self, target: &mut W) {
105        self.as_str().write_into(target);
106    }
107}
108
109impl Deserializable for SectionId {
110    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
111        String::read_from(source)?
112            .parse()
113            .map_err(|err| DeserializationError::InvalidValue(format!("invalid section id: {err}")))
114    }
115}
116
117#[derive(Clone, PartialEq, Eq)]
118#[cfg_attr(
119    all(feature = "arbitrary", test),
120    miden_test_serialization_macros::serialization_test
121)]
122pub struct Section {
123    pub id: SectionId,
124    pub data: Cow<'static, [u8]>,
125}
126
127impl fmt::Debug for Section {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        let verbose = f.alternate();
130        let mut builder = f.debug_struct("Section");
131        builder.field("id", &format_args!("{}", self.id));
132        if verbose {
133            builder.field("data", &format_args!("{}", DisplayHex(&self.data))).finish()
134        } else {
135            builder.field("data", &format_args!("{} bytes", self.data.len())).finish()
136        }
137    }
138}
139
140impl Section {
141    pub fn new<B>(id: SectionId, data: B) -> Self
142    where
143        B: Into<Cow<'static, [u8]>>,
144    {
145        Self { id, data: data.into() }
146    }
147
148    /// Returns true if this section is empty, i.e. has no data
149    pub fn is_empty(&self) -> bool {
150        self.data.is_empty()
151    }
152
153    /// Returns the size in bytes of this section's data
154    pub fn len(&self) -> usize {
155        self.data.len()
156    }
157}
158
159#[cfg(all(test, feature = "arbitrary"))]
160mod section_arbitrary {
161    use proptest::prelude::*;
162
163    use super::Section;
164    use crate::package::section::SectionId;
165
166    impl Arbitrary for Section {
167        type Parameters = ();
168        type Strategy = BoxedStrategy<Self>;
169
170        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
171            // The id round-trips through its string form (its own roundtrip test covers that);
172            // the data payload is any-valid bytes.
173            (any::<SectionId>(), proptest::collection::vec(any::<u8>(), 0..=16))
174                .prop_map(|(id, data)| Self::new(id, data))
175                .boxed()
176        }
177    }
178}
179
180impl Serializable for Section {
181    fn write_into<W: ByteWriter>(&self, target: &mut W) {
182        let id = self.id.as_str();
183        target.write_usize(id.len());
184        target.write_bytes(id.as_bytes());
185        target.write_usize(self.len());
186        target.write_bytes(&self.data);
187    }
188}
189
190impl Deserializable for Section {
191    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
192        let id_len = source.read_usize()?;
193        let id_bytes = source.read_slice(id_len)?;
194        let id_str = core::str::from_utf8(id_bytes).map_err(|err| {
195            DeserializationError::InvalidValue(format!("invalid utf-8 in section name: {err}"))
196        })?;
197        let id = id_str.parse::<SectionId>().map_err(|err| {
198            DeserializationError::InvalidValue(format!("invalid section id {id_str:?}: {err}"))
199        })?;
200
201        let len = source.read_usize()?;
202        let bytes = source.read_slice(len)?;
203        Ok(Section { id, data: Cow::Owned(bytes.to_owned()) })
204    }
205}
206
207#[cfg(feature = "arbitrary")]
208impl Arbitrary for SectionId {
209    type Parameters = ();
210    type Strategy = BoxedStrategy<Self>;
211
212    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
213        use alloc::string::String;
214
215        let builtins = proptest::sample::select(vec![
216            Self::DEBUG_INFO,
217            Self::ACCOUNT_COMPONENT_METADATA,
218            Self::PROJECT_SOURCE_PROVENANCE,
219            Self::KERNEL,
220            Self::EVENT_HANDLERS,
221        ]);
222
223        let custom = (
224            proptest::prop_oneof![
225                proptest::char::range('a', 'z'),
226                proptest::char::range('A', 'Z'),
227                Just('_'),
228            ],
229            proptest::collection::vec(
230                proptest::prop_oneof![
231                    proptest::char::range('a', 'z'),
232                    proptest::char::range('A', 'Z'),
233                    proptest::char::range('0', '9'),
234                    Just('.'),
235                    Just('_'),
236                    Just('-'),
237                ],
238                0..31,
239            ),
240        )
241            .prop_map(|(first, rest)| {
242                let mut name = String::with_capacity(rest.len() + 1);
243                name.push(first);
244                name.extend(rest);
245                Self::custom(name).expect("generated custom section ids are valid")
246            });
247
248        proptest::prop_oneof![builtins, custom].boxed()
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use alloc::vec::Vec;
255
256    use miden_core::serde::{ByteWriter, Deserializable, Serializable, SliceReader};
257
258    use super::*;
259
260    fn section_bytes_with_id(id: &str) -> Vec<u8> {
261        let mut buf = Vec::new();
262        buf.write_usize(id.len());
263        buf.write_bytes(id.as_bytes());
264        buf.write_usize(0);
265        buf
266    }
267
268    #[test]
269    fn deserialize_rejects_invalid_section_id() {
270        for bad_id in ["", "1bad", "-bad", "bad id", "../etc"] {
271            let bytes = section_bytes_with_id(bad_id);
272            let mut reader = SliceReader::new(&bytes);
273            assert!(Section::read_from(&mut reader).is_err(), "expected error for {bad_id:?}",);
274        }
275    }
276
277    #[test]
278    fn deserialize_accepts_valid_section_id() {
279        let section = Section {
280            id: SectionId::custom("my_section").unwrap(),
281            data: Cow::Borrowed(&[]),
282        };
283        let bytes = section.to_bytes();
284        let mut reader = SliceReader::new(&bytes);
285        let result = Section::read_from(&mut reader);
286        assert!(result.is_ok());
287        assert_eq!(result.unwrap().id, section.id);
288    }
289}