Skip to main content

miden_core/program/
kernel.rs

1use alloc::{string::ToString, vec::Vec};
2
3use miden_crypto::Word;
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    chiplets::hasher,
9    serde::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
10};
11
12// CONSTANTS
13// ================================================================================================
14
15/// Domain tag for the kernel commitment: the registered selector
16/// `(KERNEL_COMMITMENT_DOMAIN_ID << 8) | 1` (see the [`domain`](super::domain) module).
17pub const KERNEL_DOMAIN_TAG: crate::Felt =
18    super::domain::domain_selector(super::domain::KERNEL_COMMITMENT_DOMAIN_ID, 1);
19
20// KERNEL
21// ================================================================================================
22
23/// A list of exported kernel procedure hashes defining a VM kernel.
24///
25/// The internally-stored list always has a consistent order, regardless of the order of procedure
26/// list used to instantiate a descriptor.
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
28#[cfg_attr(feature = "serde", derive(Serialize))]
29#[cfg_attr(feature = "serde", serde(transparent))]
30#[cfg_attr(
31    all(feature = "arbitrary", test),
32    miden_test_serde_macros::serde_test(binary_serde(true))
33)]
34pub struct KernelDescriptor(Vec<Word>);
35
36impl KernelDescriptor {
37    /// The maximum number of procedures which can be exported from a KernelDescriptor.
38    pub const MAX_NUM_PROCEDURES: usize = u8::MAX as usize;
39
40    /// Returns a new [KernelDescriptor] instantiated with the specified procedure hashes.
41    ///
42    /// Hashes are canonicalized into a consistent internal order.
43    ///
44    /// # Errors
45    /// Returns an error if:
46    /// - `proc_hashes` contains duplicates.
47    /// - `proc_hashes.len()` exceeds [`MAX_NUM_PROCEDURES`](Self::MAX_NUM_PROCEDURES).
48    pub fn new(proc_hashes: &[Word]) -> Result<Self, KernelError> {
49        Self::from_hashes(proc_hashes.to_vec())
50    }
51
52    /// Returns a new [KernelDescriptor] from owned procedure hashes.
53    ///
54    /// Hashes are canonicalized into a consistent internal order.
55    ///
56    /// # Errors
57    /// Returns an error if:
58    /// - `hashes` contains duplicates.
59    /// - `hashes.len()` exceeds [`MAX_NUM_PROCEDURES`](Self::MAX_NUM_PROCEDURES).
60    pub fn from_hashes(mut hashes: Vec<Word>) -> Result<Self, KernelError> {
61        if hashes.len() > Self::MAX_NUM_PROCEDURES {
62            return Err(KernelError::TooManyProcedures(Self::MAX_NUM_PROCEDURES, hashes.len()));
63        }
64
65        // Canonical ordering is a separate kernel invariant (not just a dedup side effect), so
66        // we sort first and then validate uniqueness over the canonical representation.
67        hashes.sort_by_key(Word::as_bytes); // ensure consistent order
68        let duplicated = hashes.windows(2).any(|data| data[0] == data[1]);
69
70        if duplicated {
71            Err(KernelError::DuplicatedProcedures)
72        } else {
73            Ok(Self(hashes))
74        }
75    }
76
77    /// Creates a kernel from raw hashes without enforcing constructor invariants.
78    ///
79    /// This is only intended for tests that need intentionally malformed kernels.
80    #[cfg(test)]
81    pub(crate) fn from_hashes_unchecked(hashes: Vec<Word>) -> Self {
82        Self(hashes)
83    }
84
85    /// Returns true if this kernel does not contain any procedures.
86    pub fn is_empty(&self) -> bool {
87        self.0.is_empty()
88    }
89
90    /// Returns true if a procedure with the specified hash belongs to this kernel.
91    ///
92    /// Note: the kernel is constructed from exported kernel procedures only.
93    pub fn contains_proc(&self, proc_hash: Word) -> bool {
94        // Note: we can't use `binary_search()` here because the hashes were sorted using a
95        // different key that the `binary_search` algorithm uses.
96        self.0.contains(&proc_hash)
97    }
98
99    /// Returns a list of procedure hashes contained in this kernel.
100    pub fn proc_hashes(&self) -> &[Word] {
101        &self.0
102    }
103
104    /// Returns the canonical commitment to this kernel: the domain-tagged sequential hash of the
105    /// flattened procedure digests, `hash_elements_in_domain(flatten(procs), KERNEL_DOMAIN_TAG)`.
106    ///
107    /// This is the fixed-size identifier observed by the recursive verifier in place of the raw
108    /// digest list. The encoding is normative:
109    /// - element order is this descriptor's canonical procedure order (fixed at construction);
110    /// - length binding comes from the Sponge2 padding rule (<https://eprint.iacr.org/2024/911>:
111    ///   the first capacity element carries `len % rate` and inputs are zero-padded to a rate
112    ///   multiple), so digest lists of different lengths cannot collide;
113    /// - the empty kernel hashes to the rule's canonical empty-input value.
114    pub fn commitment(&self) -> Word {
115        hasher::hash_elements_in_domain(Word::words_as_elements(&self.0), KERNEL_DOMAIN_TAG)
116    }
117}
118
119// this is required by AIR as public inputs will be serialized with the proof
120impl Serializable for KernelDescriptor {
121    fn write_into<W: ByteWriter>(&self, target: &mut W) {
122        // expect is OK here because the number of procedures is enforced by the constructor
123        target.write_u8(self.0.len().try_into().expect("too many kernel procedures"));
124        target.write_many(&self.0)
125    }
126}
127
128impl Deserializable for KernelDescriptor {
129    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
130        let len = source.read_u8()? as usize;
131        let kernel = source.read_many_iter::<Word>(len)?.collect::<Result<_, _>>()?;
132        Self::from_hashes(kernel).map_err(|err| DeserializationError::InvalidValue(err.to_string()))
133    }
134}
135
136#[cfg(feature = "serde")]
137impl<'de> Deserialize<'de> for KernelDescriptor {
138    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
139    where
140        D: serde::Deserializer<'de>,
141    {
142        let kernel = Vec::<Word>::deserialize(deserializer)?;
143        Self::from_hashes(kernel).map_err(serde::de::Error::custom)
144    }
145}
146
147// KERNEL ERROR
148// ================================================================================================
149
150#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
151pub enum KernelError {
152    #[error("kernel cannot have duplicated procedures")]
153    DuplicatedProcedures,
154    #[error("kernel can have at most {0} procedures, received {1}")]
155    TooManyProcedures(usize, usize),
156}
157
158#[cfg(test)]
159mod tests {
160    use alloc::vec::Vec;
161
162    use super::KernelDescriptor;
163    use crate::{
164        Felt, Word,
165        serde::{ByteWriter, Deserializable, Serializable, SliceReader},
166    };
167
168    #[test]
169    fn empty_kernel_commitment_matches_hash_of_no_elements() {
170        // The empty kernel's commitment must equal the canonical domain-tagged hash of zero
171        // elements, which the recursive verifier mirrors via
172        // `hash_elements_in_domain(ptr, 0, KERNEL_DOMAIN_TAG)`.
173        let empty = KernelDescriptor::default();
174        assert_eq!(
175            empty.commitment(),
176            crate::chiplets::hasher::hash_elements_in_domain(&[], super::KERNEL_DOMAIN_TAG)
177        );
178    }
179
180    #[test]
181    fn kernel_commitment_is_independent_of_procedure_order() {
182        let a: Word = [
183            Felt::new_unchecked(1),
184            Felt::new_unchecked(2),
185            Felt::new_unchecked(3),
186            Felt::new_unchecked(4),
187        ]
188        .into();
189        let b: Word = [
190            Felt::new_unchecked(5),
191            Felt::new_unchecked(6),
192            Felt::new_unchecked(7),
193            Felt::new_unchecked(8),
194        ]
195        .into();
196
197        // The kernel canonicalizes procedure order, so the commitment binds the set of
198        // procedures, not the order in which they were supplied.
199        let in_order = KernelDescriptor::new(&[a, b]).unwrap();
200        let reversed = KernelDescriptor::new(&[b, a]).unwrap();
201        assert_eq!(in_order.commitment(), reversed.commitment());
202    }
203
204    #[test]
205    fn kernel_read_from_rejects_duplicate_procedure_hashes() {
206        let a: Word = [
207            Felt::new_unchecked(1),
208            Felt::new_unchecked(2),
209            Felt::new_unchecked(3),
210            Felt::new_unchecked(4),
211        ]
212        .into();
213        let b: Word = [
214            Felt::new_unchecked(5),
215            Felt::new_unchecked(6),
216            Felt::new_unchecked(7),
217            Felt::new_unchecked(8),
218        ]
219        .into();
220
221        assert!(
222            KernelDescriptor::new(&[a, a]).is_err(),
223            "test precondition: KernelDescriptor::new must reject duplicates"
224        );
225
226        // Manually serialize a KernelDescriptor that contains duplicates. This cannot be
227        // constructed via `KernelDescriptor::new`, but it can be produced via the binary
228        // format.
229        let mut bytes = Vec::new();
230        bytes.write_u8(3);
231        b.write_into(&mut bytes);
232        a.write_into(&mut bytes);
233        a.write_into(&mut bytes);
234
235        let mut reader = SliceReader::new(&bytes);
236        let result = KernelDescriptor::read_from(&mut reader);
237
238        assert!(
239            result.is_err(),
240            "expected KernelDescriptor::read_from to reject duplicate procedure hashes"
241        );
242    }
243
244    #[cfg(feature = "serde")]
245    #[test]
246    fn kernel_serde_deserialisation_rejects_duplicate_procedure_hashes() {
247        let a: Word = [
248            Felt::new_unchecked(1),
249            Felt::new_unchecked(2),
250            Felt::new_unchecked(3),
251            Felt::new_unchecked(4),
252        ]
253        .into();
254
255        assert!(
256            KernelDescriptor::new(&[a, a]).is_err(),
257            "test precondition: KernelDescriptor::new must reject duplicates"
258        );
259
260        // KernelDescriptor deserialization should reject duplicates.
261        let json = serde_json::to_string(&vec![a, a]).unwrap();
262        let result: Result<KernelDescriptor, _> = serde_json::from_str(&json);
263        assert!(
264            result.is_err(),
265            "expected serde deserialization to reject duplicate procedure hashes"
266        );
267    }
268
269    #[cfg(feature = "serde")]
270    #[test]
271    fn kernel_serde_deserialisation_rejects_too_many_procedure_hashes() {
272        let proc_hashes: Vec<Word> = (0u64..=255)
273            .map(|n| {
274                [
275                    Felt::new_unchecked(n),
276                    Felt::new_unchecked(n + 1),
277                    Felt::new_unchecked(n + 2),
278                    Felt::new_unchecked(n + 3),
279                ]
280                .into()
281            })
282            .collect();
283
284        let json = serde_json::to_string(&proc_hashes).unwrap();
285        let result: Result<KernelDescriptor, _> = serde_json::from_str(&json);
286        assert!(
287            result.is_err(),
288            "expected serde deserialization to reject more than MAX_NUM_PROCEDURES hashes"
289        );
290    }
291}