miden-node-rpc 0.17.0-rc.3

Miden node's front-end RPC server
Documentation
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use miden_node_proto::{DecodeMessage, Verify, generated as proto};
use miden_node_store::{NoteSyncError, NoteSyncRecord};
use miden_node_tracing::{debug, miden_instrument, miden_span_record};
use miden_node_utils::limiter::QueryParamNoteTagLimit;
use tonic::Status;

use super::error_codes::{SyncErrorCode, SyncNotesErrorCode, internal_error};
use super::{RpcService, check, invalid_block_range_to_status};
use crate::{COMPONENT, LOG_TARGET};

#[tonic::async_trait]
impl proto::server::rpc_api::SyncNotes for RpcService {
    type Input = proto::rpc::DecodedSyncNotesRequest;
    type Output = proto::rpc::SyncNotesResponse;

    fn decode(request: proto::rpc::SyncNotesRequest) -> tonic::Result<Self::Input> {
        request
            .decode_fields()
            .map_err(|err| SyncNotesErrorCode::DeserializationFailed.invalid_argument(err))
    }

    fn encode(output: Self::Output) -> tonic::Result<proto::rpc::SyncNotesResponse> {
        Ok(output)
    }

    #[miden_instrument(
        target = COMPONENT,
        name = "sync_notes",
        err,
    )]
    async fn handle(
        &self,
        request: Self::Input,
        _metadata: &tonic::metadata::MetadataMap,
        _extensions: &tonic::codegen::http::Extensions,
    ) -> tonic::Result<Self::Output> {
        let range = request.block_range;
        let note_tags = request.note_tags.into_inner();

        miden_span_record!(
            block_range.from = range.block_from,
            block_range.to = range.block_to,
            note.tags = note_tags.as_slice(),
            note.tag.count = note_tags.len()
        );

        debug!(
            target: LOG_TARGET,
            "Syncing notes",
            block_range.from = range.block_from,
            block_range.to = range.block_to,
            note.tags = note_tags.as_slice(),
            note.tag.count = note_tags.len()
        );

        check::<QueryParamNoteTagLimit>(note_tags.len())?;

        let block_range = range.verify().map_err(invalid_block_range_to_status)?;
        let (chain_tip, (results, last_block_checked)) = self
            .state
            .with_view(async |view| {
                view.sync_notes(note_tags, block_range)
                    .await
                    .map(|notes| (view.tip(), notes))
                    .map_err(note_sync_error_to_status)
            })
            .await?;
        let blocks = results
            .into_iter()
            .map(|(state, mmr_proof)| proto::rpc::sync_notes_response::NoteSyncBlock {
                block_header: Some(state.block_header.into()),
                mmr_path: Some(mmr_proof.merkle_path().clone().into()),
                notes: state.notes.into_iter().map(note_sync_record_to_proto).collect(),
            })
            .collect();

        Ok(proto::rpc::SyncNotesResponse {
            pagination_info: Some(proto::rpc::PaginationInfo {
                chain_tip: chain_tip.as_u32(),
                block_num: last_block_checked.as_u32(),
            }),
            blocks,
        })
    }
}

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

fn note_sync_record_to_proto(note: NoteSyncRecord) -> proto::rpc::NoteSyncRecord {
    let attachments = note
        .attachments
        .iter()
        .map(|attachment| {
            let payload = if attachment.num_words() == 1 {
                proto::rpc::note_sync_attachment::Payload::Value(
                    attachment.content().as_words()[0].into(),
                )
            } else {
                proto::rpc::note_sync_attachment::Payload::Commitment(
                    attachment.to_commitment().into(),
                )
            };

            proto::rpc::NoteSyncAttachment {
                scheme: attachment.attachment_scheme().as_u16().into(),
                payload: Some(payload),
            }
        })
        .collect();
    let metadata = Some(proto::rpc::NoteSyncMetadata {
        sender: Some(note.metadata.sender().into()),
        version: proto::note::NoteVersion::V1 as i32,
        note_type: proto::note::NoteType::from(note.metadata.note_type()) as i32,
        tag: note.metadata.tag().as_u32(),
        attachments,
    });
    let inclusion_proof = Some(proto::note::NoteInclusionProof {
        note_id: Some((&note.note_id).into()),
        block_num: Some(note.block_num.into()),
        note_index_in_block: note.note_index.leaf_index_value().into(),
        inclusion_path: Some(note.inclusion_path.into()),
    });
    proto::rpc::NoteSyncRecord { metadata, inclusion_proof }
}

