1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use crate::{
    accounts::AccountId,
    assembly::{Assembler, AssemblyContext, ProgramAst},
    assets::Asset,
    utils::serde::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
    vm::CodeBlock,
    Digest, Felt, Hasher, NoteError, Word, NOTE_TREE_DEPTH, WORD_SIZE, ZERO,
};

mod envelope;
pub use envelope::NoteEnvelope;

mod inputs;
pub use inputs::NoteInputs;

mod metadata;
pub use metadata::NoteMetadata;

mod note_id;
pub use note_id::NoteId;

mod nullifier;
pub use nullifier::Nullifier;

mod origin;
pub use origin::{NoteInclusionProof, NoteOrigin};

mod script;
pub use script::NoteScript;

mod assets;
pub use assets::NoteAssets;

// CONSTANTS
// ================================================================================================

/// The depth of the leafs in the note Merkle tree used to commit to notes produced in a block.
/// This is equal `NOTE_TREE_DEPTH + 1`. In the kernel we do not authenticate leaf data directly
/// but rather authenticate hash(left_leaf, right_leaf).
pub const NOTE_LEAF_DEPTH: u8 = NOTE_TREE_DEPTH + 1;

// NOTE
// ================================================================================================

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NoteType {
    /// Notes with this type have only their hash published to the network.
    OffChain,

    /// Notes with type are shared with the network encrypted.
    Encrypted,

    /// Notes with this type are known by the network, intended to be used in local transactions.
    Local,

    /// Notes with this type are known by the network, intended for network transactions.
    Network,
}

/// A note which can be used to transfer assets between accounts.
///
/// This struct is a full description of a note which is needed to execute a note in a transaction.
/// A note consists of:
///
/// Core on-chain data which is used to execute a note:
/// - A script which must be executed in a context of some account to claim the assets.
/// - A set of inputs which can be read to memory during script execution via the invocation of the
///   `note::get_inputs` in the kernel API.
/// - A set of assets stored in the note.
/// - A serial number which can be used to break linkability between note hash and note nullifier.
///
/// Auxiliary data which is used to verify authenticity and signal additional information:
/// - A metadata object which contains information about the sender, the tag and the number of
///   assets in the note.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Note {
    script: NoteScript,
    inputs: NoteInputs,
    assets: NoteAssets,
    serial_num: Word,
    metadata: NoteMetadata,

    id: NoteId,
    recipient: Digest,
    nullifier: Nullifier,
}

fn compute_recipient(serial_num: Word, script: &NoteScript, inputs: &NoteInputs) -> Digest {
    let serial_num_hash = Hasher::merge(&[serial_num.into(), Digest::default()]);
    let merge_script = Hasher::merge(&[serial_num_hash, script.hash()]);
    Hasher::merge(&[merge_script, inputs.commitment()])
}

impl Note {
    // CONSTRUCTOR
    // --------------------------------------------------------------------------------------------
    /// Returns a new note created with the specified parameters.
    ///
    /// # Errors
    /// Returns an error if:
    /// - The number of inputs exceeds 16.
    /// - The number of provided assets exceeds 1000.
    /// - The list of assets contains duplicates.
    pub fn new(
        script: NoteScript,
        inputs: &[Felt],
        assets: &[Asset],
        serial_num: Word,
        sender: AccountId,
        tag: Felt,
    ) -> Result<Self, NoteError> {
        let inputs = NoteInputs::new(inputs.to_vec())?;
        let assets = NoteAssets::new(assets)?;
        let metadata = NoteMetadata::new(sender, tag);

        Ok(Self::from_parts(script, inputs, assets, serial_num, metadata))
    }

    /// Returns a note instance created from the provided parts.
    pub fn from_parts(
        script: NoteScript,
        inputs: NoteInputs,
        assets: NoteAssets,
        serial_num: Word,
        metadata: NoteMetadata,
    ) -> Self {
        let recipient = compute_recipient(serial_num, &script, &inputs);
        let id = NoteId::new(recipient, assets.commitment());
        let nullifier =
            Nullifier::new(script.hash(), inputs.commitment(), assets.commitment(), serial_num);
        Self {
            script,
            inputs,
            assets,
            serial_num,
            metadata,
            id,
            recipient,
            nullifier,
        }
    }

    // PUBLIC ACCESSORS
    // --------------------------------------------------------------------------------------------

    /// Returns a reference script which locks the assets of this note.
    pub fn script(&self) -> &NoteScript {
        &self.script
    }

    /// Returns a reference to the note inputs.
    pub fn inputs(&self) -> &NoteInputs {
        &self.inputs
    }

    /// Returns a reference to the asset of this note.
    pub fn assets(&self) -> &NoteAssets {
        &self.assets
    }

    /// Returns a serial number of this note.
    pub fn serial_num(&self) -> Word {
        self.serial_num
    }

    /// Returns the metadata associated with this note.
    pub fn metadata(&self) -> &NoteMetadata {
        &self.metadata
    }

    /// Returns the recipient of this note.
    ///
    /// Recipient is defined and calculated as:
    ///
    /// > hash(hash(hash(serial_num, [0; 4]), script_hash), input_hash)
    ///
    pub fn recipient(&self) -> Digest {
        self.recipient
    }

    /// Returns a unique identifier of this note, which is simultaneously a commitment to the note.
    pub fn id(&self) -> NoteId {
        self.id
    }

    /// Returns the value used to authenticate a notes existence in the note tree. This is computed
    /// as a 2-to-1 hash of the note hash and note metadata [hash(note_id, note_metadata)]
    pub fn authentication_hash(&self) -> Digest {
        Hasher::merge(&[self.id().inner(), Word::from(self.metadata()).into()])
    }

    /// Returns the nullifier for this note.
    pub fn nullifier(&self) -> Nullifier {
        self.nullifier
    }
}

// SERIALIZATION
// ================================================================================================

impl Serializable for Note {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        let Note {
            script,
            inputs,
            assets,
            serial_num,
            metadata,

            id: _,
            recipient: _,
            nullifier: _,
        } = self;

        script.write_into(target);
        inputs.write_into(target);
        assets.write_into(target);
        serial_num.write_into(target);
        metadata.write_into(target);
    }
}

impl Deserializable for Note {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let script = NoteScript::read_from(source)?;
        let inputs = NoteInputs::read_from(source)?;
        let assets = NoteAssets::read_from(source)?;
        let serial_num = Word::read_from(source)?;
        let metadata = NoteMetadata::read_from(source)?;

        Ok(Self::from_parts(script, inputs, assets, serial_num, metadata))
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Note {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let bytes = self.to_bytes();
        serializer.serialize_bytes(&bytes)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Note {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use crate::utils::collections::*;

        let bytes: Vec<u8> = <Vec<u8> as serde::Deserialize>::deserialize(deserializer)?;
        Self::read_from_bytes(&bytes).map_err(serde::de::Error::custom)
    }
}