miden-protocol 0.17.0-rc.4

Core components of the Miden protocol
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
use alloc::string::ToString;
use alloc::vec;
use std::collections::BTreeMap;
use std::vec::Vec;

use assert_matches::assert_matches;

use crate::account::{
    AccountCode,
    AccountHeader,
    AccountId,
    AccountStorageHeader,
    PartialAccount,
    PartialStorage,
    StorageSlotHeader,
    StorageSlotName,
    StorageSlotType,
};
use crate::asset::PartialVault;
use crate::block::BlockHeader;
use crate::block::account_tree::AccountIdKey;
use crate::errors::{TransactionInputError, TransactionInputsExtractionError};
use crate::protocol_config::ProtocolConfig;
use crate::testing::account_id::{
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2,
};
use crate::transaction::{InputNotes, PartialBlockchain, TransactionArgs, TransactionInputs};
use crate::utils::serde::{Deserializable, Serializable};
use crate::vm::AdviceInputs;
use crate::{Felt, Word};

#[test]
fn test_read_foreign_account_inputs_missing_data() {
    let native_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
    let foreign_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2).unwrap();

    // Create minimal transaction inputs with empty advice map.
    let code = AccountCode::mock();
    let storage_header = AccountStorageHeader::new(vec![]).unwrap();
    let partial_storage = PartialStorage::new(storage_header, []).unwrap();
    let partial_vault = PartialVault::new(Word::default());
    let partial_account = PartialAccount::new(
        native_account_id,
        Felt::new_unchecked(10),
        code,
        partial_storage,
        partial_vault,
        None,
    )
    .unwrap();

    let tx_inputs = TransactionInputs {
        account: partial_account,
        block_header: BlockHeader::mock(0, None, None, &[]),
        blockchain: PartialBlockchain::default(),
        input_notes: InputNotes::new(vec![]).unwrap(),
        protocol_config: ProtocolConfig::mock(),
        tx_args: TransactionArgs::default(),
        advice_inputs: AdviceInputs::default(),
        foreign_account_code: Vec::new(),
        foreign_account_slot_names: BTreeMap::new(),
    };

    // Try to read foreign account that doesn't exist in advice map.
    let result = tx_inputs.read_foreign_account_inputs(foreign_account_id);

    assert!(
        matches!(result, Err(TransactionInputsExtractionError::ForeignAccountNotFound(id)) if id == foreign_account_id)
    );
}

