miden-testing 0.14.6

Miden protocol testing tools
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
use miden_processor::advice::AdviceInputs;
use miden_processor::crypto::random::RandomCoin;
use miden_protocol::account::auth::{AuthScheme, AuthSecretKey, PublicKey};
use miden_protocol::account::{
    Account,
    AccountBuilder,
    AccountId,
    AccountStorageMode,
    AccountType,
};
use miden_protocol::asset::FungibleAsset;
use miden_protocol::note::NoteType;
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE,
};
use miden_protocol::transaction::RawOutputNote;
use miden_protocol::vm::AdviceMap;
use miden_protocol::{Felt, Hasher, Word};
use miden_standards::account::auth::AuthMultisig;
use miden_standards::account::components::multisig_library;
use miden_standards::account::interface::{AccountInterface, AccountInterfaceExt};
use miden_standards::account::wallets::BasicWallet;
use miden_standards::code_builder::CodeBuilder;
use miden_standards::errors::standards::{
    ERR_PROC_THRESHOLD_EXCEEDS_NUM_APPROVERS,
    ERR_TX_ALREADY_EXECUTED,
};
use miden_standards::note::P2idNote;
use miden_standards::testing::account_interface::get_public_keys_from_account;
use miden_testing::utils::create_spawn_note;
use miden_testing::{Auth, MockChainBuilder, assert_transaction_executor_error};
use miden_tx::TransactionExecutorError;
use miden_tx::auth::{BasicAuthenticator, SigningInputs, TransactionAuthenticator};
use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;
use rstest::rstest;

// ================================================================================================
// HELPER FUNCTIONS
// ================================================================================================

type MultisigTestSetup =
    (Vec<AuthSecretKey>, Vec<AuthScheme>, Vec<PublicKey>, Vec<BasicAuthenticator>);

/// Sets up secret keys, public keys, and authenticators for multisig testing for the given scheme.
fn setup_keys_and_authenticators_with_scheme(
    num_approvers: usize,
    threshold: usize,
    auth_scheme: AuthScheme,
) -> anyhow::Result<MultisigTestSetup> {
    let seed: [u8; 32] = rand::random();
    let mut rng = ChaCha20Rng::from_seed(seed);

    let mut secret_keys = Vec::new();
    let mut auth_schemes = Vec::new();
    let mut public_keys = Vec::new();
    let mut authenticators = Vec::new();

    for _ in 0..num_approvers {
        let sec_key = match auth_scheme {
            AuthScheme::EcdsaK256Keccak => AuthSecretKey::new_ecdsa_k256_keccak_with_rng(&mut rng),
            AuthScheme::Falcon512Poseidon2 => {
                AuthSecretKey::new_falcon512_poseidon2_with_rng(&mut rng)
            },
            _ => anyhow::bail!("unsupported auth scheme for this test: {auth_scheme:?}"),
        };
        let pub_key = sec_key.public_key();

        secret_keys.push(sec_key);
        auth_schemes.push(auth_scheme);
        public_keys.push(pub_key);
    }

    // Create authenticators for required signers
    for secret_key in secret_keys.iter().take(threshold) {
        let authenticator = BasicAuthenticator::new(core::slice::from_ref(secret_key));
        authenticators.push(authenticator);
    }

    Ok((secret_keys, auth_schemes, public_keys, authenticators))
}

/// Creates a multisig account with the specified configuration
fn create_multisig_account(
    threshold: u32,
    approvers: &[(PublicKey, AuthScheme)],
    asset_amount: u64,
    proc_threshold_map: Vec<(Word, u32)>,
) -> anyhow::Result<Account> {
    let approvers = approvers
        .iter()
        .map(|(pub_key, auth_scheme)| (pub_key.to_commitment(), *auth_scheme))
        .collect();

    let multisig_account = AccountBuilder::new([0; 32])
        .with_auth_component(Auth::Multisig { threshold, approvers, proc_threshold_map })
        .with_component(BasicWallet)
        .account_type(AccountType::RegularAccountUpdatableCode)
        .storage_mode(AccountStorageMode::Public)
        .with_assets(vec![FungibleAsset::mock(asset_amount)])
        .build_existing()?;

    Ok(multisig_account)
}

// ================================================================================================
// TESTS
// ================================================================================================

/// Tests basic 2-of-2 multisig functionality with note creation.
///
/// This test verifies that a multisig account with 2 approvers and threshold 2
/// can successfully execute a transaction that creates an output note when both
/// required signatures are provided.
///
/// **Roles:**
/// - 2 Approvers (multisig signers)
/// - 1 Multisig Contract
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_2_of_2_with_note_creation(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    // Setup keys and authenticators
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(2, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    // Create multisig account
    let multisig_starting_balance = 10u64;
    let mut multisig_account =
        create_multisig_account(2, &approvers, multisig_starting_balance, vec![])?;

    let output_note_asset = FungibleAsset::mock(0);

    let mut mock_chain_builder =
        MockChainBuilder::with_accounts([multisig_account.clone()]).unwrap();

    // Create output note for spawn note
    let output_note = mock_chain_builder.add_p2id_note(
        multisig_account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE.try_into().unwrap(),
        &[output_note_asset],
        NoteType::Public,
    )?;

    // Create spawn note to generate the output note
    let input_note = mock_chain_builder.add_spawn_note([&output_note])?;

    let mut mock_chain = mock_chain_builder.build().unwrap();

    let salt = Word::from([Felt::new(1); 4]);

    // Execute transaction without signatures - should fail
    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[input_note.id()], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note.clone())])
        .auth_args(salt)
        .build()?;

    let tx_summary = match tx_context_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => anyhow::bail!("expected abort with tx effects: {error}"),
    };

    // Get signatures from both approvers
    let msg = tx_summary.as_ref().to_commitment();
    let tx_summary = SigningInputs::TransactionSummary(tx_summary);

    let sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary)
        .await?;
    let sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &tx_summary)
        .await?;

    // Execute transaction with signatures - should succeed
    let tx_context_execute = mock_chain
        .build_tx_context(multisig_account.id(), &[input_note.id()], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note)])
        .add_signature(public_keys[0].to_commitment(), msg, sig_1)
        .add_signature(public_keys[1].to_commitment(), msg, sig_2)
        .auth_args(salt)
        .build()?
        .execute()
        .await?;

    multisig_account.apply_delta(tx_context_execute.account_delta())?;

    mock_chain.add_pending_executed_transaction(&tx_context_execute)?;
    mock_chain.prove_next_block()?;

    assert_eq!(
        multisig_account
            .vault()
            .get_balance(AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET)?)?,
        multisig_starting_balance - output_note_asset.unwrap_fungible().amount()
    );

    Ok(())
}

