miden-node-ntx-builder 0.14.0-alpha.1

Miden node's network transaction builder component
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! DB-level tests for NTX builder query functions.

use diesel::prelude::*;
use miden_node_proto::domain::account::NetworkAccountId;
use miden_protocol::Word;
use miden_protocol::account::{
    AccountComponentMetadata,
    AccountId,
    AccountStorageMode,
    AccountType,
};
use miden_protocol::block::BlockNumber;
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_REGULAR_NETWORK_ACCOUNT_IMMUTABLE_CODE,
    AccountIdBuilder,
};
use miden_protocol::transaction::TransactionId;
use miden_standards::note::{NetworkAccountTarget, NoteExecutionHint};
use miden_standards::testing::note::NoteBuilder;
use rand_chacha::ChaCha20Rng;
use rand_chacha::rand_core::SeedableRng;

use super::*;
use crate::db::models::conv as conversions;
use crate::db::{Db, schema};

// TEST HELPERS
// ================================================================================================

/// Creates a file-backed SQLite connection with migrations applied.
fn test_conn() -> (SqliteConnection, tempfile::TempDir) {
    Db::test_conn()
}

/// Creates a network account ID from a test constant.
fn mock_network_account_id() -> NetworkAccountId {
    let account_id: AccountId =
        ACCOUNT_ID_REGULAR_NETWORK_ACCOUNT_IMMUTABLE_CODE.try_into().unwrap();
    NetworkAccountId::try_from(account_id).unwrap()
}

/// Creates a distinct network account ID using a seeded RNG.
fn mock_network_account_id_seeded(seed: u8) -> NetworkAccountId {
    let account_id = AccountIdBuilder::new()
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Network)
        .build_with_seed([seed; 32]);
    NetworkAccountId::try_from(account_id).unwrap()
}

/// Creates a unique `TransactionId` from a seed value.
fn mock_tx_id(seed: u64) -> TransactionId {
    let w = |n: u64| Word::try_from([n, 0, 0, 0]).unwrap();
    TransactionId::new(w(seed), w(seed + 1), w(seed + 2), w(seed + 3))
}

/// Creates a `SingleTargetNetworkNote` targeting the given network account.
fn mock_single_target_note(
    network_account_id: NetworkAccountId,
    seed: u8,
) -> AccountTargetNetworkNote {
    let mut rng = ChaCha20Rng::from_seed([seed; 32]);
    let sender = AccountIdBuilder::new()
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Private)
        .build_with_rng(&mut rng);

    let target = NetworkAccountTarget::new(network_account_id.inner(), NoteExecutionHint::Always)
        .expect("network account should be valid target");

    let note = NoteBuilder::new(sender, rng).attachment(target).build().unwrap();

    AccountTargetNetworkNote::new(note).expect("note should be single-target network note")
}

/// Counts the total number of rows in the `notes` table.
fn count_notes(conn: &mut SqliteConnection) -> i64 {
    schema::notes::table.count().get_result(conn).unwrap()
}

/// Counts the total number of rows in the `accounts` table.
fn count_accounts(conn: &mut SqliteConnection) -> i64 {
    schema::accounts::table.count().get_result(conn).unwrap()
}

/// Counts inflight account rows.
fn count_inflight_accounts(conn: &mut SqliteConnection) -> i64 {
    schema::accounts::table
        .filter(schema::accounts::transaction_id.is_not_null())
        .count()
        .get_result(conn)
        .unwrap()
}

/// Counts committed account rows.
fn count_committed_accounts(conn: &mut SqliteConnection) -> i64 {
    schema::accounts::table
        .filter(schema::accounts::transaction_id.is_null())
        .count()
        .get_result(conn)
        .unwrap()
}

// PURGE INFLIGHT TESTS
// ================================================================================================

#[test]
fn purge_inflight_clears_all_inflight_state() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let tx_id = mock_tx_id(1);
    let note = mock_single_target_note(account_id, 10);

    // Insert committed account.
    upsert_committed_account(conn, account_id, &mock_account(account_id)).unwrap();

    // Insert a transaction (creates inflight account row + note + consumption).
    add_transaction(conn, &tx_id, None, std::slice::from_ref(&note), &[]).unwrap();

    assert!(count_inflight_accounts(conn) == 0); // No account delta, so no inflight account.
    assert_eq!(count_notes(conn), 1);

    // Mark note as consumed by another tx.
    let tx_id2 = mock_tx_id(2);
    add_transaction(conn, &tx_id2, None, &[], &[note.as_note().nullifier()]).unwrap();

    // Verify consumed_by is set.
    let consumed_count: i64 = schema::notes::table
        .filter(schema::notes::consumed_by.is_not_null())
        .count()
        .get_result(conn)
        .unwrap();
    assert_eq!(consumed_count, 1);

    // Purge inflight state.
    purge_inflight(conn).unwrap();

    // Inflight accounts should be gone.
    assert_eq!(count_inflight_accounts(conn), 0);
    // Committed account should remain.
    assert_eq!(count_committed_accounts(conn), 1);
    // Inflight-created notes should be gone.
    assert_eq!(count_notes(conn), 0);
}

