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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use alloc::string::ToString;

use miden_objects::{
    crypto::rand::FeltRng,
    notes::{Note, NoteDetails, NoteFile, NoteId, NoteInclusionProof, NoteTag},
    transaction::InputNote,
};
use miden_tx::auth::TransactionAuthenticator;
use tracing::info;
use winter_maybe_async::maybe_await;

use crate::{
    rpc::NodeRpcClient,
    store::{InputNoteRecord, NoteStatus, Store, StoreError},
    Client, ClientError,
};

impl<N: NodeRpcClient, R: FeltRng, S: Store, A: TransactionAuthenticator> Client<N, R, S, A> {
    // INPUT NOTE CREATION
    // --------------------------------------------------------------------------------------------

    /// Imports a new input note into the client's store. The information stored depends on the
    /// type of note file provided.
    ///
    /// - If the note file is a [NoteFile::NoteId], the note is fetched from the node and stored in
    ///   the client's store. If the note is private or does not exist, an error is returned. If the
    ///   ID was already stored, the inclusion proof and metadata are updated.
    /// - If the note file is a [NoteFile::NoteDetails], a new note is created with the provided
    ///   details. The note is marked as ignored if it contains no tag or if the tag is not
    ///   relevant.
    /// - If the note file is a [NoteFile::NoteWithProof], the note is stored with the provided
    ///   inclusion proof and metadata. The MMR data is only fetched from the node if the note is
    ///   committed in the past relative to the client.
    pub async fn import_note(&mut self, note_file: NoteFile) -> Result<NoteId, ClientError> {
        let note = match note_file {
            NoteFile::NoteId(id) => {
                let note_record = self.import_note_record_by_id(id).await?;
                if note_record.is_none() {
                    return Ok(id);
                }

                note_record.expect("The note record should be Some")
            },
            NoteFile::NoteDetails { details, after_block_num, tag } => {
                self.import_note_record_by_details(details, after_block_num, tag).await?
            },
            NoteFile::NoteWithProof(note, inclusion_proof) => {
                self.import_note_record_by_proof(note, inclusion_proof).await?
            },
        };
        let id = note.id();

        if maybe_await!(self.get_input_note(id)).is_ok() {
            return Err(ClientError::NoteImportError(format!(
                "Note with ID {} already exists",
                id
            )));
        }

        maybe_await!(self.store.insert_input_note(note))?;
        Ok(id)
    }

    // HELPERS
    // ================================================================================================

    /// Builds a note record from the note id. The note information is fetched from the node and
    /// stored in the client's store. If the note already exists in the store, the inclusion proof
    /// and metadata are updated.
    ///
    /// Errors:
    /// - If the note does not exist on the node.
    /// - If the note exists but is private.
    async fn import_note_record_by_id(
        &mut self,
        id: NoteId,
    ) -> Result<Option<InputNoteRecord>, ClientError> {
        let mut chain_notes = self.rpc_api.get_notes_by_id(&[id]).await?;
        if chain_notes.is_empty() {
            return Err(ClientError::NoteNotFoundOnChain(id));
        }

        let note_details: crate::rpc::NoteDetails =
            chain_notes.pop().expect("chain_notes should have at least one element");

        let inclusion_details = note_details.inclusion_details();

        // Add the inclusion proof to the imported note
        let inclusion_proof = NoteInclusionProof::new(
            inclusion_details.block_num,
            inclusion_details.note_index,
            inclusion_details.merkle_path.clone(),
        )?;

        let store_note = maybe_await!(self.get_input_note(id));

        match store_note {
            Ok(store_note) => {
                // TODO: Join these calls to one method that updates both fields with one query
                // (issue #404)
                maybe_await!(self
                    .store
                    .update_note_inclusion_proof(store_note.id(), inclusion_proof))?;
                maybe_await!(self
                    .store
                    .update_note_metadata(store_note.id(), *note_details.metadata()))?;

                Ok(None)
            },
            Err(ClientError::StoreError(StoreError::NoteNotFound(_))) => {
                let node_note = match note_details {
                    crate::rpc::NoteDetails::Public(note, _) => note,
                    crate::rpc::NoteDetails::OffChain(..) => {
                        return Err(ClientError::NoteImportError(
                            "Incomplete imported note is private".to_string(),
                        ))
                    },
                };

                self.import_note_record_by_proof(node_note, inclusion_proof).await.map(Some)
            },
            Err(err) => Err(err),
        }
    }