#[test]
fn test_read_foreign_account_inputs_with_storage_data() {
    use crate::testing::account_id::ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2;

    let native_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
    let foreign_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2).unwrap();

    // Create minimal transaction inputs with proper advice map.
    let code = AccountCode::mock();
    let storage_header = AccountStorageHeader::new(vec![]).unwrap();
    let partial_storage = PartialStorage::new(storage_header, []).unwrap();
    let partial_vault = PartialVault::new(Word::default());
    let partial_account = PartialAccount::new(
        native_account_id,
        Felt::new_unchecked(10),
        code.clone(),
        partial_storage,
        partial_vault,
        None,
    )
    .unwrap();

    // Create foreign account header and storage data.
    let foreign_header = AccountHeader::new(
        foreign_account_id,
        Felt::new_unchecked(5),
        Word::default(),
        Word::new([Felt::ONE, Felt::from(2_u32), Felt::from(3_u32), Felt::from(4_u32)]),
        code.commitment(),
    );

    // Create storage slots with test data.
    let slot_name1 = StorageSlotName::new("test::slot1::value".to_string()).unwrap();
    let slot_name2 = StorageSlotName::new("test::slot2::value".to_string()).unwrap();
    let slot1 = StorageSlotHeader::new(
        slot_name1,
        StorageSlotType::Value,
        Word::new([Felt::from(10_u32), Felt::from(20_u32), Felt::from(30_u32), Felt::from(40_u32)]),
    );
    let slot2 = StorageSlotHeader::new(
        slot_name2,
        StorageSlotType::Map,
        Word::new([Felt::from(50_u32), Felt::from(60_u32), Felt::from(70_u32), Felt::from(80_u32)]),
    );

    let mut slots = vec![slot1, slot2];
    slots.sort_by_key(|slot| slot.id());
    let foreign_storage_header = AccountStorageHeader::new(slots.clone()).unwrap();

    // Create advice inputs with both account header and storage header.
    let account_id_key = AccountIdKey::from(foreign_account_id);
    let advice_inputs = AdviceInputs::default().with_map([
        (account_id_key.as_word(), foreign_header.to_elements().to_vec()),
        (foreign_header.storage_commitment(), foreign_storage_header.to_elements()),
    ]);

    let foreign_account_slot_names = BTreeMap::from([
        (slots[0].id(), slots[0].name().clone()),
        (slots[1].id(), slots[1].name().clone()),
    ]);
    let tx_inputs = TransactionInputs {
        account: partial_account,
        block_header: BlockHeader::mock(0, None, None, &[]),
        blockchain: PartialBlockchain::default(),
        input_notes: InputNotes::new(vec![]).unwrap(),
        protocol_config: ProtocolConfig::mock(),
        tx_args: TransactionArgs::default(),
        advice_inputs,
        foreign_account_code: vec![code],
        foreign_account_slot_names,
    };

    // Try to read foreign account with storage data.
    // Should succeed and create partial account with proper storage.
    let account_inputs = tx_inputs.read_foreign_account_inputs(foreign_account_id).unwrap();
    assert_eq!(account_inputs.id(), foreign_account_id);
    assert_eq!(account_inputs.account().nonce(), Felt::new_unchecked(5));

    // Verify storage was properly reconstructed.
    let storage = account_inputs.account().storage();
    assert_eq!(storage.header().slots().count(), 2);

    // Verify witness data is valid.
    let witness = account_inputs.witness();
    assert_eq!(witness.id(), foreign_account_id);

    // Verify the witness can compute a valid account root.
    let computed_root = account_inputs.compute_account_root();
    assert!(
        computed_root.is_ok(),
        "Failed to compute account root from witness: {:?}",
        computed_root.err()
    );

    // Test that the witness path has the expected depth for SMT.
    assert_eq!(witness.path().depth(), 64, "Witness path should have SMT depth of 64");
}

#[test]
fn test_read_foreign_account_inputs_with_proper_witness() {
    use crate::block::account_tree::AccountTree;
    use crate::crypto::merkle::smt::Smt;
    use crate::testing::account_id::ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2;

    let native_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
    let foreign_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2).unwrap();

    // Create a native account.
    let code = AccountCode::mock();
    let storage_header = AccountStorageHeader::new(vec![]).unwrap();
    let partial_storage = PartialStorage::new(storage_header, []).unwrap();
    let partial_vault = PartialVault::new(Word::default());
    let native_account = PartialAccount::new(
        native_account_id,
        Felt::new_unchecked(10),
        code.clone(),
        partial_storage,
        partial_vault,
        None,
    )
    .unwrap();

    // Create a foreign account with proper commitment.
    let foreign_header = AccountHeader::new(
        foreign_account_id,
        Felt::new_unchecked(5),
        Word::default(),
        Word::new([Felt::ONE, Felt::from(2_u32), Felt::from(3_u32), Felt::from(4_u32)]),
        code.commitment(),
    );

    // Create storage header for the foreign account.
    let foreign_storage_header = AccountStorageHeader::new(vec![]).unwrap();

    // Create an account tree and insert both accounts to get proper Merkle paths.
    let mut account_tree = AccountTree::<Smt>::default();

    // Insert native account.
    let native_commitment = AccountHeader::from(&native_account).to_commitment();
    account_tree.insert(native_account_id, native_commitment).unwrap();

    // Insert foreign account.
    let _foreign_partial_account = PartialAccount::new(
        foreign_account_id,
        Felt::new_unchecked(5),
        code.clone(),
        PartialStorage::new(foreign_storage_header.clone(), []).unwrap(),
        PartialVault::new(Word::default()),
        None,
    )
    .unwrap();
    account_tree.insert(foreign_account_id, foreign_header.to_commitment()).unwrap();

    let foreign_witness = account_tree.open(foreign_account_id);

    // Add account and storage headers to the advice map.
    let account_id_key = AccountIdKey::from(foreign_account_id);
    let leaf = foreign_witness.leaf();
    let advice_inputs = AdviceInputs::default()
        .with_map([
            (account_id_key.as_word(), foreign_header.to_elements().to_vec()),
            (foreign_header.storage_commitment(), foreign_storage_header.to_elements()),
            (leaf.hash(), leaf.to_elements().collect()),
        ])
        .with_merkle_store(foreign_witness.authenticated_nodes().collect());

    let block_header = BlockHeader::mock(0, None, None, &[]);

    let tx_inputs = TransactionInputs {
        account: native_account,
        block_header,
        blockchain: PartialBlockchain::default(),
        input_notes: InputNotes::new(vec![]).unwrap(),
        protocol_config: ProtocolConfig::mock(),
        tx_args: TransactionArgs::default(),
        advice_inputs,
        foreign_account_code: vec![code],
        foreign_account_slot_names: BTreeMap::new(),
    };

    // Test reading foreign account inputs.
    // Should succeed and create proper witness.
    let account_inputs = tx_inputs.read_foreign_account_inputs(foreign_account_id).unwrap();
    assert_eq!(account_inputs.id(), foreign_account_id);
    assert_eq!(account_inputs.account().nonce(), Felt::new_unchecked(5));

    // Verify witness data.
    let witness = account_inputs.witness();
    assert_eq!(witness.id(), foreign_account_id);

    // Verify the witness contains the expected account ID and can compute a root.
    let computed_root = account_inputs.compute_account_root();
    assert!(
        computed_root.is_ok(),
        "Failed to compute account root from witness: {:?}",
        computed_root.err()
    );

    // The computed root should be consistent - we're mainly testing that
    // the witness was properly reconstructed from the Merkle store data.
    let _computed_root_value = computed_root.unwrap();

    // Test that the witness path has the expected depth (64 for SMT).
    assert_eq!(witness.path().depth(), 64, "Witness path should have SMT depth of 64");
}