// HANDLE TRANSACTION ADDED TESTS
// ================================================================================================

#[test]
fn transaction_added_inserts_notes_and_marks_consumed() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let tx_id = mock_tx_id(1);
    let note1 = mock_single_target_note(account_id, 10);
    let note2 = mock_single_target_note(account_id, 20);

    // Insert committed note first (to test consumption).
    insert_committed_notes(conn, std::slice::from_ref(&note1)).unwrap();
    assert_eq!(count_notes(conn), 1);

    // Add transaction that creates note2 and consumes note1.
    add_transaction(
        conn,
        &tx_id,
        None,
        std::slice::from_ref(&note2),
        &[note1.as_note().nullifier()],
    )
    .unwrap();

    // Should now have 2 notes total.
    assert_eq!(count_notes(conn), 2);

    // note1 should be consumed.
    let consumed: Option<Vec<u8>> = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note1.as_note().nullifier()))
        .select(schema::notes::consumed_by)
        .first(conn)
        .unwrap();
    assert!(consumed.is_some());

    // note2 should have created_by set.
    let created: Option<Vec<u8>> = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note2.as_note().nullifier()))
        .select(schema::notes::created_by)
        .first(conn)
        .unwrap();
    assert!(created.is_some());
}

#[test]
fn transaction_added_is_idempotent_for_notes() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let tx_id = mock_tx_id(1);
    let note = mock_single_target_note(account_id, 10);

    // Insert the same transaction twice.
    add_transaction(conn, &tx_id, None, std::slice::from_ref(&note), &[]).unwrap();
    add_transaction(conn, &tx_id, None, std::slice::from_ref(&note), &[]).unwrap();

    // Should only have one note (INSERT OR IGNORE).
    assert_eq!(count_notes(conn), 1);
}

// HANDLE BLOCK COMMITTED TESTS
// ================================================================================================

#[test]
fn block_committed_promotes_inflight_notes_to_committed() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let tx_id = mock_tx_id(1);
    let note = mock_single_target_note(account_id, 10);
    let block_num = BlockNumber::from(1u32);
    let header = mock_block_header(block_num);

    // Add a transaction that creates a note.
    add_transaction(conn, &tx_id, None, std::slice::from_ref(&note), &[]).unwrap();

    // Verify created_by is set.
    let created: Option<Vec<u8>> = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note.as_note().nullifier()))
        .select(schema::notes::created_by)
        .first(conn)
        .unwrap();
    assert!(created.is_some());

    // Commit the block.
    commit_block(conn, &[tx_id], block_num, &header).unwrap();

    // created_by should now be NULL (promoted to committed).
    let created: Option<Vec<u8>> = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note.as_note().nullifier()))
        .select(schema::notes::created_by)
        .first(conn)
        .unwrap();
    assert!(created.is_none());
}

#[test]
fn block_committed_deletes_consumed_notes() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let note = mock_single_target_note(account_id, 10);

    // Insert a committed note.
    insert_committed_notes(conn, std::slice::from_ref(&note)).unwrap();
    assert_eq!(count_notes(conn), 1);

    // Consume it via a transaction.
    let tx_id = mock_tx_id(1);
    add_transaction(conn, &tx_id, None, &[], &[note.as_note().nullifier()]).unwrap();

    // Commit the block.
    let block_num = BlockNumber::from(1u32);
    let header = mock_block_header(block_num);
    commit_block(conn, &[tx_id], block_num, &header).unwrap();

    // Consumed note should be deleted.
    assert_eq!(count_notes(conn), 0);
}

#[test]
fn block_committed_promotes_inflight_account_to_committed() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let account = mock_account(account_id);

    // Insert committed account.
    upsert_committed_account(conn, account_id, &account).unwrap();
    assert_eq!(count_committed_accounts(conn), 1);

    // Insert inflight row.
    let tx_id = mock_tx_id(1);
    let row = AccountInsert {
        account_id: conversions::network_account_id_to_bytes(account_id),
        transaction_id: Some(conversions::transaction_id_to_bytes(&tx_id)),
        account_data: conversions::account_to_bytes(&account),
    };
    diesel::insert_into(schema::accounts::table).values(&row).execute(conn).unwrap();

    assert_eq!(count_inflight_accounts(conn), 1);
    assert_eq!(count_committed_accounts(conn), 1);

    // Commit the block.
    let block_num = BlockNumber::from(1u32);
    let header = mock_block_header(block_num);
    commit_block(conn, &[tx_id], block_num, &header).unwrap();

    // Should have 1 committed and 0 inflight.
    assert_eq!(count_committed_accounts(conn), 1);
    assert_eq!(count_inflight_accounts(conn), 0);
}