/// Tests 2-of-4 multisig with all possible signer combinations.
///
/// This test verifies that a multisig account with 4 approvers and threshold 2
/// can successfully execute transactions when signed by any 2 of the 4 approvers.
/// It tests all 6 possible combinations of 2 signers to ensure the multisig
/// implementation correctly validates signatures from any valid subset.
///
/// **Tested combinations:** (0,1), (0,2), (0,3), (1,2), (1,3), (2,3)
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_2_of_4_all_signer_combinations(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    // Setup keys and authenticators (4 approvers, all 4 can sign)
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(4, 4, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    // Create multisig account with 4 approvers but threshold of 2
    let multisig_account = create_multisig_account(2, &approvers, 10, vec![])?;

    let mut mock_chain = MockChainBuilder::with_accounts([multisig_account.clone()])
        .unwrap()
        .build()
        .unwrap();

    // Test different combinations of 2 signers out of 4
    let signer_combinations = [
        (0, 1), // First two
        (0, 2), // First and third
        (0, 3), // First and fourth
        (1, 2), // Second and third
        (1, 3), // Second and fourth
        (2, 3), // Last two
    ];

    for (i, (signer1_idx, signer2_idx)) in signer_combinations.iter().enumerate() {
        let salt = Word::from([Felt::new(10 + i as u64); 4]);

        // Execute transaction without signatures first to get tx summary
        let tx_context_init = mock_chain
            .build_tx_context(multisig_account.id(), &[], &[])?
            .auth_args(salt)
            .build()?;

        let tx_summary = match tx_context_init.execute().await.unwrap_err() {
            TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
            error => anyhow::bail!("expected abort with tx effects: {error}"),
        };

        // Get signatures from the specific combination of signers
        let msg = tx_summary.as_ref().to_commitment();
        let tx_summary = SigningInputs::TransactionSummary(tx_summary);

        let sig_1 = authenticators[*signer1_idx]
            .get_signature(public_keys[*signer1_idx].to_commitment(), &tx_summary)
            .await?;
        let sig_2 = authenticators[*signer2_idx]
            .get_signature(public_keys[*signer2_idx].to_commitment(), &tx_summary)
            .await?;

        // Execute transaction with signatures - should succeed for any combination
        let tx_context_execute = mock_chain
            .build_tx_context(multisig_account.id(), &[], &[])?
            .auth_args(salt)
            .add_signature(public_keys[*signer1_idx].to_commitment(), msg, sig_1)
            .add_signature(public_keys[*signer2_idx].to_commitment(), msg, sig_2)
            .build()?;

        let executed_tx = tx_context_execute.execute().await.unwrap_or_else(|_| {
            panic!("Transaction should succeed with signers {signer1_idx} and {signer2_idx}")
        });

        // Apply the transaction to the mock chain for the next iteration
        mock_chain.add_pending_executed_transaction(&executed_tx)?;
        mock_chain.prove_next_block()?;
    }

    Ok(())
}

/// Tests multisig replay protection to prevent transaction re-execution.
///
/// This test verifies that a 2-of-3 multisig account properly prevents replay attacks
/// by rejecting attempts to execute the same transaction twice. The first execution
/// should succeed with valid signatures, but the second attempt with identical
/// parameters should fail with ERR_TX_ALREADY_EXECUTED.
///
/// **Roles:**
/// - 3 Approvers (2 signers required)
/// - 1 Multisig Contract
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_replay_protection(#[case] auth_scheme: AuthScheme) -> anyhow::Result<()> {
    // Setup keys and authenticators (3 approvers, but only 2 signers)
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(3, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    // Create 2/3 multisig account
    let multisig_account = create_multisig_account(2, &approvers, 20, vec![])?;

    let mut mock_chain = MockChainBuilder::with_accounts([multisig_account.clone()])
        .unwrap()
        .build()
        .unwrap();

    let salt = Word::from([Felt::new(3); 4]);

    // Execute transaction without signatures first to get tx summary
    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .auth_args(salt)
        .build()?;

    let tx_summary = match tx_context_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };

    // Get signatures from 2 of the 3 approvers
    let msg = tx_summary.as_ref().to_commitment();
    let tx_summary = SigningInputs::TransactionSummary(tx_summary);

    let sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary)
        .await?;
    let sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &tx_summary)
        .await?;

    // Execute transaction with signatures - should succeed (first execution)
    let tx_context_execute = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .add_signature(public_keys[0].to_commitment(), msg, sig_1.clone())
        .add_signature(public_keys[1].to_commitment(), msg, sig_2.clone())
        .auth_args(salt)
        .build()?
        .execute()
        .await?;

    // Apply the transaction to the mock chain
    mock_chain.add_pending_executed_transaction(&tx_context_execute)?;
    mock_chain.prove_next_block()?;

    // Attempt to execute the same transaction again - should fail due to replay protection
    let tx_context_replay = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .add_signature(public_keys[0].to_commitment(), msg, sig_1)
        .add_signature(public_keys[1].to_commitment(), msg, sig_2)
        .auth_args(salt)
        .build()?;

    // This should fail due to replay protection
    let result = tx_context_replay.execute().await;
    assert_transaction_executor_error!(result, ERR_TX_ALREADY_EXECUTED);

    Ok(())
}

