miden_core/
kernel.rs

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