#[test]
fn test_transaction_inputs_serialization_with_foreign_slot_names() {
    use miden_core::Felt;

    use crate::account::{
        AccountCode,
        AccountId,
        AccountStorageHeader,
        PartialAccount,
        PartialStorage,
        StorageSlotName,
    };
    use crate::asset::PartialVault;
    use crate::testing::account_id::ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE;

    // Create test account IDs
    let native_account_id =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();

    // Create some slot names and IDs.
    let slot_name_1 = StorageSlotName::new("test::slot1::value".to_string()).unwrap();
    let slot_name_2 = StorageSlotName::new("test::slot2::map".to_string()).unwrap();
    let slot_name_3 = StorageSlotName::new("another::slot::value".to_string()).unwrap();

    let slot_id_1 = slot_name_1.id();
    let slot_id_2 = slot_name_2.id();
    let slot_id_3 = slot_name_3.id();

    // Create foreign account slot names map.
    let mut foreign_account_slot_names = BTreeMap::new();
    foreign_account_slot_names.insert(slot_id_1, slot_name_1.clone());
    foreign_account_slot_names.insert(slot_id_2, slot_name_2.clone());
    foreign_account_slot_names.insert(slot_id_3, slot_name_3.clone());

    // Create a basic TransactionInputs with foreign slot names.
    let code = AccountCode::mock();
    let storage_header = AccountStorageHeader::new(vec![]).unwrap();
    let partial_storage = PartialStorage::new(storage_header, []).unwrap();
    let partial_vault = PartialVault::new(Word::default());
    let partial_account = PartialAccount::new(
        native_account_id,
        Felt::new_unchecked(10),
        code,
        partial_storage,
        partial_vault,
        None,
    )
    .unwrap();

    let original_tx_inputs = TransactionInputs {
        account: partial_account,
        block_header: BlockHeader::mock(0, None, None, &[]),
        blockchain: PartialBlockchain::default(),
        input_notes: InputNotes::new(vec![]).unwrap(),
        protocol_config: ProtocolConfig::mock(),
        tx_args: TransactionArgs::default(),
        advice_inputs: AdviceInputs::default(),
        foreign_account_code: Vec::new(),
        foreign_account_slot_names,
    };

    // Test serialization roundtrip.
    let serialized = original_tx_inputs.to_bytes();
    let deserialized = TransactionInputs::read_from_bytes(&serialized).unwrap();

    // Verify that foreign account slot names are preserved.
    assert_eq!(
        original_tx_inputs.foreign_account_slot_names(),
        deserialized.foreign_account_slot_names()
    );

    // Verify specific slot names.
    let deserialized_slots = deserialized.foreign_account_slot_names();

    // Check slots.
    assert_eq!(deserialized_slots.get(&slot_id_1).unwrap(), &slot_name_1);
    assert_eq!(deserialized_slots.get(&slot_id_2).unwrap(), &slot_name_2);
    assert_eq!(deserialized_slots.get(&slot_id_3).unwrap(), &slot_name_3);

    // Verify the entire structure is identical.
    assert_eq!(original_tx_inputs, deserialized);
}