/// Tests multisig signer update functionality.
///
/// This test verifies that a multisig account can:
/// 1. Execute a transaction script to update signers and threshold
/// 2. Create a second transaction signed by the new owners
/// 3. Properly handle multisig authentication with the updated signers
///
/// **Roles:**
/// - 2 Original Approvers (multisig signers)
/// - 4 New Approvers (updated multisig signers)
/// - 1 Multisig Contract
/// - 1 Transaction Script calling multisig procedures
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_update_signers(#[case] auth_scheme: AuthScheme) -> anyhow::Result<()> {
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(2, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    let multisig_account = create_multisig_account(2, &approvers, 10, vec![])?;

    // SECTION 1: Execute a transaction script to update signers and threshold
    // ================================================================================

    let mut mock_chain_builder =
        MockChainBuilder::with_accounts([multisig_account.clone()]).unwrap();

    let output_note_asset = FungibleAsset::mock(0);

    // Create output note for spawn note
    let output_note = mock_chain_builder.add_p2id_note(
        multisig_account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE.try_into().unwrap(),
        &[output_note_asset],
        NoteType::Public,
    )?;

    let mut mock_chain = mock_chain_builder.clone().build().unwrap();

    let salt = Word::from([Felt::new(3); 4]);

    // Setup new signers
    let mut advice_map = AdviceMap::default();
    let (_new_secret_keys, _new_auth_schemes, new_public_keys, _new_authenticators) =
        setup_keys_and_authenticators_with_scheme(4, 4, auth_scheme)?;

    let threshold = 3u64;
    let num_of_approvers = 4u64;

    // Create vector with threshold config and public keys (4 field elements each)
    let mut config_and_pubkeys_vector = Vec::new();
    config_and_pubkeys_vector.extend_from_slice(&[
        Felt::new(threshold),
        Felt::new(num_of_approvers),
        Felt::new(0),
        Felt::new(0),
    ]);

    // Add each public key to the vector
    for public_key in new_public_keys.iter().rev() {
        let key_word: Word = public_key.to_commitment().into();
        config_and_pubkeys_vector.extend_from_slice(key_word.as_elements());

        config_and_pubkeys_vector.extend_from_slice(&[
            Felt::new(auth_scheme as u64),
            Felt::new(0),
            Felt::new(0),
            Felt::new(0),
        ]);
    }

    // Hash the vector to create config hash
    let multisig_config_hash = Hasher::hash_elements(&config_and_pubkeys_vector);

    // Insert config and public keys into advice map
    advice_map.insert(multisig_config_hash, config_and_pubkeys_vector);

    // Create a transaction script that calls the update_signers procedure
    let tx_script_code = "
        begin
            call.::miden::standards::components::auth::multisig::update_signers_and_threshold
        end
    ";

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script(tx_script_code)?;

    let advice_inputs = AdviceInputs {
        map: advice_map.clone(),
        ..Default::default()
    };

    // Pass the MULTISIG_CONFIG_HASH as the tx_script_args
    let tx_script_args: Word = multisig_config_hash;

    // Execute transaction without signatures first to get tx summary
    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script.clone())
        .tx_script_args(tx_script_args)
        .extend_advice_inputs(advice_inputs.clone())
        .auth_args(salt)
        .build()?;

    let tx_summary = match tx_context_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };

    // Get signatures from both approvers
    let msg = tx_summary.as_ref().to_commitment();
    let tx_summary = SigningInputs::TransactionSummary(tx_summary);

    let sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary)
        .await?;
    let sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &tx_summary)
        .await?;

    // Execute transaction with signatures - should succeed
    let update_approvers_tx = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script)
        .tx_script_args(multisig_config_hash)
        .add_signature(public_keys[0].to_commitment(), msg, sig_1)
        .add_signature(public_keys[1].to_commitment(), msg, sig_2)
        .auth_args(salt)
        .extend_advice_inputs(advice_inputs)
        .build()?
        .execute()
        .await?;

    // Verify the transaction executed successfully
    assert_eq!(update_approvers_tx.account_delta().nonce_delta(), Felt::new(1));

    mock_chain.add_pending_executed_transaction(&update_approvers_tx)?;
    mock_chain.prove_next_block()?;

    // Apply the delta to get the updated account with new signers
    let mut updated_multisig_account = multisig_account.clone();
    updated_multisig_account.apply_delta(update_approvers_tx.account_delta())?;

    // Verify that the public keys were actually updated in storage
    for (i, expected_key) in new_public_keys.iter().enumerate() {
        let storage_key = [Felt::new(i as u64), Felt::new(0), Felt::new(0), Felt::new(0)].into();
        let storage_item = updated_multisig_account
            .storage()
            .get_map_item(AuthMultisig::approver_public_keys_slot(), storage_key)
            .unwrap();

        let expected_word: Word = expected_key.to_commitment().into();

        assert_eq!(storage_item, expected_word, "Public key {} doesn't match expected value", i);
    }

    // Verify the threshold was updated by checking the config storage slot
    let threshold_config_storage = updated_multisig_account
        .storage()
        .get_item(AuthMultisig::threshold_config_slot())
        .unwrap();

    assert_eq!(
        threshold_config_storage[0],
        Felt::new(threshold),
        "Threshold was not updated correctly"
    );
    assert_eq!(
        threshold_config_storage[1],
        Felt::new(num_of_approvers),
        "Num approvers was not updated correctly"
    );

    // Extract public keys using the interface function
    let extracted_pub_keys = get_public_keys_from_account(&updated_multisig_account);

    // Verify that we have the expected number of public keys (4 new ones)
    assert_eq!(
        extracted_pub_keys.len(),
        4,
        "get_public_keys_from_account should return 4 public keys after update"
    );

    // Verify that the extracted public keys match the new ones we set
    for (i, expected_key) in new_public_keys.iter().enumerate() {
        let expected_word: Word = expected_key.to_commitment().into();

        // Find the matching key in extracted keys (order might be different)
        let found_key = extracted_pub_keys.iter().find(|&key| *key == expected_word);

        assert!(
            found_key.is_some(),
            "Public key {} not found in extracted keys: expected {:?}, got {:?}",
            i,
            expected_word,
            extracted_pub_keys
        );
    }

    // SECTION 2: Create a second transaction signed by the new owners
    // ================================================================================

    // Now test creating a note with the new signers
    // Setup authenticators for the new signers (we need 3 out of 4 for threshold 3)
    let mut new_authenticators = Vec::new();
    for secret_key in _new_secret_keys.iter().take(3) {
        let authenticator = BasicAuthenticator::new(core::slice::from_ref(secret_key));
        new_authenticators.push(authenticator);
    }

    // Create a new output note for the second transaction with new signers
    let output_note_new = P2idNote::create(
        updated_multisig_account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE.try_into().unwrap(),
        vec![output_note_asset],
        NoteType::Public,
        Default::default(),
        &mut RandomCoin::new(Word::empty()),
    )?;

    // Create a new spawn note for the second transaction
    let input_note_new = create_spawn_note([&output_note_new])?;

    let salt_new = Word::from([Felt::new(4); 4]);

    // Build the new mock chain with the updated account and notes
    let mut new_mock_chain_builder =
        MockChainBuilder::with_accounts([updated_multisig_account.clone()]).unwrap();
    new_mock_chain_builder.add_output_note(RawOutputNote::Full(input_note_new.clone()));
    let new_mock_chain = new_mock_chain_builder.build().unwrap();

    // Execute transaction without signatures first to get tx summary
    let tx_context_init_new = new_mock_chain
        .build_tx_context(updated_multisig_account.id(), &[input_note_new.id()], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note.clone())])
        .auth_args(salt_new)
        .build()?;

    let tx_summary_new = match tx_context_init_new.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };

    // Get signatures from 3 of the 4 new approvers (threshold is 3)
    let msg_new = tx_summary_new.as_ref().to_commitment();
    let tx_summary_new = SigningInputs::TransactionSummary(tx_summary_new);

    let sig_1_new = new_authenticators[0]
        .get_signature(new_public_keys[0].to_commitment(), &tx_summary_new)
        .await?;
    let sig_2_new = new_authenticators[1]
        .get_signature(new_public_keys[1].to_commitment(), &tx_summary_new)
        .await?;
    let sig_3_new = new_authenticators[2]
        .get_signature(new_public_keys[2].to_commitment(), &tx_summary_new)
        .await?;

    // SECTION 3: Properly handle multisig authentication with the updated signers
    // ================================================================================

    // Execute transaction with new signatures - should succeed
    let tx_context_execute_new = new_mock_chain
        .build_tx_context(updated_multisig_account.id(), &[input_note_new.id()], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note_new)])
        .add_signature(new_public_keys[0].to_commitment(), msg_new, sig_1_new)
        .add_signature(new_public_keys[1].to_commitment(), msg_new, sig_2_new)
        .add_signature(new_public_keys[2].to_commitment(), msg_new, sig_3_new)
        .auth_args(salt_new)
        .build()?
        .execute()
        .await?;

    // Verify the transaction executed successfully with new signers
    assert_eq!(tx_context_execute_new.account_delta().nonce_delta(), Felt::new(1));

    Ok(())
}

