miden-objects 0.17.0-rc.3

Canonical Protobuf representations for Miden protocol objects
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use alloc::format;
use alloc::vec::Vec;

use miden_protocol::Word;
use miden_protocol::account::AccountUpdateDetails;
use miden_protocol::block::{
    BlockAccountUpdate,
    BlockBody,
    BlockHeader,
    BlockNumber,
    BlockSignatures,
    FeeParameters,
    OutputNoteBatch,
    SignedBlock,
    ValidatorConfig,
};
use miden_protocol::crypto::dsa::ecdsa_k256_keccak::{PublicKey, Signature};
use miden_protocol::crypto::merkle::MerklePath;
use miden_protocol::crypto::merkle::mmr::{Forest, MmrPeaks, PartialMmr};
use miden_protocol::note::Nullifier;
use miden_protocol::protocol_config::NextProtocolConfig;
use miden_protocol::transaction::{
    OrderedTransactionHeaders,
    OutputNote,
    PartialBlockchain,
    TransactionHeader,
};

use super::{MessageDecodeExt, required};
use crate::{ConversionError, ConversionResultExt, proto};

// BLOCK NUMBER
// ================================================================================================

impl From<BlockNumber> for proto::blockchain::BlockNumber {
    fn from(value: BlockNumber) -> Self {
        Self { block_num: value.as_u32() }
    }
}

impl From<proto::blockchain::BlockNumber> for BlockNumber {
    fn from(value: proto::blockchain::BlockNumber) -> Self {
        value.block_num.into()
    }
}

// PARTIAL BLOCKCHAIN
// ================================================================================================

impl From<&PartialBlockchain> for proto::blockchain::PartialBlockchain {
    fn from(value: &PartialBlockchain) -> Self {
        let mmr = value.mmr();
        let tracked_leaves = mmr
            .leaves()
            .map(|(position, leaf)| {
                let proof = mmr
                    .open(position)
                    .expect("tracked MMR position must be in bounds")
                    .expect("tracked MMR leaf must have an opening");
                proto::blockchain::TrackedMmrLeaf {
                    position: position as u64,
                    leaf: Some(leaf.into()),
                    path: proof.merkle_path().nodes().iter().map(Into::into).collect(),
                }
            })
            .collect();
        Self {
            forest: mmr.forest().num_leaves() as u64,
            peaks: mmr.peaks().peaks().iter().map(Into::into).collect(),
            tracked_leaves,
            block_headers: value.block_headers().map(Into::into).collect(),
        }
    }
}

impl TryFrom<proto::blockchain::PartialBlockchain> for PartialBlockchain {
    type Error = ConversionError;

    fn try_from(value: proto::blockchain::PartialBlockchain) -> Result<Self, Self::Error> {
        let forest_size = usize::try_from(value.forest).context("forest")?;
        let forest = Forest::new(forest_size).map_err(ConversionError::new).context("forest")?;
        let peaks = value
            .peaks
            .into_iter()
            .enumerate()
            .map(|(index, peak)| Word::try_from(peak).context(format!("peaks[{index}]")))
            .collect::<Result<Vec<_>, _>>()?;
        let peaks = MmrPeaks::new(forest, peaks).map_err(ConversionError::new).context("peaks")?;
        let mut mmr = PartialMmr::from_peaks(peaks);

        let mut previous_position = None;
        for (index, tracked) in value.tracked_leaves.into_iter().enumerate() {
            let position = usize::try_from(tracked.position)
                .context(format!("tracked_leaves[{index}].position"))?;
            if position >= forest_size {
                return Err(ConversionError::message(format!(
                    "tracked leaf position {position} is outside forest of size {forest_size}"
                ))
                .context(format!("tracked_leaves[{index}].position")));
            }
            if previous_position.is_some_and(|previous| position <= previous) {
                return Err(ConversionError::message(
                    "tracked leaf positions must be unique and strictly increasing",
                )
                .context(format!("tracked_leaves[{index}].position")));
            }
            previous_position = Some(position);

            let decoder = tracked.decoder();
            let leaf = required!(decoder, tracked.leaf)?;
            let path = tracked
                .path
                .into_iter()
                .enumerate()
                .map(|(path_index, node)| {
                    Word::try_from(node)
                        .context(format!("tracked_leaves[{index}].path[{path_index}]"))
                })
                .collect::<Result<Vec<_>, _>>()?;
            mmr.track(position, leaf, &MerklePath::new(path))
                .map_err(ConversionError::new)
                .context(format!("tracked_leaves[{index}]"))?;
        }

        let mut previous_block_num = None;
        let block_headers = value
            .block_headers
            .into_iter()
            .enumerate()
            .map(|(index, header)| {
                let header =
                    BlockHeader::try_from(header).context(format!("block_headers[{index}]"))?;
                if previous_block_num.is_some_and(|previous| header.block_num() <= previous) {
                    return Err(ConversionError::message(
                        "block headers must be unique and ordered by ascending block number",
                    )
                    .context(format!("block_headers[{index}].block_num")));
                }
                previous_block_num = Some(header.block_num());
                Ok(header)
            })
            .collect::<Result<Vec<_>, ConversionError>>()?;

        Self::new(mmr, block_headers).map_err(ConversionError::new)
    }
}