    /// Builds a note record from the note and inclusion proof. The note's nullifier is used to
    /// determine if the note has been consumed in the node and gives it the correct status.
    ///
    /// If the note is not consumed and it was committed in the past relative to the client, then
    /// the MMR for the relevant block is fetched from the node and stored.
    async fn import_note_record_by_proof(
        &mut self,
        note: Note,
        inclusion_proof: NoteInclusionProof,
    ) -> Result<InputNoteRecord, ClientError> {
        let details = note.clone().into();

        let status = if let Some(block_height) =
            self.rpc_api.get_nullifier_commit_height(&note.nullifier()).await?
        {
            NoteStatus::Consumed { consumer_account_id: None, block_height }
        } else {
            let block_height = inclusion_proof.location().block_num();
            let current_block_num = maybe_await!(self.get_sync_height())?;

            if block_height < current_block_num {
                let mut current_partial_mmr = maybe_await!(self.build_current_partial_mmr(true))?;

                self.get_and_store_authenticated_block(block_height, &mut current_partial_mmr)
                    .await?;
            }

            NoteStatus::Committed { block_height }
        };

        Ok(InputNoteRecord::new(
            note.id(),
            note.recipient().digest(),
            note.assets().clone(),
            status,
            Some(*note.metadata()),
            Some(inclusion_proof),
            details,
            false,
            None,
        ))
    }

    /// Builds a note record from the note details. If a tag is not provided or not tracked, the
    /// note is marked as ignored.
    async fn import_note_record_by_details(
        &mut self,
        details: NoteDetails,
        after_block_num: u32,
        tag: Option<NoteTag>,
    ) -> Result<InputNoteRecord, ClientError> {
        let record_details = details.clone().into();

        match tag {
            Some(tag) => {
                let ignored = !maybe_await!(self.get_tracked_note_tags())?.contains(&tag);

                if ignored {
                    info!("Ignoring note with tag {}", tag);
                }

                if let (NoteStatus::Committed { block_height }, Some(input_note)) =
                    self.check_expected_note(after_block_num, tag, &details).await?
                {
                    let mut current_partial_mmr =
                        maybe_await!(self.build_current_partial_mmr(true))?;
                    self.get_and_store_authenticated_block(block_height, &mut current_partial_mmr)
                        .await?;
                    Ok(InputNoteRecord::from(input_note))
                } else {
                    Ok(InputNoteRecord::new(
                        details.id(),
                        details.recipient().digest(),
                        details.assets().clone(),
                        NoteStatus::Expected {
                            created_at: None,
                            block_height: Some(after_block_num),
                        },
                        None,
                        None,
                        record_details,
                        ignored,
                        Some(tag),
                    ))
                }
            },
            None => Ok(InputNoteRecord::new(
                details.id(),
                details.recipient().digest(),
                details.assets().clone(),
                NoteStatus::Expected {
                    created_at: None,
                    block_height: Some(after_block_num),
                },
                None,
                None,
                record_details,
                true,
                None,
            )),
        }
    }

    /// Synchronizes a note with the chain.
    async fn check_expected_note(
        &mut self,
        mut request_block_num: u32,
        tag: NoteTag,
        expected_note: &miden_objects::notes::NoteDetails,
    ) -> Result<(NoteStatus, Option<InputNote>), ClientError> {
        let current_block_num = maybe_await!(self.get_sync_height())?;
        loop {
            if request_block_num > current_block_num {
                return Ok((
                    NoteStatus::Expected {
                        created_at: None,
                        block_height: Some(request_block_num),
                    },
                    None,
                ));
            };

            let sync_notes = self.rpc_api.sync_notes(request_block_num, &[tag]).await?;

            if sync_notes.block_header.block_num() == sync_notes.chain_tip {
                return Ok((
                    NoteStatus::Expected {
                        created_at: None,
                        block_height: Some(request_block_num),
                    },
                    None,
                ));
            }

            // This means that notes with that note_tag were found.
            // Therefore, we should check if a note with the same id was found.
            let committed_note =
                sync_notes.notes.iter().find(|note| note.note_id() == &expected_note.id());

            if let Some(note) = committed_note {
                // This means that a note with the same id was found.
                // Therefore, we should mark the note as committed.
                let note_block_num = sync_notes.block_header.block_num();

                if note_block_num > current_block_num {
                    return Ok((
                        NoteStatus::Expected {
                            created_at: None,
                            block_height: Some(request_block_num),
                        },
                        None,
                    ));
                };

                let note_inclusion_proof = NoteInclusionProof::new(
                    note_block_num,
                    note.note_index(),
                    note.merkle_path().clone(),
                )?;

                return Ok((
                    NoteStatus::Committed {
                        // Block header can't be None since we check that already in the if
                        // statement.
                        block_height: note_block_num,
                    },
                    Some(InputNote::authenticated(
                        Note::new(
                            expected_note.assets().clone(),
                            note.metadata(),
                            expected_note.recipient().clone(),
                        ),
                        note_inclusion_proof,
                    )),
                ));
            } else {
                // This means that a note with the same id was not found.
                // Therefore, we should request again for sync_notes with the same note_tag
                // and with the block_num of the last block header
                // (sync_notes.block_header.unwrap()).
                request_block_num = sync_notes.block_header.block_num();
            }
        }
    }
}