/// Tests multisig signer update functionality with owner removal.
///
/// This test verifies that a multisig account can:
/// 1. Start with 5 owners and threshold 4
/// 2. Execute a transaction to remove 3 owners (updating to 2 owners)
/// 3. Verify that all removed owners' storage slots are properly cleared
///
/// **Roles:**
/// - 5 Original Approvers (multisig signers, threshold 4)
/// - 2 Updated Approvers (after removing 3 owners)
/// - 1 Multisig Contract
/// - 1 Transaction Script calling multisig procedures
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_update_signers_remove_owner(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    // Setup 5 original owners with threshold 4
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(5, 5, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    let multisig_account = create_multisig_account(4, &approvers, 10, vec![])?;

    // Build mock chain
    let mock_chain_builder = MockChainBuilder::with_accounts([multisig_account.clone()]).unwrap();
    let mut mock_chain = mock_chain_builder.build().unwrap();

    // Setup new signers (remove the last 3 owners, keeping first 2)
    let new_public_keys = &public_keys[0..2];
    let threshold = 1u64;
    let num_of_approvers = 2u64;

    // Create multisig config vector
    let mut config_and_pubkeys_vector =
        vec![Felt::new(threshold), Felt::new(num_of_approvers), Felt::new(0), Felt::new(0)];

    // Add each public key to the vector
    for public_key in new_public_keys.iter().rev() {
        let key_word: Word = public_key.to_commitment().into();
        config_and_pubkeys_vector.extend_from_slice(key_word.as_elements());

        config_and_pubkeys_vector.extend_from_slice(&[
            Felt::new(auth_scheme as u64),
            Felt::new(0),
            Felt::new(0),
            Felt::new(0),
        ]);
    }

    // Create config hash and advice map
    let multisig_config_hash = Hasher::hash_elements(&config_and_pubkeys_vector);
    let mut advice_map = AdviceMap::default();
    advice_map.insert(multisig_config_hash, config_and_pubkeys_vector);

    // Create transaction script
    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script("begin\n    call.::miden::standards::components::auth::multisig::update_signers_and_threshold\nend")?;

    let advice_inputs = AdviceInputs { map: advice_map, ..Default::default() };

    let salt = Word::from([Felt::new(3); 4]);

    // Execute without signatures to get tx summary
    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script.clone())
        .tx_script_args(multisig_config_hash)
        .extend_advice_inputs(advice_inputs.clone())
        .auth_args(salt)
        .build()?;

    let tx_summary = match tx_context_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };

    // Get signatures from 4 of the 5 original approvers (threshold is 4)
    let msg = tx_summary.as_ref().to_commitment();
    let tx_summary = SigningInputs::TransactionSummary(tx_summary);

    let sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary)
        .await?;
    let sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &tx_summary)
        .await?;
    let sig_3 = authenticators[2]
        .get_signature(public_keys[2].to_commitment(), &tx_summary)
        .await?;
    let sig_4 = authenticators[3]
        .get_signature(public_keys[3].to_commitment(), &tx_summary)
        .await?;

    // Execute with signatures
    let update_approvers_tx = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script)
        .tx_script_args(multisig_config_hash)
        .add_signature(public_keys[0].to_commitment(), msg, sig_1)
        .add_signature(public_keys[1].to_commitment(), msg, sig_2)
        .add_signature(public_keys[2].to_commitment(), msg, sig_3)
        .add_signature(public_keys[3].to_commitment(), msg, sig_4)
        .auth_args(salt)
        .extend_advice_inputs(advice_inputs)
        .build()?
        .execute()
        .await?;

    // Verify transaction success
    assert_eq!(update_approvers_tx.account_delta().nonce_delta(), Felt::new(1));

    mock_chain.add_pending_executed_transaction(&update_approvers_tx)?;
    mock_chain.prove_next_block()?;

    // Apply delta to get updated account
    let mut updated_multisig_account = multisig_account.clone();
    updated_multisig_account.apply_delta(update_approvers_tx.account_delta())?;

    // Verify public keys were updated
    for (i, expected_key) in new_public_keys.iter().enumerate() {
        let storage_key = [Felt::new(i as u64), Felt::new(0), Felt::new(0), Felt::new(0)].into();
        let storage_item = updated_multisig_account
            .storage()
            .get_map_item(AuthMultisig::approver_public_keys_slot(), storage_key)
            .unwrap();
        let expected_word: Word = expected_key.to_commitment().into();
        assert_eq!(storage_item, expected_word, "Public key {} doesn't match", i);
    }

    // Verify threshold and num_approvers
    let threshold_config = updated_multisig_account
        .storage()
        .get_item(AuthMultisig::threshold_config_slot())
        .unwrap();
    assert_eq!(threshold_config[0], Felt::new(threshold), "Threshold not updated");
    assert_eq!(threshold_config[1], Felt::new(num_of_approvers), "Num approvers not updated");

    // Verify extracted public keys
    let extracted_pub_keys = get_public_keys_from_account(&updated_multisig_account);
    assert_eq!(extracted_pub_keys.len(), 2, "Should have 2 public keys after update");

    for expected_key in new_public_keys.iter() {
        let expected_word: Word = expected_key.to_commitment().into();
        assert!(
            extracted_pub_keys.contains(&expected_word),
            "Public key not found in extracted keys"
        );
    }

    // Verify removed owners' slots are empty (indices 2, 3, and 4 should be cleared)
    for removed_idx in 2..5 {
        let removed_owner_key =
            [Felt::new(removed_idx), Felt::new(0), Felt::new(0), Felt::new(0)].into();
        let removed_owner_slot = updated_multisig_account
            .storage()
            .get_map_item(AuthMultisig::approver_public_keys_slot(), removed_owner_key)
            .unwrap();
        assert_eq!(
            removed_owner_slot,
            Word::empty(),
            "Removed owner's slot at index {} should be empty",
            removed_idx
        );
    }

    // Verify only 2 non-empty keys remain (at indices 0 and 1)
    let mut non_empty_count = 0;
    for i in 0..5 {
        let storage_key = [Felt::new(i as u64), Felt::new(0), Felt::new(0), Felt::new(0)].into();
        let storage_item = updated_multisig_account
            .storage()
            .get_map_item(AuthMultisig::approver_public_keys_slot(), storage_key)
            .unwrap();

        if storage_item != Word::empty() {
            non_empty_count += 1;
            assert!(i < 2, "Found non-empty key at index {} which should be removed", i);

            let expected_word: Word = new_public_keys.get(i).unwrap().to_commitment().into();
            assert_eq!(storage_item, expected_word, "Key at index {} doesn't match", i);
        }
    }
    assert_eq!(
        non_empty_count, 2,
        "Should have exactly 2 non-empty keys after removing 3 owners"
    );

    Ok(())
}