fn note_sync_error_to_status(err: NoteSyncError) -> Status {
    let message = err.to_string();
    match err {
        NoteSyncError::DatabaseError(err) => super::database_error_to_status(&err),
        NoteSyncError::InvalidBlockRange(_) => {
            SyncErrorCode::InvalidBlockRange.invalid_argument(message)
        },
        NoteSyncError::RangeBeyondTip(_) => {
            SyncNotesErrorCode::FutureBlock.invalid_argument(message)
        },
        NoteSyncError::DeserializationFailed(err) => {
            SyncNotesErrorCode::DeserializationFailed.invalid_argument(err)
        },
        NoteSyncError::UnderlyingDatabaseError(_)
        | NoteSyncError::EmptyBlockHeadersTable
        | NoteSyncError::MmrError(_) => internal_error(message),
    }
}

#[cfg(test)]
mod tests {
    use miden_node_proto::prost::Message;
    use miden_protocol::account::{AccountId, AccountIdVersion, AccountType, AssetCallbackFlag};
    use miden_protocol::block::{BlockNoteIndex, BlockNumber, ValidatorConfig};
    use miden_protocol::crypto::merkle::SparseMerklePath;
    use miden_protocol::note::{
        NoteAttachment,
        NoteAttachmentScheme,
        NoteAttachments,
        NoteId,
        NoteMetadata,
        NoteTag,
        NoteType,
        PartialNoteMetadata,
    };
    use miden_protocol::{
        BLOCK_NOTE_TREE_DEPTH,
        Hasher,
        MAX_BATCHES_PER_BLOCK,
        MAX_OUTPUT_NOTES_PER_BATCH,
        Word,
    };

    use super::*;