#[test]
fn try_from_parts_preserves_all_transaction_input_components() {
    let account_id = AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
    let code = AccountCode::mock();
    let account = PartialAccount::new(
        account_id,
        Felt::new_unchecked(10),
        code.clone(),
        PartialStorage::new(AccountStorageHeader::new(vec![]).unwrap(), []).unwrap(),
        PartialVault::new(Word::default()),
        None,
    )
    .unwrap();
    let blockchain = PartialBlockchain::default();
    let block_header = BlockHeader::mock(0, Some(blockchain.peaks().hash_peaks()), None, &[]);
    let protocol_config = ProtocolConfig::mock();
    let input_notes = InputNotes::new(vec![]).unwrap();
    let tx_args = TransactionArgs::from_parts(
        None,
        Word::new([Felt::from(1_u32); 4]),
        BTreeMap::new(),
        AdviceInputs::default(),
        Word::new([Felt::from(2_u32); 4]),
    );
    let advice_inputs = AdviceInputs::default()
        .with_map([(Word::new([Felt::from(3_u32); 4]), vec![Felt::from(4_u32)])]);
    let foreign_account_code = vec![code];
    let slot_name = StorageSlotName::new("test::slot::value".to_string()).unwrap();
    let foreign_account_slot_names = BTreeMap::from([(slot_name.id(), slot_name)]);

    let tx_inputs = TransactionInputs::try_from_parts(
        account.clone(),
        block_header.clone(),
        protocol_config.clone(),
        blockchain.clone(),
        input_notes.clone(),
        tx_args.clone(),
        advice_inputs.clone(),
        foreign_account_code.clone(),
        foreign_account_slot_names.clone(),
    )
    .unwrap();

    assert_eq!(tx_inputs.account(), &account);
    assert_eq!(tx_inputs.block_header(), &block_header);
    assert_eq!(tx_inputs.protocol_config(), &protocol_config);
    assert_eq!(tx_inputs.blockchain(), &blockchain);
    assert_eq!(tx_inputs.input_notes(), &input_notes);
    assert_eq!(tx_inputs.tx_args(), &tx_args);
    assert_eq!(tx_inputs.advice_inputs(), &advice_inputs);
    assert_eq!(tx_inputs.foreign_account_code(), foreign_account_code);
    assert_eq!(tx_inputs.foreign_account_slot_names(), &foreign_account_slot_names);
}

#[test]
fn try_from_parts_rejects_an_inconsistent_protocol_config() {
    let account_id = AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE).unwrap();
    let account = PartialAccount::new(
        account_id,
        Felt::new_unchecked(10),
        AccountCode::mock(),
        PartialStorage::new(AccountStorageHeader::new(vec![]).unwrap(), []).unwrap(),
        PartialVault::new(Word::default()),
        None,
    )
    .unwrap();
    let blockchain = PartialBlockchain::default();
    let block_header = BlockHeader::mock(0, Some(blockchain.peaks().hash_peaks()), None, &[]);
    let different_fee_faucet =
        AccountId::try_from(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE_2).unwrap();
    let protocol_config =
        ProtocolConfig::current(crate::asset::AssetId::new_fungible(different_fee_faucet)).unwrap();

    let result = TransactionInputs::try_from_parts(
        account,
        block_header,
        protocol_config,
        blockchain,
        InputNotes::new(vec![]).unwrap(),
        TransactionArgs::default(),
        AdviceInputs::default(),
        Vec::new(),
        BTreeMap::new(),
    );

    assert_matches!(result, Err(TransactionInputError::InconsistentProtocolConfig { .. }));
}