// BLOCK HEADER
// ================================================================================================

impl From<&BlockHeader> for proto::blockchain::BlockHeader {
    fn from(header: &BlockHeader) -> Self {
        Self {
            version: proto::blockchain::BlockVersion::V1 as i32,
            timestamp: header.timestamp(),
            block_num: Some(header.block_num().into()),
            prev_block_commitment: Some(header.prev_block_commitment().into()),
            chain_commitment: Some(header.chain_commitment().into()),
            account_root: Some(header.account_root().into()),
            nullifier_root: Some(header.nullifier_root().into()),
            note_root: Some(header.note_root().into()),
            tx_commitment: Some(header.tx_commitment().into()),
            validator_config: Some(header.validator_config().into()),
            fee_parameters: Some(header.fee_parameters().into()),
            protocol_config_commitment: Some(header.protocol_config_commitment().into()),
            next_protocol_config: header.next_protocol_config().map(Into::into),
        }
    }
}

impl From<BlockHeader> for proto::blockchain::BlockHeader {
    fn from(header: BlockHeader) -> Self {
        (&header).into()
    }
}

impl TryFrom<&proto::blockchain::BlockHeader> for BlockHeader {
    type Error = ConversionError;

    fn try_from(value: &proto::blockchain::BlockHeader) -> Result<Self, Self::Error> {
        value.clone().try_into()
    }
}

impl TryFrom<proto::blockchain::BlockHeader> for BlockHeader {
    type Error = ConversionError;

    fn try_from(header: proto::blockchain::BlockHeader) -> Result<Self, Self::Error> {
        decode_block_version(header.version).context("version")?;

        let decoder = header.decoder();
        let block_num = required!(decoder, header.block_num).context("block_num")?;
        let prev_block_commitment = required!(decoder, header.prev_block_commitment)?;
        let chain_commitment = required!(decoder, header.chain_commitment)?;
        let account_root = required!(decoder, header.account_root)?;
        let nullifier_root = required!(decoder, header.nullifier_root)?;
        let note_root = required!(decoder, header.note_root)?;
        let tx_commitment = required!(decoder, header.tx_commitment)?;
        let validator_config = required!(decoder, header.validator_config)?;
        let fee_parameters = required!(decoder, header.fee_parameters)?;
        let protocol_config_commitment = required!(decoder, header.protocol_config_commitment)?;
        let next_protocol_config = header
            .next_protocol_config
            .map(TryInto::try_into)
            .transpose()
            .context("next_protocol_config")?;

        Ok(BlockHeader::new(
            prev_block_commitment,
            block_num,
            chain_commitment,
            account_root,
            nullifier_root,
            note_root,
            tx_commitment,
            validator_config,
            fee_parameters,
            protocol_config_commitment,
            next_protocol_config,
            header.timestamp,
        ))
    }
}

fn decode_block_version(version: i32) -> Result<(), ConversionError> {
    match proto::blockchain::BlockVersion::try_from(version) {
        Ok(proto::blockchain::BlockVersion::V1) => Ok(()),
        Ok(proto::blockchain::BlockVersion::Unspecified) => {
            Err(ConversionError::message("block header version is unspecified"))
        },
        Err(error) => Err(ConversionError::with_source(
            format!("unknown block header version {version}"),
            error,
        )),
    }
}

// BLOCK BODY
// ================================================================================================