    #[test]
    fn sync_note_encodes_attachment_values_and_commitments() {
        let single_word = Word::from([1, 2, 3, 4u32]);
        let single_word_scheme = NoteAttachmentScheme::new(42).unwrap();
        let multi_word_scheme = NoteAttachmentScheme::new(100).unwrap();
        let multi_word_attachment = NoteAttachment::with_words(
            multi_word_scheme,
            vec![Word::from([5, 6, 7, 8u32]), Word::from([9, 10, 11, 12u32])],
        )
        .unwrap();
        let multi_word_commitment = multi_word_attachment.to_commitment();
        let attachments = NoteAttachments::new(vec![
            NoteAttachment::with_word(single_word_scheme, single_word),
            multi_word_attachment,
        ])
        .unwrap();

        let sender = AccountId::dummy(
            [1; 15],
            AccountIdVersion::Version1,
            AccountType::Public,
            AssetCallbackFlag::Disabled,
        );
        let metadata = NoteMetadata::new(
            PartialNoteMetadata::new(sender, NoteType::Private).with_tag(NoteTag::from(7u32)),
            &attachments,
        );
        let expected_metadata_commitment = metadata.to_commitment();
        let record = NoteSyncRecord {
            block_num: BlockNumber::from(3),
            note_index: BlockNoteIndex::new(0, 1).unwrap(),
            note_id: NoteId::from_raw(Word::from([13, 14, 15, 16u32])),
            metadata,
            attachments: attachments.clone(),
            inclusion_path: SparseMerklePath::default(),
        };

        let proto_record = note_sync_record_to_proto(record);
        let proto_metadata = proto_record.metadata.unwrap();
        assert_eq!(proto_metadata.sender, Some(sender.into()));
        assert_eq!(proto_metadata.version, proto::note::NoteVersion::V1 as i32);
        assert_eq!(proto_metadata.note_type, proto::note::NoteType::Private as i32);
        assert_eq!(proto_metadata.tag, 7);
        assert_eq!(proto_metadata.attachments.len(), 2);

        let first = &proto_metadata.attachments[0];
        assert_eq!(first.scheme, u32::from(single_word_scheme.as_u16()));
        assert_eq!(
            first.payload,
            Some(proto::rpc::note_sync_attachment::Payload::Value(single_word.into()))
        );

        let second = &proto_metadata.attachments[1];
        assert_eq!(second.scheme, u32::from(multi_word_scheme.as_u16()));
        assert_eq!(
            second.payload,
            Some(proto::rpc::note_sync_attachment::Payload::Commitment(
                multi_word_commitment.into()
            ))
        );

        let attachment_commitments: Vec<Word> = proto_metadata
            .attachments
            .iter()
            .map(|attachment| match attachment.payload.as_ref().unwrap() {
                proto::rpc::note_sync_attachment::Payload::Value(value) => {
                    let value = Word::try_from(value).unwrap();
                    Hasher::hash_elements(value.as_elements())
                },
                proto::rpc::note_sync_attachment::Payload::Commitment(commitment) => {
                    Word::try_from(commitment).unwrap()
                },
            })
            .collect();
        let commitment_elements: Vec<_> =
            attachment_commitments.iter().flat_map(Word::as_elements).copied().collect();
        let attachments_commitment = Hasher::hash_elements(&commitment_elements);
        assert_eq!(attachments_commitment, attachments.to_commitment());

        let mut attachment_schemes = proto_metadata
            .attachments
            .iter()
            .map(|attachment| attachment.scheme)
            .collect::<Vec<_>>();
        attachment_schemes.resize(NoteAttachments::MAX_COUNT, 0);
        let reconstructed: NoteMetadata = proto::note::NoteMetadata {
            version: proto_metadata.version,
            sender: proto_metadata.sender,
            note_type: proto_metadata.note_type,
            tag: proto_metadata.tag,
            attachment_schemes,
            attachments_commitment: Some(attachments_commitment.into()),
        }
        .decode_fields()
        .unwrap()
        .verify()
        .unwrap();
        assert_eq!(reconstructed.to_commitment(), expected_metadata_commitment);
    }

    #[test]
    fn sync_note_without_attachments_encodes_an_empty_list() {
        let attachments = NoteAttachments::empty();
        let sender = AccountId::dummy(
            [2; 15],
            AccountIdVersion::Version1,
            AccountType::Public,
            AssetCallbackFlag::Disabled,
        );
        let record = NoteSyncRecord {
            block_num: BlockNumber::from(1),
            note_index: BlockNoteIndex::new(0, 0).unwrap(),
            note_id: NoteId::from_raw(Word::from([1, 1, 1, 1u32])),
            metadata: NoteMetadata::new(
                PartialNoteMetadata::new(sender, NoteType::Public),
                &attachments,
            ),
            attachments,
            inclusion_path: SparseMerklePath::default(),
        };

        let proto_record = note_sync_record_to_proto(record);
        let metadata = proto_record.metadata.unwrap();
        assert!(metadata.attachments.is_empty());
        assert_eq!(metadata.version, proto::note::NoteVersion::V1 as i32);
    }