// HANDLE TRANSACTIONS REVERTED TESTS
// ================================================================================================

#[test]
fn transactions_reverted_restores_consumed_notes() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let note = mock_single_target_note(account_id, 10);

    // Insert committed note.
    insert_committed_notes(conn, std::slice::from_ref(&note)).unwrap();

    // Consume it via a transaction.
    let tx_id = mock_tx_id(1);
    add_transaction(conn, &tx_id, None, &[], &[note.as_note().nullifier()]).unwrap();

    // Verify consumed.
    let consumed: Option<Vec<u8>> = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note.as_note().nullifier()))
        .select(schema::notes::consumed_by)
        .first(conn)
        .unwrap();
    assert!(consumed.is_some());

    // Revert the transaction.
    let reverted = revert_transaction(conn, &[tx_id]).unwrap();
    assert!(reverted.is_empty());

    // Note should be un-consumed.
    let consumed: Option<Vec<u8>> = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note.as_note().nullifier()))
        .select(schema::notes::consumed_by)
        .first(conn)
        .unwrap();
    assert!(consumed.is_none());
}

#[test]
fn transactions_reverted_deletes_inflight_created_notes() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let tx_id = mock_tx_id(1);
    let note = mock_single_target_note(account_id, 10);

    // Add transaction that creates a note.
    add_transaction(conn, &tx_id, None, std::slice::from_ref(&note), &[]).unwrap();
    assert_eq!(count_notes(conn), 1);

    // Revert the transaction.
    revert_transaction(conn, &[tx_id]).unwrap();

    // Inflight-created note should be deleted.
    assert_eq!(count_notes(conn), 0);
}

#[test]
fn transactions_reverted_reports_reverted_account_creations() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let account = mock_account(account_id);
    let tx_id = mock_tx_id(1);

    // Insert an inflight account row (simulating account creation by tx).
    let row = AccountInsert {
        account_id: conversions::network_account_id_to_bytes(account_id),
        transaction_id: Some(conversions::transaction_id_to_bytes(&tx_id)),
        account_data: conversions::account_to_bytes(&account),
    };
    diesel::insert_into(schema::accounts::table).values(&row).execute(conn).unwrap();

    // Revert the transaction --- account creation should be reported.
    let reverted = revert_transaction(conn, &[tx_id]).unwrap();
    assert_eq!(reverted.len(), 1);
    assert_eq!(reverted[0], account_id);

    // Account should be gone.
    assert_eq!(count_accounts(conn), 0);
}

// AVAILABLE NOTES TESTS
// ================================================================================================

#[test]
fn available_notes_filters_consumed_and_exceeded_attempts() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let note_good = mock_single_target_note(account_id, 10);
    let note_consumed = mock_single_target_note(account_id, 20);
    let note_failed = mock_single_target_note(account_id, 30);

    // Insert all as committed.
    insert_committed_notes(conn, &[note_good.clone(), note_consumed.clone(), note_failed.clone()])
        .unwrap();

    // Consume one note.
    let tx_id = mock_tx_id(1);
    add_transaction(conn, &tx_id, None, &[], &[note_consumed.as_note().nullifier()]).unwrap();

    // Mark one note as failed many times (exceed max_attempts=3).
    let block_num = BlockNumber::from(100u32);
    notes_failed(conn, &[note_failed.as_note().nullifier()], block_num).unwrap();
    notes_failed(conn, &[note_failed.as_note().nullifier()], block_num).unwrap();
    notes_failed(conn, &[note_failed.as_note().nullifier()], block_num).unwrap();

    // Query available notes with max_attempts=3.
    let result = available_notes(conn, account_id, block_num, 3).unwrap();

    // Only note_good should be available (note_consumed is consumed, note_failed exceeded
    // attempts).
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].nullifier(), note_good.as_note().nullifier());
}

#[test]
fn available_notes_only_returns_notes_for_specified_account() {
    let (conn, _dir) = &mut test_conn();

    let account_id_1 = mock_network_account_id();
    let account_id_2 = mock_network_account_id_seeded(42);

    let note_acct1 = mock_single_target_note(account_id_1, 10);
    let note_acct2 = mock_single_target_note(account_id_2, 20);

    insert_committed_notes(conn, &[note_acct1.clone(), note_acct2]).unwrap();

    let block_num = BlockNumber::from(100u32);
    let result = available_notes(conn, account_id_1, block_num, 30).unwrap();

    assert_eq!(result.len(), 1);
    assert_eq!(result[0].nullifier(), note_acct1.as_note().nullifier());
}

// NOTES FAILED TESTS
// ================================================================================================

