Skip to main content

miden_core/program/
kernel.rs

1use alloc::vec::Vec;
2
3use miden_crypto::Word;
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7use crate::serde::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
8
9// KERNEL
10// ================================================================================================
11
12/// A list of procedure hashes defining a VM kernel.
13///
14/// The internally-stored list always has a consistent order, regardless of the order of procedure
15/// list used to instantiate a kernel.
16#[derive(Debug, Clone, Default, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
18#[cfg_attr(feature = "serde", serde(transparent))]
19#[cfg_attr(
20    all(feature = "arbitrary", test),
21    miden_test_serde_macros::serde_test(binary_serde(true))
22)]
23pub struct Kernel(Vec<Word>);
24
25impl Kernel {
26    /// The maximum number of procedures which can be exported from a Kernel.
27    pub const MAX_NUM_PROCEDURES: usize = u8::MAX as usize;
28
29    /// Returns a new [Kernel] instantiated with the specified procedure hashes.
30    pub fn new(proc_hashes: &[Word]) -> Result<Self, KernelError> {
31        if proc_hashes.len() > Self::MAX_NUM_PROCEDURES {
32            Err(KernelError::TooManyProcedures(Self::MAX_NUM_PROCEDURES, proc_hashes.len()))
33        } else {
34            let mut hashes = proc_hashes.to_vec();
35            hashes.sort_by_key(|v| v.as_bytes()); // ensure consistent order
36
37            let duplicated = hashes.windows(2).any(|data| data[0] == data[1]);
38
39            if duplicated {
40                Err(KernelError::DuplicatedProcedures)
41            } else {
42                Ok(Self(hashes))
43            }
44        }
45    }
46
47    /// Returns true if this kernel does not contain any procedures.
48    pub fn is_empty(&self) -> bool {
49        self.0.is_empty()
50    }
51
52    /// Returns true if a procedure with the specified hash belongs to this kernel.
53    pub fn contains_proc(&self, proc_hash: Word) -> bool {
54        // Note: we can't use `binary_search()` here because the hashes were sorted using a
55        // different key that the `binary_search` algorithm uses.
56        self.0.contains(&proc_hash)
57    }
58
59    /// Returns a list of procedure hashes contained in this kernel.
60    pub fn proc_hashes(&self) -> &[Word] {
61        &self.0
62    }
63}
64
65// this is required by AIR as public inputs will be serialized with the proof
66impl Serializable for Kernel {
67    fn write_into<W: ByteWriter>(&self, target: &mut W) {
68        // expect is OK here because the number of procedures is enforced by the constructor
69        target.write_u8(self.0.len().try_into().expect("too many kernel procedures"));
70        target.write_many(&self.0)
71    }
72}
73
74impl Deserializable for Kernel {
75    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
76        let len = source.read_u8()? as usize;
77        let kernel = source.read_many_iter::<Word>(len)?.collect::<Result<_, _>>()?;
78        Ok(Self(kernel))
79    }
80}
81
82// KERNEL ERROR
83// ================================================================================================
84
85#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
86pub enum KernelError {
87    #[error("kernel cannot have duplicated procedures")]
88    DuplicatedProcedures,
89    #[error("kernel can have at most {0} procedures, received {1}")]
90    TooManyProcedures(usize, usize),
91}