Skip to main content

miden_node_proto/decode/
utils.rs

1use miden_protocol::Word;
2use miden_protocol::account::AccountId;
3
4use crate::decode::{ConversionResultExt, GrpcStructDecoder};
5use crate::errors::ConversionError;
6use crate::{decode, generated as proto};
7
8/// Reads a block range from a request, returning a specific error type if the field is missing
9pub fn read_block_range<E>(
10    block_range: Option<proto::rpc::BlockRange>,
11    entity: &'static str,
12) -> Result<proto::rpc::BlockRange, E>
13where
14    E: From<ConversionError>,
15{
16    block_range.ok_or_else(|| {
17        ConversionError::message(format!("{entity}: missing field `block_range`")).into()
18    })
19}
20
21/// Reads and converts a root field from a request to Word, returning a specific error type if
22/// conversion fails
23pub fn read_root<E>(
24    root: Option<proto::primitives::Digest>,
25    entity: &'static str,
26) -> Result<Word, E>
27where
28    E: From<ConversionError>,
29{
30    root.ok_or_else(|| ConversionError::message(format!("{entity}: missing field `root`")))?
31        .try_into()
32        .context("root")
33        .map_err(|e: ConversionError| e.into())
34}
35
36/// Converts a collection of proto primitives to Words, returning a specific error type if
37/// conversion fails
38pub fn convert_digests_to_words<E, I>(digests: I) -> Result<Vec<Word>, E>
39where
40    E: From<ConversionError>,
41    I: IntoIterator,
42    I::Item: TryInto<Word, Error = ConversionError>,
43{
44    digests
45        .into_iter()
46        .map(TryInto::try_into)
47        .collect::<Result<Vec<_>, ConversionError>>()
48        .context("digests")
49        .map_err(Into::into)
50}
51
52/// Reads account IDs from a request, returning a specific error type if conversion fails
53pub fn read_account_ids<E, I>(account_ids: I) -> Result<Vec<AccountId>, E>
54where
55    E: From<ConversionError>,
56    I: IntoIterator<Item = proto::account::AccountId>,
57{
58    account_ids
59        .into_iter()
60        .map(AccountId::try_from)
61        .collect::<Result<_, ConversionError>>()
62        .context("account_ids")
63        .map_err(Into::into)
64}
65
66pub fn read_account_id<M: crate::prost::Message, E>(
67    account_id: Option<proto::account::AccountId>,
68) -> Result<AccountId, E>
69where
70    E: From<ConversionError>,
71{
72    let decoder = GrpcStructDecoder::<M>::default();
73    decode!(decoder, account_id).map_err(|e: ConversionError| e.into())
74}