miden_stdlib_sys/intrinsics/
crypto.rs

1//! Cryptographic intrinsics for the Miden VM.
2//!
3//! This module provides Rust bindings for cryptographic operations available in the Miden VM.
4#![allow(warnings)]
5
6use crate::intrinsics::{Felt, Word};
7
8/// A cryptographic digest representing a 256-bit hash value.
9///
10/// This is a wrapper around `Word` which contains 4 field elements.
11#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
12#[repr(transparent)]
13pub struct Digest {
14    pub inner: Word,
15}
16
17impl Digest {
18    /// Creates a new `Digest` from a `[Felt; 4]` array.
19    #[inline]
20    pub fn new(felts: [Felt; 4]) -> Self {
21        Self {
22            inner: Word::from(felts),
23        }
24    }
25
26    /// Creates a new `Digest` from a `Word`.
27    #[inline]
28    pub const fn from_word(word: Word) -> Self {
29        Self { inner: word }
30    }
31}
32
33impl From<Word> for Digest {
34    #[inline]
35    fn from(word: Word) -> Self {
36        Self::from_word(word)
37    }
38}
39
40impl From<Digest> for Word {
41    #[inline]
42    fn from(digest: Digest) -> Self {
43        digest.inner
44    }
45}
46
47impl From<[Felt; 4]> for Digest {
48    #[inline]
49    fn from(felts: [Felt; 4]) -> Self {
50        Self::new(felts)
51    }
52}
53
54impl From<Digest> for [Felt; 4] {
55    #[inline]
56    fn from(digest: Digest) -> Self {
57        digest.inner.into()
58    }
59}
60
61#[link(wasm_import_module = "miden:core-intrinsics/intrinsics-crypto@1.0.0")]
62extern "C" {
63    /// Computes the hash of two digests using the Rescue Prime Optimized (RPO)
64    /// permutation in 2-to-1 mode.
65    ///
66    /// This is the `hmerge` instruction in the Miden VM.
67    ///
68    /// Input: Pointer to an array of two digests (8 field elements total)
69    /// Output: One digest (4 field elements) written to the result pointer
70    #[link_name = "hmerge"]
71    fn extern_hmerge(
72        // Pointer to array of two digests
73        digests_ptr: *const Felt,
74        // Result pointer
75        result_ptr: *mut Felt,
76    );
77}
78
79/// Computes the hash of two digests using the Rescue Prime Optimized (RPO)
80/// permutation in 2-to-1 mode.
81///
82/// This directly maps to the `hmerge` VM instruction.
83///
84/// # Arguments
85/// * `digests` - An array of two digests to be merged. The function internally
86///   reorders them as required by the VM instruction (from [A, B] to [B, A] on the stack).
87#[inline]
88pub fn merge(digests: [Digest; 2]) -> Digest {
89    unsafe {
90        let mut ret_area = ::core::mem::MaybeUninit::<Word>::uninit();
91        let result_ptr = ret_area.as_mut_ptr().addr() as u32;
92
93        let digests_ptr = digests.as_ptr().addr() as u32;
94        extern_hmerge(digests_ptr as *const Felt, result_ptr as *mut Felt);
95
96        Digest::from_word(ret_area.assume_init())
97    }
98}