/// Tests that signer updates are rejected when stored procedure threshold overrides would become
/// unreachable for the new signer set.
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_update_signers_rejects_unreachable_proc_thresholds(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    let (_secret_keys, auth_schemes, public_keys, _authenticators) =
        setup_keys_and_authenticators_with_scheme(3, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    // Configure a procedure override that is valid for the initial signer set (3-of-3),
    // but invalid after updating to 2 signers.
    let multisig_account =
        create_multisig_account(2, &approvers, 10, vec![(BasicWallet::receive_asset_digest(), 3)])?;

    let mock_chain = MockChainBuilder::with_accounts([multisig_account.clone()])
        .unwrap()
        .build()
        .unwrap();

    let new_public_keys = &public_keys[0..2];
    let threshold = 2u64;
    let num_of_approvers = 2u64;

    let mut config_and_pubkeys_vector =
        vec![Felt::new(threshold), Felt::new(num_of_approvers), Felt::new(0), Felt::new(0)];

    for public_key in new_public_keys.iter().rev() {
        let key_word: Word = public_key.to_commitment().into();
        config_and_pubkeys_vector.extend_from_slice(key_word.as_elements());
        config_and_pubkeys_vector.extend_from_slice(&[
            Felt::new(auth_scheme as u64),
            Felt::new(0),
            Felt::new(0),
            Felt::new(0),
        ]);
    }

    let multisig_config_hash = Hasher::hash_elements(&config_and_pubkeys_vector);
    let mut advice_map = AdviceMap::default();
    advice_map.insert(multisig_config_hash, config_and_pubkeys_vector);

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script("begin\n    call.::miden::standards::components::auth::multisig::update_signers_and_threshold\nend")?;

    let advice_inputs = AdviceInputs { map: advice_map, ..Default::default() };
    let salt = Word::from([Felt::new(8); 4]);

    let result = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script)
        .tx_script_args(multisig_config_hash)
        .extend_advice_inputs(advice_inputs)
        .auth_args(salt)
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(result, ERR_PROC_THRESHOLD_EXCEEDS_NUM_APPROVERS);

    Ok(())
}

