Skip to main content

miden_protocol/note/
nullifier.rs

1use core::fmt::{Debug, Display, Formatter};
2
3use miden_core::WORD_SIZE;
4use miden_crypto::WordError;
5use miden_crypto_derive::WordWrapper;
6
7use super::{
8    ByteReader,
9    ByteWriter,
10    Deserializable,
11    DeserializationError,
12    Felt,
13    Hasher,
14    Serializable,
15    Word,
16    ZERO,
17};
18use crate::note::{NoteDetails, NoteMetadata, NoteScriptRoot};
19
20// CONSTANTS
21// ================================================================================================
22
23const NULLIFIER_PREFIX_SHIFT: u8 = 48;
24
25// NULLIFIER
26// ================================================================================================
27
28/// A note's nullifier.
29///
30/// A note's nullifier is computed as:
31///
32/// > `hash(SERIAL_NUM, SCRIPT_ROOT, STORAGE_COMMITMENT, ASSET_COMMITMENT, METADATA,
33/// > ATTACHMENTS_COMMITMENT)`.
34///
35/// This achieves the following properties:
36/// - Every note can be reduced to a single unique nullifier.
37/// - We cannot derive a note's ID from its nullifier, or a note's nullifier from its ID.
38/// - To compute the nullifier we must know all components of the note: serial_num, script_root,
39///   storage_commitment, asset_commitment, metadata and attachments_commitment.
40#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, WordWrapper)]
41pub struct Nullifier(Word);
42
43impl Nullifier {
44    /// Returns a new note [Nullifier] instantiated from the provided note components.
45    pub fn new(
46        script_root: NoteScriptRoot,
47        storage_commitment: Word,
48        asset_commitment: Word,
49        serial_num: Word,
50        metadata_word: Word,
51        attachments_commitment: Word,
52    ) -> Self {
53        let mut elements = [ZERO; 6 * WORD_SIZE];
54        elements[..4].copy_from_slice(serial_num.as_elements());
55        elements[4..8].copy_from_slice(script_root.as_elements());
56        elements[8..12].copy_from_slice(storage_commitment.as_elements());
57        elements[12..16].copy_from_slice(asset_commitment.as_elements());
58        elements[16..20].copy_from_slice(metadata_word.as_elements());
59        elements[20..24].copy_from_slice(attachments_commitment.as_elements());
60        Self(Hasher::hash_elements(&elements))
61    }
62
63    /// Returns a new note [Nullifier] instantiated from the provided note details and metadata.
64    pub fn from_details_and_metadata(details: &NoteDetails, metadata: &NoteMetadata) -> Self {
65        Self::new(
66            details.script().root(),
67            details.storage().commitment(),
68            details.assets().commitment(),
69            details.serial_num(),
70            metadata.to_metadata_word(),
71            metadata.attachments_commitment(),
72        )
73    }
74
75    /// Returns the most significant felt (the last element in array)
76    pub fn most_significant_felt(&self) -> Felt {
77        self.as_elements()[3]
78    }
79
80    /// Returns the prefix of this nullifier.
81    ///
82    /// Nullifier prefix is defined as the 16 most significant bits of the nullifier value.
83    pub fn prefix(&self) -> u16 {
84        (self.as_word()[3].as_canonical_u64() >> NULLIFIER_PREFIX_SHIFT) as u16
85    }
86
87    /// Creates a Nullifier from a hex string. Assumes that the string starts with "0x" and
88    /// that the hexadecimal characters are big-endian encoded.
89    ///
90    /// Callers must ensure the provided value is an actual [`Nullifier`].
91    pub fn from_hex(hex_value: &str) -> Result<Self, WordError> {
92        Word::try_from(hex_value).map(Self::from_raw)
93    }
94
95    #[cfg(any(feature = "testing", test))]
96    pub fn dummy(n: u64) -> Self {
97        Self(Word::new([Felt::ZERO, Felt::ZERO, Felt::ZERO, Felt::new_unchecked(n)]))
98    }
99}
100
101impl Display for Nullifier {
102    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
103        f.write_str(&self.to_hex())
104    }
105}
106
107impl Debug for Nullifier {
108    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
109        Display::fmt(self, f)
110    }
111}
112
113// SERIALIZATION
114// ================================================================================================
115
116impl Serializable for Nullifier {
117    fn write_into<W: ByteWriter>(&self, target: &mut W) {
118        target.write_bytes(&self.0.to_bytes());
119    }
120
121    fn get_size_hint(&self) -> usize {
122        Word::SERIALIZED_SIZE
123    }
124}
125
126impl Deserializable for Nullifier {
127    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
128        let nullifier = Word::read_from(source)?;
129        Ok(Self(nullifier))
130    }
131}
132
133// TESTS
134// ================================================================================================
135
136#[cfg(test)]
137mod tests {
138    use crate::note::Nullifier;
139
140    #[test]
141    fn test_from_hex_and_back() {
142        let nullifier_hex = "0x41e7dbbc8ce63ec25cf2d76d76162f16ef8fd1195288171f5e5a3e178222f6d2";
143        let nullifier = Nullifier::from_hex(nullifier_hex).unwrap();
144
145        assert_eq!(nullifier_hex, nullifier.to_hex());
146    }
147}