miden_core/
kernel.rs

1use alloc::vec::Vec;
2
3use miden_crypto::hash::rpo::RpoDigest;
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<RpoDigest>);
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: &[RpoDigest]) -> 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: RpoDigest) -> bool {
49        self.0.binary_search(&proc_hash).is_ok()
50    }
51
52    /// Returns a list of procedure hashes contained in this kernel.
53    pub fn proc_hashes(&self) -> &[RpoDigest] {
54        &self.0
55    }
56}
57
58// this is required by AIR as public inputs will be serialized with the proof
59impl Serializable for Kernel {
60    fn write_into<W: ByteWriter>(&self, target: &mut W) {
61        // expect is OK here because the number of procedures is enforced by the constructor
62        target.write_u8(self.0.len().try_into().expect("too many kernel procedures"));
63        target.write_many(&self.0)
64    }
65}
66
67impl Deserializable for Kernel {
68    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
69        let len = source.read_u8()? as usize;
70        let kernel = source.read_many::<RpoDigest>(len)?;
71        Ok(Self(kernel))
72    }
73}