/// Tests that newly added approvers cannot sign transactions before the signer update is executed.
///
/// This is a regression test to ensure that unauthorized parties cannot add their own public keys
/// to the multisig configuration and immediately use them to sign transactions before
/// the current approvers have validated and executed the signer update.
///
/// **Test Flow:**
/// 1. Create a multisig account with 2 original approvers
/// 2. Prepare a signer update transaction with new approvers
/// 3. Try to sign the transaction with the NEW approvers (should fail)
/// 4. Verify that only the CURRENT approvers can sign the update transaction
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_new_approvers_cannot_sign_before_update(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    // SECTION 1: Create a multisig account with 2 original approvers
    // ================================================================================

    let (_secret_keys, auth_schemes, public_keys, _authenticators) =
        setup_keys_and_authenticators_with_scheme(2, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    let multisig_account = create_multisig_account(2, &approvers, 10, vec![])?;

    let mock_chain = MockChainBuilder::with_accounts([multisig_account.clone()])
        .unwrap()
        .build()
        .unwrap();

    let salt = Word::from([Felt::new(5); 4]);

    // SECTION 2: Prepare a signer update transaction with new approvers
    // ================================================================================

    // Get the multisig library

    // Setup new signers (these should NOT be able to sign the update transaction)
    let mut advice_map = AdviceMap::default();
    let (_new_secret_keys, _new_auth_schemes, new_public_keys, new_authenticators) =
        setup_keys_and_authenticators_with_scheme(4, 4, auth_scheme)?;

    let threshold = 3u64;
    let num_of_approvers = 4u64;

    // Create vector with threshold config and public keys (4 field elements each)
    let mut config_and_pubkeys_vector = Vec::new();
    config_and_pubkeys_vector.extend_from_slice(&[
        Felt::new(threshold),
        Felt::new(num_of_approvers),
        Felt::new(0),
        Felt::new(0),
    ]);

    // Add each public key to the vector
    for public_key in new_public_keys.iter().rev() {
        let key_word: Word = public_key.to_commitment().into();
        config_and_pubkeys_vector.extend_from_slice(key_word.as_elements());

        config_and_pubkeys_vector.extend_from_slice(&[
            Felt::new(auth_scheme as u64),
            Felt::new(0),
            Felt::new(0),
            Felt::new(0),
        ]);
    }

    // Hash the vector to create config hash
    let multisig_config_hash = Hasher::hash_elements(&config_and_pubkeys_vector);

    // Insert config and public keys into advice map
    advice_map.insert(multisig_config_hash, config_and_pubkeys_vector);

    // Create a transaction script that calls the update_signers procedure
    let tx_script_code = "
        begin
            call.::miden::standards::components::auth::multisig::update_signers_and_threshold
        end
    ";

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script(tx_script_code)?;

    let advice_inputs = AdviceInputs {
        map: advice_map.clone(),
        ..Default::default()
    };

    // Pass the MULTISIG_CONFIG_HASH as the tx_script_args
    let tx_script_args: Word = multisig_config_hash;

    // Execute transaction without signatures first to get tx summary
    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script.clone())
        .tx_script_args(tx_script_args)
        .extend_advice_inputs(advice_inputs.clone())
        .auth_args(salt)
        .build()?;

    let tx_summary = match tx_context_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };

    // SECTION 3: Try to sign the transaction with the NEW approvers (should fail)
    // ================================================================================

    // Get signatures from the NEW approvers (these should NOT work)
    let msg = tx_summary.as_ref().to_commitment();
    let tx_summary_signing = SigningInputs::TransactionSummary(tx_summary.clone());

    let new_sig_1 = new_authenticators[0]
        .get_signature(new_public_keys[0].to_commitment(), &tx_summary_signing)
        .await?;
    let new_sig_2 = new_authenticators[1]
        .get_signature(new_public_keys[1].to_commitment(), &tx_summary_signing)
        .await?;

    // Try to execute transaction with NEW signatures - should FAIL
    let tx_context_with_new_sigs = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(tx_script.clone())
        .tx_script_args(multisig_config_hash)
        .add_signature(new_public_keys[0].to_commitment(), msg, new_sig_1)
        .add_signature(new_public_keys[1].to_commitment(), msg, new_sig_2)
        .auth_args(salt)
        .extend_advice_inputs(advice_inputs.clone())
        .build()?;

    // SECTION 4: Verify that only the CURRENT approvers can sign the update transaction
    // ================================================================================

    // Should fail - new approvers not yet authorized
    let result = tx_context_with_new_sigs.execute().await;

    // Assert that the transaction fails as expected
    assert!(
        result.is_err(),
        "Transaction should fail when signed by unauthorized new approvers"
    );

    Ok(())
}

