Skip to main content

miden_node_proto/domain/
note.rs

1use std::sync::Arc;
2
3use miden_protocol::crypto::merkle::SparseMerklePath;
4use miden_protocol::note::{
5    Note,
6    NoteAttachmentHeader,
7    NoteAttachmentScheme,
8    NoteAttachments,
9    NoteDetails,
10    NoteDetailsCommitment,
11    NoteHeader,
12    NoteId,
13    NoteInclusionProof,
14    NoteMetadata,
15    NoteScript,
16    NoteTag,
17    NoteType,
18    PartialNoteMetadata,
19};
20use miden_protocol::utils::serde::Serializable;
21use miden_protocol::{MastForest, MastNodeId, Word};
22use miden_standards::note::AccountTargetNetworkNote;
23
24use crate::decode::{ConversionResultExt, DecodeBytesExt, GrpcDecodeExt};
25use crate::errors::ConversionError;
26use crate::{decode, generated as proto};
27
28// NOTE TYPE
29// ================================================================================================
30
31impl From<NoteType> for proto::note::NoteType {
32    fn from(note_type: NoteType) -> Self {
33        match note_type {
34            NoteType::Public => proto::note::NoteType::Public,
35            NoteType::Private => proto::note::NoteType::Private,
36        }
37    }
38}
39
40impl TryFrom<proto::note::NoteType> for NoteType {
41    type Error = ConversionError;
42
43    fn try_from(note_type: proto::note::NoteType) -> Result<Self, Self::Error> {
44        match note_type {
45            proto::note::NoteType::Public => Ok(NoteType::Public),
46            proto::note::NoteType::Private => Ok(NoteType::Private),
47            proto::note::NoteType::Unspecified => {
48                Err(ConversionError::message("enum variant discriminant out of range"))
49            },
50        }
51    }
52}
53
54// NOTE METADATA
55// ================================================================================================
56
57impl From<NoteMetadata> for proto::note::NoteMetadata {
58    fn from(val: NoteMetadata) -> Self {
59        let sender = Some(val.sender().into());
60        let note_type = proto::note::NoteType::from(val.note_type()) as i32;
61        let tag = val.tag().as_u32();
62        let attachment_schemes = val
63            .attachment_headers()
64            .iter()
65            .map(|header| u32::from(header.scheme().map_or(0, |s| s.as_u16())))
66            .collect();
67        let attachments_commitment = Some(val.attachments_commitment().into());
68
69        proto::note::NoteMetadata {
70            sender,
71            note_type,
72            tag,
73            attachment_schemes,
74            attachments_commitment,
75        }
76    }
77}
78
79impl TryFrom<proto::note::NoteMetadata> for NoteMetadata {
80    type Error = ConversionError;
81
82    fn try_from(value: proto::note::NoteMetadata) -> Result<Self, Self::Error> {
83        let decoder = value.decoder();
84        let sender = decode!(decoder, value.sender)?;
85        let note_type = proto::note::NoteType::try_from(value.note_type)
86            .map_err(|_| ConversionError::message("enum variant discriminant out of range"))?
87            .try_into()
88            .context("note_type")?;
89        let tag = NoteTag::new(value.tag);
90        let attachments_commitment: Word = decode!(decoder, value.attachments_commitment)?;
91
92        if value.attachment_schemes.len() > NoteAttachments::MAX_COUNT {
93            return Err(ConversionError::message("too many attachment schemes"));
94        }
95        let mut attachment_headers = [NoteAttachmentHeader::absent(); NoteAttachments::MAX_COUNT];
96        for (slot, raw) in attachment_headers.iter_mut().zip(value.attachment_schemes) {
97            let raw = u16::try_from(raw)
98                .map_err(|_| ConversionError::message("attachment scheme out of u16 range"))?;
99            *slot = if raw == 0 {
100                NoteAttachmentHeader::absent()
101            } else {
102                NoteAttachmentHeader::new(NoteAttachmentScheme::new(raw)?)
103            };
104        }
105
106        let partial = PartialNoteMetadata::new(sender, note_type).with_tag(tag);
107        Ok(NoteMetadata::from_parts(partial, attachment_headers, attachments_commitment))
108    }
109}
110
111// NOTE
112// ================================================================================================
113
114impl From<Note> for proto::note::NetworkNote {
115    fn from(note: Note) -> Self {
116        let metadata = Some(proto::note::NoteMetadata::from(*note.metadata()));
117        let attachments = note.attachments().to_bytes();
118        let details = NoteDetails::from(note).to_bytes();
119        Self { metadata, details, attachments }
120    }
121}
122
123impl From<Note> for proto::note::Note {
124    fn from(note: Note) -> Self {
125        let metadata = Some(proto::note::NoteMetadata::from(*note.metadata()));
126        let attachments = note.attachments().to_bytes();
127        let details = Some(NoteDetails::from(note).to_bytes());
128        Self { metadata, details, attachments }
129    }
130}
131
132impl From<AccountTargetNetworkNote> for proto::note::NetworkNote {
133    fn from(note: AccountTargetNetworkNote) -> Self {
134        note.into_note().into()
135    }
136}
137
138impl TryFrom<proto::note::NetworkNote> for AccountTargetNetworkNote {
139    type Error = ConversionError;
140
141    fn try_from(value: proto::note::NetworkNote) -> Result<Self, Self::Error> {
142        let decoder = value.decoder();
143        let proto::note::NetworkNote { metadata, details, attachments } = value;
144
145        let metadata = decode!(decoder, metadata)?;
146        let partial_metadata = partial_note_metadata_from_proto(metadata)?;
147
148        let note_details = NoteDetails::decode_bytes(&details, "NoteDetails")?;
149        let (assets, recipient) = note_details.into_parts();
150        let attachments = decode_attachments(&attachments)?;
151
152        let note = Note::with_attachments(assets, partial_metadata, recipient, attachments);
153        AccountTargetNetworkNote::new(note).map_err(ConversionError::from)
154    }
155}
156
157impl TryFrom<proto::note::Note> for Note {
158    type Error = ConversionError;
159
160    fn try_from(proto_note: proto::note::Note) -> Result<Self, Self::Error> {
161        let decoder = proto_note.decoder();
162        let proto::note::Note { metadata, details, attachments } = proto_note;
163
164        let metadata = decode!(decoder, metadata)?;
165        let partial_metadata = partial_note_metadata_from_proto(metadata)?;
166
167        let details: Vec<u8> = decode!(decoder, details)?;
168        let note_details = NoteDetails::decode_bytes(&details, "NoteDetails")?;
169        let (assets, recipient) = note_details.into_parts();
170        let attachments = decode_attachments(&attachments)?;
171
172        Ok(Note::with_attachments(assets, partial_metadata, recipient, attachments))
173    }
174}
175
176// NOTE ID
177// ================================================================================================
178
179impl From<Word> for proto::note::NoteId {
180    fn from(digest: Word) -> Self {
181        Self { id: Some(digest.into()) }
182    }
183}
184
185impl TryFrom<proto::note::NoteId> for Word {
186    type Error = ConversionError;
187
188    fn try_from(note_id: proto::note::NoteId) -> Result<Self, Self::Error> {
189        let decoder = note_id.decoder();
190        decode!(decoder, note_id.id)
191    }
192}
193
194impl From<&NoteId> for proto::note::NoteId {
195    fn from(note_id: &NoteId) -> Self {
196        Self { id: Some(note_id.into()) }
197    }
198}
199
200impl From<(&NoteId, &NoteInclusionProof)> for proto::note::NoteInclusionInBlockProof {
201    fn from((note_id, proof): (&NoteId, &NoteInclusionProof)) -> Self {
202        Self {
203            note_id: Some(note_id.into()),
204            block_num: proof.location().block_num().as_u32(),
205            note_index_in_block: proof.location().block_note_tree_index().into(),
206            inclusion_path: Some(proof.note_path().clone().into()),
207        }
208    }
209}
210
211impl TryFrom<&proto::note::NoteInclusionInBlockProof> for (NoteId, NoteInclusionProof) {
212    type Error = ConversionError;
213
214    fn try_from(
215        proof: &proto::note::NoteInclusionInBlockProof,
216    ) -> Result<(NoteId, NoteInclusionProof), Self::Error> {
217        let decoder = proof.decoder();
218        let inclusion_path: SparseMerklePath =
219            decoder.decode_field("inclusion_path", proof.inclusion_path.clone())?;
220        let note_id: Word = decode!(decoder, proof.note_id)?;
221
222        Ok((
223            NoteId::from_raw(note_id),
224            NoteInclusionProof::new(
225                proof.block_num.into(),
226                proof.note_index_in_block.try_into().context("note_index_in_block")?,
227                inclusion_path,
228            )?,
229        ))
230    }
231}
232
233// NOTE HEADER
234// ================================================================================================
235
236impl From<NoteHeader> for proto::note::NoteHeader {
237    fn from(header: NoteHeader) -> Self {
238        Self {
239            details_commitment: Some(header.details_commitment().as_word().into()),
240            metadata: Some(header.into_metadata().into()),
241        }
242    }
243}
244
245impl TryFrom<proto::note::NoteHeader> for NoteHeader {
246    type Error = ConversionError;
247
248    fn try_from(value: proto::note::NoteHeader) -> Result<Self, Self::Error> {
249        let decoder = value.decoder();
250        let details_commitment_word: Word = decode!(decoder, value.details_commitment)?;
251        let metadata: NoteMetadata = decode!(decoder, value.metadata)?;
252
253        Ok(NoteHeader::new(
254            NoteDetailsCommitment::from_raw(details_commitment_word),
255            metadata,
256        ))
257    }
258}
259
260// NOTE SCRIPT
261// ================================================================================================
262
263impl From<NoteScript> for proto::note::NoteScript {
264    fn from(script: NoteScript) -> Self {
265        Self {
266            entrypoint: script.entrypoint().into(),
267            mast: script.mast().to_bytes(),
268        }
269    }
270}
271
272impl TryFrom<proto::note::NoteScript> for NoteScript {
273    type Error = ConversionError;
274
275    fn try_from(value: proto::note::NoteScript) -> Result<Self, Self::Error> {
276        let proto::note::NoteScript { entrypoint, mast } = value;
277
278        let mast = MastForest::decode_bytes(&mast, "note_script.mast")?;
279        let entrypoint = MastNodeId::from_u32_safe(entrypoint, &mast)
280            .map_err(|err| ConversionError::deserialization("note_script.entrypoint", err))?;
281
282        Ok(Self::from_parts(Arc::new(mast), entrypoint))
283    }
284}
285
286// HELPERS
287// ================================================================================================
288
289/// Decodes the `(sender, note_type, tag)` triple from a proto `NoteMetadata` into a
290/// [`PartialNoteMetadata`]. The attachment-related fields on the proto are ignored — when full
291/// attachments are also transmitted, the receiver derives the canonical headers and commitment from
292/// those instead.
293fn partial_note_metadata_from_proto(
294    value: proto::note::NoteMetadata,
295) -> Result<PartialNoteMetadata, ConversionError> {
296    let decoder = value.decoder();
297    let sender = decode!(decoder, value.sender)?;
298    let note_type = proto::note::NoteType::try_from(value.note_type)
299        .map_err(|_| ConversionError::message("enum variant discriminant out of range"))?
300        .try_into()
301        .context("note_type")?;
302    let tag = NoteTag::new(value.tag);
303    Ok(PartialNoteMetadata::new(sender, note_type).with_tag(tag))
304}
305
306/// Decodes a serialized [`NoteAttachments`] payload. Empty bytes are treated as an empty collection
307/// so that proto3's default value round-trips cleanly.
308fn decode_attachments(bytes: &[u8]) -> Result<NoteAttachments, ConversionError> {
309    if bytes.is_empty() {
310        Ok(NoteAttachments::empty())
311    } else {
312        NoteAttachments::decode_bytes(bytes, "NoteAttachments")
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use miden_protocol::account::{AccountId, AccountIdVersion, AccountType, AssetCallbackFlag};
319
320    use super::*;
321
322    #[test]
323    fn note_header_roundtrip_preserves_id() {
324        // Build a NoteHeader with a known details_commitment and metadata.
325        let details_commitment =
326            NoteDetailsCommitment::from_raw(Word::try_from([1u64, 2, 3, 4]).unwrap());
327        let sender = AccountId::dummy(
328            [1; 15],
329            AccountIdVersion::Version1,
330            AccountType::Public,
331            AssetCallbackFlag::Disabled,
332        );
333        let metadata = NoteMetadata::new(
334            PartialNoteMetadata::new(sender, NoteType::Public).with_tag(NoteTag::from(7u32)),
335            &NoteAttachments::default(),
336        );
337
338        let original = NoteHeader::new(details_commitment, metadata);
339
340        // Round-trip through proto.
341        let proto_header: proto::note::NoteHeader = original.into();
342        let decoded = NoteHeader::try_from(proto_header).expect("proto NoteHeader should decode");
343
344        // The protocol round trip must preserve both fields. The wire schema stores them in
345        // separate fields.
346        assert_eq!(decoded.id(), original.id());
347        assert_eq!(decoded.details_commitment(), original.details_commitment());
348        assert_eq!(decoded.metadata(), original.metadata());
349    }
350}