miden_core/
kernel.rs

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