/// Tests that 1-of-2 approvers can consume a note but 2-of-2 are required to send a note.
///
/// This test verifies that a multisig account with 2 approvers and threshold 2, but a procedure
/// threshold of 1 for note consumption, can:
/// 1. Consume a note when only one approver signs the transaction
/// 2. Send a note only when both approvers sign the transaction (default threshold)
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_proc_threshold_overrides(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    // Setup keys and authenticators
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(2, 2, auth_scheme)?;

    let proc_threshold_map = vec![(BasicWallet::receive_asset_digest(), 1)];

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    // Create multisig account
    let multisig_starting_balance = 10u64;
    let mut multisig_account =
        create_multisig_account(2, &approvers, multisig_starting_balance, proc_threshold_map)?;

    // SECTION 1: Test note consumption with 1 signature
    // ================================================================================

    // 1. create a mock note from some random account
    let mut mock_chain_builder =
        MockChainBuilder::with_accounts([multisig_account.clone()]).unwrap();

    let note = mock_chain_builder.add_p2id_note(
        multisig_account.id(),
        multisig_account.id(),
        &[FungibleAsset::mock(1)],
        NoteType::Public,
    )?;

    let mut mock_chain = mock_chain_builder.build()?;

    // 2. consume without signatures
    let salt = Word::from([Felt::new(1); 4]);
    let tx_context = mock_chain
        .build_tx_context(multisig_account.id(), &[note.id()], &[])?
        .auth_args(salt)
        .build()?;

    let tx_summary = match tx_context.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_summary) => tx_summary,
        error => panic!("expected abort with tx summary: {error:?}"),
    };

    // 3. get signature from one approver
    let msg = tx_summary.as_ref().to_commitment();
    let tx_summary_signing = SigningInputs::TransactionSummary(tx_summary.clone());
    let sig = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary_signing)
        .await?;

    // 4. execute with signature
    let tx_result = mock_chain
        .build_tx_context(multisig_account.id(), &[note.id()], &[])?
        .add_signature(public_keys[0].to_commitment(), msg, sig)
        .auth_args(salt)
        .build()?
        .execute()
        .await;

    assert!(tx_result.is_ok(), "Note consumption with 1 signature should succeed");

    // Apply the transaction to the account
    multisig_account.apply_delta(tx_result.as_ref().unwrap().account_delta())?;
    mock_chain.add_pending_executed_transaction(&tx_result.unwrap())?;
    mock_chain.prove_next_block()?;

    // SECTION 2: Test note sending requires 2 signatures
    // ================================================================================

    let salt2 = Word::from([Felt::new(2); 4]);

    // Create output note to send 5 units from the account
    let output_note = P2idNote::create(
        multisig_account.id(),
        ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE.try_into().unwrap(),
        vec![FungibleAsset::mock(5)],
        NoteType::Public,
        Default::default(),
        &mut RandomCoin::new(Word::from([Felt::new(42); 4])),
    )?;
    let multisig_account_interface = AccountInterface::from_account(&multisig_account);
    let send_note_transaction_script =
        multisig_account_interface.build_send_notes_script(&[output_note.clone().into()], None)?;

    // Execute transaction without signatures to get tx summary
    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note.clone())])
        .tx_script(send_note_transaction_script.clone())
        .auth_args(salt2)
        .build()?;

    let tx_summary2 = match tx_context_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };
    // Get signature from only ONE approver
    let msg2 = tx_summary2.as_ref().to_commitment();
    let tx_summary2_signing = SigningInputs::TransactionSummary(tx_summary2.clone());

    let sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary2_signing)
        .await?;

    // Try to execute with only 1 signature - should FAIL
    let tx_context_one_sig = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note.clone())])
        .add_signature(public_keys[0].to_commitment(), msg2, sig_1)
        .tx_script(send_note_transaction_script.clone())
        .auth_args(salt2)
        .build()?;

    let result = tx_context_one_sig.execute().await;
    match result {
        Err(TransactionExecutorError::Unauthorized(_)) => {
            // Expected: transaction should fail with insufficient signatures
        },
        _ => panic!(
            "Transaction should fail with Unauthorized error when only 1 signature provided for note sending"
        ),
    }

    // Now get signatures from BOTH approvers
    let sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &tx_summary2_signing)
        .await?;
    let sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &tx_summary2_signing)
        .await?;

    // Execute with 2 signatures - should SUCCEED
    let result = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .extend_expected_output_notes(vec![RawOutputNote::Full(output_note)])
        .add_signature(public_keys[0].to_commitment(), msg2, sig_1)
        .add_signature(public_keys[1].to_commitment(), msg2, sig_2)
        .auth_args(salt2)
        .tx_script(send_note_transaction_script)
        .build()?
        .execute()
        .await;

    assert!(result.is_ok(), "Transaction should succeed with 2 signatures for note sending");

    // Apply the transaction to the account
    multisig_account.apply_delta(result.as_ref().unwrap().account_delta())?;
    mock_chain.add_pending_executed_transaction(&result.unwrap())?;
    mock_chain.prove_next_block()?;

    assert_eq!(multisig_account.vault().get_balance(FungibleAsset::mock_issuer())?, 6);

    Ok(())
}