#[test]
fn notes_failed_increments_attempt_count() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let note = mock_single_target_note(account_id, 10);

    insert_committed_notes(conn, std::slice::from_ref(&note)).unwrap();

    let block_num = BlockNumber::from(5u32);
    notes_failed(conn, &[note.as_note().nullifier()], block_num).unwrap();
    notes_failed(conn, &[note.as_note().nullifier()], block_num).unwrap();

    let (attempt_count, last_attempt): (i32, Option<i64>) = schema::notes::table
        .find(conversions::nullifier_to_bytes(&note.as_note().nullifier()))
        .select((schema::notes::attempt_count, schema::notes::last_attempt))
        .first(conn)
        .unwrap();

    assert_eq!(attempt_count, 2);
    assert_eq!(last_attempt, Some(conversions::block_num_to_i64(block_num)));
}

// CHAIN STATE TESTS
// ================================================================================================

#[test]
fn upsert_chain_state_updates_singleton() {
    let (conn, _dir) = &mut test_conn();

    let block_num_1 = BlockNumber::from(1u32);
    let header_1 = mock_block_header(block_num_1);
    upsert_chain_state(conn, block_num_1, &header_1).unwrap();

    // Upsert again with higher block.
    let block_num_2 = BlockNumber::from(2u32);
    let header_2 = mock_block_header(block_num_2);
    upsert_chain_state(conn, block_num_2, &header_2).unwrap();

    // Should only have one row.
    let row_count: i64 = schema::chain_state::table.count().get_result(conn).unwrap();
    assert_eq!(row_count, 1);

    // Should have the latest block number.
    let stored_block_num: i64 = schema::chain_state::table
        .select(schema::chain_state::block_num)
        .first(conn)
        .unwrap();
    assert_eq!(stored_block_num, conversions::block_num_to_i64(block_num_2));
}

// NOTE SCRIPT TESTS
// ================================================================================================

#[test]
fn note_script_insert_and_lookup() {
    let (conn, _dir) = &mut test_conn();

    // Extract a NoteScript from a mock note.
    let account_id = mock_network_account_id();
    let note: miden_protocol::note::Note = mock_single_target_note(account_id, 10).into_note();
    let script = note.script().clone();
    let root = script.root();

    // Insert the script.
    insert_note_script(conn, &root, &script).unwrap();

    // Look it up — should match the original.
    let found = lookup_note_script(conn, &root).unwrap();
    assert!(found.is_some());
    assert_eq!(found.unwrap().root(), script.root());
}

#[test]
fn note_script_lookup_returns_none_for_missing() {
    let (conn, _dir) = &mut test_conn();

    let missing_root = Word::default();
    let found = lookup_note_script(conn, &missing_root).unwrap();
    assert!(found.is_none());
}

#[test]
fn note_script_insert_is_idempotent() {
    let (conn, _dir) = &mut test_conn();

    let account_id = mock_network_account_id();
    let note: miden_protocol::note::Note = mock_single_target_note(account_id, 10).into_note();
    let script = note.script().clone();
    let root = script.root();

    // Insert the same script twice — should not error.
    insert_note_script(conn, &root, &script).unwrap();
    insert_note_script(conn, &root, &script).unwrap();

    // Should still be retrievable.
    let found = lookup_note_script(conn, &root).unwrap();
    assert!(found.is_some());
}

// HELPERS (domain type construction)
// ================================================================================================

/// Creates a mock `Account` for a network account.
///
/// Uses `AccountBuilder` with minimal components needed for serialization.
fn mock_account(_account_id: NetworkAccountId) -> miden_protocol::account::Account {
    use miden_protocol::account::auth::{AuthScheme, PublicKeyCommitment};
    use miden_protocol::account::{AccountBuilder, AccountComponent};
    use miden_standards::account::auth::AuthSingleSig;

    let component_code = miden_standards::code_builder::CodeBuilder::default()
        .compile_component_code("test::interface", "pub proc test_proc push.1.2 add end")
        .unwrap();

    let component = AccountComponent::new(
        component_code,
        vec![],
        AccountComponentMetadata::mock("test").with_supports_all_types(),
    )
    .unwrap();

    AccountBuilder::new([0u8; 32])
        .account_type(AccountType::RegularAccountImmutableCode)
        .storage_mode(AccountStorageMode::Network)
        .with_component(component)
        .with_auth_component(AuthSingleSig::new(
            PublicKeyCommitment::from(Word::default()),
            AuthScheme::Falcon512Rpo,
        ))
        .build_existing()
        .unwrap()
}

/// Creates a mock `BlockHeader` for the given block number.
fn mock_block_header(block_num: BlockNumber) -> miden_protocol::block::BlockHeader {
    miden_protocol::block::BlockHeader::mock(block_num, None, None, &[], Word::default())
}