    #[test]
    #[expect(
        clippy::too_many_lines,
        reason = "the fixture exercises the maximum size of each response field"
    )]
    fn compact_note_sync_response_fits_pagination_size_estimates() {
        // Keep these budgets aligned with the store note sync pagination estimates.
        const RECORD_BUDGET: usize = 900;
        const BLOCK_OVERHEAD_BUDGET: usize = 1800;

        let word = Word::from([1, 2, 3, 4u32]);
        let attachments = NoteAttachments::new(
            (1..=NoteAttachments::MAX_COUNT)
                .map(|scheme| {
                    NoteAttachment::with_word(
                        NoteAttachmentScheme::new(u16::try_from(scheme).unwrap()).unwrap(),
                        word,
                    )
                })
                .collect(),
        )
        .unwrap();
        let sender = AccountId::dummy(
            [1; 15],
            AccountIdVersion::Version1,
            AccountType::Public,
            AssetCallbackFlag::Disabled,
        );
        let record = note_sync_record_to_proto(NoteSyncRecord {
            block_num: BlockNumber::from(u32::MAX),
            note_index: BlockNoteIndex::new(
                MAX_BATCHES_PER_BLOCK - 1,
                MAX_OUTPUT_NOTES_PER_BATCH - 1,
            )
            .unwrap(),
            note_id: NoteId::from_raw(word),
            metadata: NoteMetadata::new(
                PartialNoteMetadata::new(sender, NoteType::Public)
                    .with_tag(NoteTag::from(u32::MAX)),
                &attachments,
            ),
            attachments,
            inclusion_path: SparseMerklePath::from_parts(
                0,
                vec![word; usize::from(BLOCK_NOTE_TREE_DEPTH)],
            )
            .unwrap(),
        });
        assert_eq!(record.metadata.as_ref().unwrap().attachments.len(), 4);
        assert_eq!(
            record
                .inclusion_proof
                .as_ref()
                .unwrap()
                .inclusion_path
                .as_ref()
                .unwrap()
                .siblings
                .len(),
            16
        );

        let header = proto::blockchain::BlockHeader {
            version: proto::blockchain::BlockVersion::V1 as i32,
            timestamp: u32::MAX,
            block_num: Some(BlockNumber::from(u32::MAX).into()),
            prev_block_commitment: Some(word.into()),
            chain_commitment: Some(word.into()),
            account_root: Some(word.into()),
            nullifier_root: Some(word.into()),
            note_root: Some(word.into()),
            tx_commitment: Some(word.into()),
            validator_config: Some(proto::blockchain::ValidatorConfig {
                keys: vec![
                    proto::primitives::PublicKey {
                        key: Some(proto::primitives::public_key::Key::EcdsaK256Keccak(vec![2; 33])),
                    };
                    ValidatorConfig::MAX_VALIDATORS
                ],
                quorum: u32::try_from(ValidatorConfig::MAX_VALIDATORS).unwrap(),
            }),
            fee_parameters: Some(proto::blockchain::FeeParameters {
                verification_base_fee: u32::MAX,
            }),
            protocol_config_commitment: Some(word.into()),
            next_protocol_config: Some(proto::blockchain::NextProtocolConfig {
                effective_from: Some(BlockNumber::from(u32::MAX).into()),
                protocol_config: Some(word.into()),
            }),
        };
        let block = proto::rpc::sync_notes_response::NoteSyncBlock {
            block_header: Some(header),
            mmr_path: Some(proto::primitives::MerklePath {
                siblings: vec![word.into(); u32::BITS as usize],
            }),
            notes: Vec::new(),
        };
        let mut response = proto::rpc::SyncNotesResponse {
            pagination_info: Some(proto::rpc::PaginationInfo {
                chain_tip: u32::MAX,
                block_num: u32::MAX,
            }),
            blocks: vec![block],
        };
        let overhead = response.encoded_len();
        assert!(overhead <= BLOCK_OVERHEAD_BUDGET, "block overhead is {overhead} bytes");

        response.blocks[0].notes.push(record);
        let record_size = response.encoded_len() - overhead;
        assert!(record_size <= RECORD_BUDGET, "compact note record adds {record_size} bytes");
        assert!(response.encoded_len() <= BLOCK_OVERHEAD_BUDGET + RECORD_BUDGET);
    }
}