/// Tests setting a per-procedure threshold override and clearing it via `proc_threshold == 0`.
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_set_procedure_threshold(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    let (_secret_keys, auth_schemes, public_keys, authenticators) =
        setup_keys_and_authenticators_with_scheme(2, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    let mut multisig_account = create_multisig_account(2, &approvers, 10, vec![])?;
    let mut mock_chain_builder =
        MockChainBuilder::with_accounts([multisig_account.clone()]).unwrap();
    let one_sig_note = mock_chain_builder.add_p2id_note(
        multisig_account.id(),
        multisig_account.id(),
        &[FungibleAsset::mock(1)],
        NoteType::Public,
    )?;
    let clear_check_note = mock_chain_builder.add_p2id_note(
        multisig_account.id(),
        multisig_account.id(),
        &[FungibleAsset::mock(1)],
        NoteType::Public,
    )?;
    let mut mock_chain = mock_chain_builder.build().unwrap();
    let proc_root = BasicWallet::receive_asset_digest();

    let set_script_code = format!(
        r#"
        begin
            push.{proc_root}
            push.1
            call.::miden::standards::components::auth::multisig::set_procedure_threshold
            dropw
            drop
        end
        "#
    );
    let set_script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script(set_script_code)?;

    // 1) Set override to 1 (requires default 2 signatures).
    let set_salt = Word::from([Felt::new(50); 4]);

    let set_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(set_script.clone())
        .auth_args(set_salt)
        .build()?;
    let set_summary = match set_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };
    let set_msg = set_summary.as_ref().to_commitment();
    let set_summary = SigningInputs::TransactionSummary(set_summary);
    let set_sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &set_summary)
        .await?;
    let set_sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &set_summary)
        .await?;

    let set_tx = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(set_script)
        .add_signature(public_keys[0].to_commitment(), set_msg, set_sig_1)
        .add_signature(public_keys[1].to_commitment(), set_msg, set_sig_2)
        .auth_args(set_salt)
        .build()?
        .execute()
        .await?;

    multisig_account.apply_delta(set_tx.account_delta())?;
    mock_chain.add_pending_executed_transaction(&set_tx)?;
    mock_chain.prove_next_block()?;

    // 2) Verify receive_asset can now execute with one signature.
    let one_sig_salt = Word::from([Felt::new(51); 4]);

    let one_sig_init = mock_chain
        .build_tx_context(multisig_account.id(), &[one_sig_note.id()], &[])?
        .auth_args(one_sig_salt)
        .build()?;
    let one_sig_summary = match one_sig_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };
    let one_sig_msg = one_sig_summary.as_ref().to_commitment();
    let one_sig_summary = SigningInputs::TransactionSummary(one_sig_summary);
    let one_sig = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &one_sig_summary)
        .await?;

    let one_sig_tx = mock_chain
        .build_tx_context(multisig_account.id(), &[one_sig_note.id()], &[])?
        .add_signature(public_keys[0].to_commitment(), one_sig_msg, one_sig)
        .auth_args(one_sig_salt)
        .build()?
        .execute()
        .await
        .expect("override=1 should allow receive_asset with one signature");
    multisig_account.apply_delta(one_sig_tx.account_delta())?;
    mock_chain.add_pending_executed_transaction(&one_sig_tx)?;
    mock_chain.prove_next_block()?;

    // 3) Clear override by setting threshold to zero.
    let clear_script_code = format!(
        r#"
        begin
            push.{proc_root}
            push.0
            call.::miden::standards::components::auth::multisig::set_procedure_threshold
            dropw
            drop
        end
        "#
    );
    let clear_script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script(clear_script_code)?;
    let clear_salt = Word::from([Felt::new(52); 4]);

    let clear_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(clear_script.clone())
        .auth_args(clear_salt)
        .build()?;
    let clear_summary = match clear_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };
    let clear_msg = clear_summary.as_ref().to_commitment();
    let clear_summary = SigningInputs::TransactionSummary(clear_summary);
    let clear_sig_1 = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &clear_summary)
        .await?;
    let clear_sig_2 = authenticators[1]
        .get_signature(public_keys[1].to_commitment(), &clear_summary)
        .await?;

    let clear_tx = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(clear_script)
        .add_signature(public_keys[0].to_commitment(), clear_msg, clear_sig_1)
        .add_signature(public_keys[1].to_commitment(), clear_msg, clear_sig_2)
        .auth_args(clear_salt)
        .build()?
        .execute()
        .await?;

    multisig_account.apply_delta(clear_tx.account_delta())?;
    mock_chain.add_pending_executed_transaction(&clear_tx)?;
    mock_chain.prove_next_block()?;

    // 4) After clear, one signature should no longer be sufficient for receive_asset.
    let clear_check_salt = Word::from([Felt::new(53); 4]);

    let clear_check_init = mock_chain
        .build_tx_context(multisig_account.id(), &[clear_check_note.id()], &[])?
        .auth_args(clear_check_salt)
        .build()?;
    let clear_check_summary = match clear_check_init.execute().await.unwrap_err() {
        TransactionExecutorError::Unauthorized(tx_effects) => tx_effects,
        error => panic!("expected abort with tx effects: {error:?}"),
    };
    let clear_check_msg = clear_check_summary.as_ref().to_commitment();
    let clear_check_summary = SigningInputs::TransactionSummary(clear_check_summary);
    let clear_check_sig = authenticators[0]
        .get_signature(public_keys[0].to_commitment(), &clear_check_summary)
        .await?;

    let clear_check_result = mock_chain
        .build_tx_context(multisig_account.id(), &[clear_check_note.id()], &[])?
        .add_signature(public_keys[0].to_commitment(), clear_check_msg, clear_check_sig)
        .auth_args(clear_check_salt)
        .build()?
        .execute()
        .await;

    assert!(
        matches!(clear_check_result, Err(TransactionExecutorError::Unauthorized(_))),
        "override cleared via threshold=0 should restore default threshold requirements"
    );

    Ok(())
}

/// Tests setting an override threshold above num_approvers is rejected.
#[rstest]
#[case::ecdsa(AuthScheme::EcdsaK256Keccak)]
#[case::falcon(AuthScheme::Falcon512Poseidon2)]
#[tokio::test]
async fn test_multisig_set_procedure_threshold_rejects_exceeding_approvers(
    #[case] auth_scheme: AuthScheme,
) -> anyhow::Result<()> {
    let (_secret_keys, auth_schemes, public_keys, _authenticators) =
        setup_keys_and_authenticators_with_scheme(2, 2, auth_scheme)?;

    let approvers = public_keys
        .iter()
        .zip(auth_schemes.iter())
        .map(|(pk, scheme)| (pk.clone(), *scheme))
        .collect::<Vec<_>>();

    let multisig_account = create_multisig_account(2, &approvers, 10, vec![])?;
    let proc_root = BasicWallet::receive_asset_digest();

    let script_code = format!(
        r#"
        begin
            push.{proc_root}
            push.3
            call.::miden::standards::components::auth::multisig::set_procedure_threshold
        end
        "#
    );
    let script = CodeBuilder::default()
        .with_dynamically_linked_library(multisig_library())?
        .compile_tx_script(script_code)?;

    let mock_chain = MockChainBuilder::with_accounts([multisig_account.clone()])
        .unwrap()
        .build()
        .unwrap();
    let salt = Word::from([Felt::new(54); 4]);

    let tx_context_init = mock_chain
        .build_tx_context(multisig_account.id(), &[], &[])?
        .tx_script(script.clone())
        .auth_args(salt)
        .build()?;

    let result = tx_context_init.execute().await;

    assert_transaction_executor_error!(result, ERR_PROC_THRESHOLD_EXCEEDS_NUM_APPROVERS);

    Ok(())
}