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))]
22#[cfg_attr(
23    all(feature = "arbitrary", test),
24    miden_test_serde_macros::serde_test(winter_serde(true))
25)]
26pub struct Kernel(Vec<Word>);
27
28impl Kernel {
29    /// The maximum number of procedures which can be exported from a Kernel.
30    pub const MAX_NUM_PROCEDURES: usize = u8::MAX as usize;
31
32    /// Returns a new [Kernel] instantiated with the specified procedure hashes.
33    pub fn new(proc_hashes: &[Word]) -> Result<Self, KernelError> {
34        if proc_hashes.len() > Self::MAX_NUM_PROCEDURES {
35            Err(KernelError::TooManyProcedures(Self::MAX_NUM_PROCEDURES, proc_hashes.len()))
36        } else {
37            let mut hashes = proc_hashes.to_vec();
38            hashes.sort_by_key(|v| v.as_bytes()); // ensure consistent order
39
40            let duplicated = hashes.windows(2).any(|data| data[0] == data[1]);
41
42            if duplicated {
43                Err(KernelError::DuplicatedProcedures)
44            } else {
45                Ok(Self(hashes))
46            }
47        }
48    }
49
50    /// Returns true if this kernel does not contain any procedures.
51    pub fn is_empty(&self) -> bool {
52        self.0.is_empty()
53    }
54
55    /// Returns true if a procedure with the specified hash belongs to this kernel.
56    pub fn contains_proc(&self, proc_hash: Word) -> bool {
57        // Note: we can't use `binary_search()` here because the hashes were sorted using a
58        // different key that the `binary_search` algorithm uses.
59        self.0.contains(&proc_hash)
60    }
61
62    /// Returns a list of procedure hashes contained in this kernel.
63    pub fn proc_hashes(&self) -> &[Word] {
64        &self.0
65    }
66}
67
68// this is required by AIR as public inputs will be serialized with the proof
69impl Serializable for Kernel {
70    fn write_into<W: ByteWriter>(&self, target: &mut W) {
71        // expect is OK here because the number of procedures is enforced by the constructor
72        target.write_u8(self.0.len().try_into().expect("too many kernel procedures"));
73        target.write_many(&self.0)
74    }
75}
76
77impl Deserializable for Kernel {
78    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
79        let len = source.read_u8()? as usize;
80        let kernel = source.read_many::<Word>(len)?;
81        Ok(Self(kernel))
82    }
83}