miden-protocol 0.16.0-alpha.4

Core components of the Miden protocol
Documentation
use alloc::sync::Arc;

use crate::assembly::Library;
use crate::assembly::mast::MastForest;
use crate::utils::sync::LazyLock;
use crate::vm::Package;

// CONSTANTS
// ================================================================================================

const PROTOCOL_PACKAGE_BYTES: &[u8] =
    include_bytes!(concat!(env!("OUT_DIR"), "/assets/miden-protocol.masp"));

static PROTOCOL_PACKAGE: LazyLock<Arc<Package>> = LazyLock::new(|| {
    Arc::new(
        // These bytes are produced by this crate's build script and embedded in the binary.
        Package::read_from_bytes_trusted(PROTOCOL_PACKAGE_BYTES)
            .expect("protocol lib masp should be well-formed"),
    )
});

// PROTOCOL LIBRARY
// ================================================================================================

#[derive(Clone)]
pub struct ProtocolLib(Arc<Package>);

impl ProtocolLib {
    /// Returns the underlying [`Arc<Package>`]
    pub fn package(&self) -> Arc<Package> {
        self.0.clone()
    }

    /// Returns a reference to the [`MastForest`] of the inner [`Library`].
    pub fn mast_forest(&self) -> &Arc<MastForest> {
        self.0.mast_forest()
    }
}

impl AsRef<Library> for ProtocolLib {
    fn as_ref(&self) -> &Library {
        self.0.as_ref()
    }
}

impl From<ProtocolLib> for Library {
    fn from(value: ProtocolLib) -> Self {
        Arc::unwrap_or_clone(value.0)
    }
}

impl Default for ProtocolLib {
    fn default() -> Self {
        ProtocolLib(PROTOCOL_PACKAGE.clone())
    }
}

// TESTS
// ================================================================================================

// NOTE: Most protocol-related tests can be found in miden-testing.
#[cfg(all(test, feature = "std"))]
mod tests {
    use super::ProtocolLib;
    use crate::assembly::Path;

    #[test]
    fn test_compile() {
        let path = Path::new("::miden::protocol::active_account::get_id");
        let miden = ProtocolLib::default();
        let exists = miden.0.module_infos().any(|module| {
            module
                .procedures()
                .any(|(_, proc)| module.path().join(&proc.name).as_path() == path)
        });

        assert!(exists);
    }
}