impl From<&BlockBody> for proto::blockchain::BlockBody {
    fn from(body: &BlockBody) -> Self {
        Self {
            updated_accounts: body.updated_accounts().iter().map(Into::into).collect(),
            output_note_batches: body.output_note_batches().iter().map(Into::into).collect(),
            created_nullifiers: body
                .created_nullifiers()
                .iter()
                .map(|nullifier| nullifier.as_word().into())
                .collect(),
            transactions: body.transactions().as_slice().iter().map(Into::into).collect(),
        }
    }
}

impl From<BlockBody> for proto::blockchain::BlockBody {
    fn from(body: BlockBody) -> Self {
        (&body).into()
    }
}

impl TryFrom<proto::blockchain::BlockBody> for BlockBody {
    type Error = ConversionError;

    fn try_from(value: proto::blockchain::BlockBody) -> Result<Self, Self::Error> {
        let updated_accounts = value
            .updated_accounts
            .into_iter()
            .enumerate()
            .map(|(index, update)| {
                BlockAccountUpdate::try_from(update).context(format!("updated_accounts[{index}]"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let output_note_batches = value
            .output_note_batches
            .into_iter()
            .enumerate()
            .map(|(index, batch)| {
                OutputNoteBatch::try_from(batch).context(format!("output_note_batches[{index}]"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let created_nullifiers = value
            .created_nullifiers
            .into_iter()
            .enumerate()
            .map(|(index, nullifier)| {
                Word::try_from(nullifier)
                    .map(Nullifier::from_raw)
                    .context(format!("created_nullifiers[{index}]"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let transactions = value
            .transactions
            .into_iter()
            .enumerate()
            .map(|(index, transaction)| {
                TransactionHeader::try_from(transaction).context(format!("transactions[{index}]"))
            })
            .collect::<Result<Vec<_>, _>>()?;

        BlockBody::new(
            updated_accounts,
            output_note_batches,
            created_nullifiers,
            OrderedTransactionHeaders::new_unchecked(transactions),
        )
        .map_err(ConversionError::new)
    }
}

impl TryFrom<&proto::blockchain::BlockBody> for BlockBody {
    type Error = ConversionError;

    fn try_from(value: &proto::blockchain::BlockBody) -> Result<Self, Self::Error> {
        value.clone().try_into()
    }
}

// BLOCK BODY COMPONENTS
// ================================================================================================

impl From<&BlockAccountUpdate> for proto::blockchain::BlockAccountUpdate {
    fn from(update: &BlockAccountUpdate) -> Self {
        Self {
            account_id: Some(update.account_id().into()),
            final_state_commitment: Some(update.final_state_commitment().into()),
            details: Some(update.details().into()),
        }
    }
}

impl TryFrom<proto::blockchain::BlockAccountUpdate> for BlockAccountUpdate {
    type Error = ConversionError;

    fn try_from(update: proto::blockchain::BlockAccountUpdate) -> Result<Self, Self::Error> {
        let decoder = update.decoder();
        let account_id = required!(decoder, update.account_id)?;
        let final_state_commitment = required!(decoder, update.final_state_commitment)?;
        let details: AccountUpdateDetails = required!(decoder, update.details)?;
        BlockAccountUpdate::new(account_id, final_state_commitment, details)
            .map_err(ConversionError::new)
    }
}

impl From<&(usize, OutputNote)> for proto::blockchain::IndexedOutputNote {
    fn from((index, note): &(usize, OutputNote)) -> Self {
        Self {
            note_index_in_batch: u32::try_from(*index)
                .expect("valid output note indices fit into u32"),
            note: Some(note.into()),
        }
    }
}

impl TryFrom<proto::blockchain::IndexedOutputNote> for (usize, OutputNote) {
    type Error = ConversionError;

    fn try_from(note: proto::blockchain::IndexedOutputNote) -> Result<Self, Self::Error> {
        let decoder = note.decoder();
        let index = usize::try_from(note.note_index_in_batch).context("note_index_in_batch")?;
        let output_note = required!(decoder, note.note)?;
        Ok((index, output_note))
    }
}

impl From<&OutputNoteBatch> for proto::blockchain::OutputNoteBatch {
    fn from(batch: &OutputNoteBatch) -> Self {
        Self {
            notes: batch.iter().map(Into::into).collect(),
        }
    }
}

impl TryFrom<proto::blockchain::OutputNoteBatch> for OutputNoteBatch {
    type Error = ConversionError;

    fn try_from(batch: proto::blockchain::OutputNoteBatch) -> Result<Self, Self::Error> {
        batch
            .notes
            .into_iter()
            .enumerate()
            .map(|(position, note)| {
                <(usize, OutputNote)>::try_from(note).context(format!("notes[{position}]"))
            })
            .collect()
    }
}

// SIGNED BLOCK
// ================================================================================================

impl From<&SignedBlock> for proto::blockchain::SignedBlock {
    fn from(block: &SignedBlock) -> Self {
        Self {
            header: Some(block.header().into()),
            body: Some(block.body().into()),
            signatures: block.signatures().as_signatures().iter().map(Into::into).collect(),
        }
    }
}

impl From<SignedBlock> for proto::blockchain::SignedBlock {
    fn from(block: SignedBlock) -> Self {
        (&block).into()
    }
}

impl TryFrom<proto::blockchain::SignedBlock> for SignedBlock {
    type Error = ConversionError;

    fn try_from(value: proto::blockchain::SignedBlock) -> Result<Self, Self::Error> {
        let decoder = value.decoder();
        let header = required!(decoder, value.header)?;
        let body = required!(decoder, value.body)?;
        let signatures = value
            .signatures
            .into_iter()
            .map(Signature::try_from)
            .collect::<Result<Vec<_>, _>>()
            .context("signatures")?;
        let signatures = BlockSignatures::new(signatures)
            .map_err(ConversionError::new)
            .context("signatures")?;

        SignedBlock::new(header, body, signatures)
            .map_err(ConversionError::new)
            .context("body")
    }
}

impl TryFrom<&proto::blockchain::SignedBlock> for SignedBlock {
    type Error = ConversionError;

    fn try_from(value: &proto::blockchain::SignedBlock) -> Result<Self, Self::Error> {
        value.clone().try_into()
    }
}

// VALIDATOR AND PROTOCOL CONFIGURATION
// ================================================================================================

impl TryFrom<proto::blockchain::ValidatorConfig> for ValidatorConfig {
    type Error = ConversionError;

    fn try_from(value: proto::blockchain::ValidatorConfig) -> Result<Self, Self::Error> {
        let keys = value
            .keys
            .into_iter()
            .enumerate()
            .map(|(index, key)| PublicKey::try_from(key).context(format!("keys[{index}]")))
            .collect::<Result<Vec<_>, _>>()?;
        let quorum = u16::try_from(value.quorum).context("quorum")?;

        Self::new(keys, quorum).map_err(ConversionError::new)
    }
}

impl From<&ValidatorConfig> for proto::blockchain::ValidatorConfig {
    fn from(value: &ValidatorConfig) -> Self {
        Self {
            keys: value.keys().iter().map(Into::into).collect(),
            quorum: u32::from(value.quorum()),
        }
    }
}

impl From<ValidatorConfig> for proto::blockchain::ValidatorConfig {
    fn from(value: ValidatorConfig) -> Self {
        (&value).into()
    }
}

impl TryFrom<proto::blockchain::NextProtocolConfig> for NextProtocolConfig {
    type Error = ConversionError;

    fn try_from(value: proto::blockchain::NextProtocolConfig) -> Result<Self, Self::Error> {
        let decoder = value.decoder();
        let effective_from = required!(decoder, value.effective_from)?;
        let protocol_config = required!(decoder, value.protocol_config)?;

        Self::new(effective_from, protocol_config).map_err(ConversionError::new)
    }
}

impl From<&NextProtocolConfig> for proto::blockchain::NextProtocolConfig {
    fn from(value: &NextProtocolConfig) -> Self {
        Self {
            effective_from: Some(value.effective_from().into()),
            protocol_config: Some(value.protocol_config().into()),
        }
    }
}

impl From<NextProtocolConfig> for proto::blockchain::NextProtocolConfig {
    fn from(value: NextProtocolConfig) -> Self {
        (&value).into()
    }
}

impl From<proto::blockchain::FeeParameters> for FeeParameters {
    fn from(value: proto::blockchain::FeeParameters) -> Self {
        Self::new(value.verification_base_fee)
    }
}

impl From<&FeeParameters> for proto::blockchain::FeeParameters {
    fn from(value: &FeeParameters) -> Self {
        Self {
            verification_base_fee: value.verification_base_fee(),
        }
    }
}

impl From<FeeParameters> for proto::blockchain::FeeParameters {
    fn from(value: FeeParameters) -> Self {
        (&value).into()
    }
}