miden-multisig-client 0.18.1

High-level SDK for interacting with multisig accounts on Miden via GUARDIAN
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
//! Proposal builder for multisig transactions.

use std::num::NonZeroU32;
use std::sync::Arc;

use guardian_client::GuardianClient;
use guardian_shared::ToJson;
use miden_client::rpc::NodeRpcClient;
use miden_protocol::Word;
use miden_protocol::account::AccountId;
use miden_protocol::note::{NoteId, NoteType};
use miden_standards::account::auth::{ApproverSet, MultisigAuthArgs};

use crate::MidenSdkClient;
use crate::account::MultisigAccount;
use crate::error::{MultisigError, Result};
use crate::execution::build_transfer_asset;
use crate::guardian_endpoint::verify_endpoint_commitment;
use crate::keystore::{KeyManager, ensure_hex_prefix};
use crate::payload::ProposalPayload;
use crate::procedures::ProcedureName;
use crate::proposal::{P2ideHeights, Proposal, ProposalMetadata, TransactionType};
use crate::utils::hex_body_eq;

use super::{
    build_p2id_transaction_request, build_update_guardian_transaction_request,
    build_update_procedure_threshold_transaction_request, build_update_signers_transaction_request,
    execute_for_summary_at_tip, generate_salt, proposer_auth_args, word_to_hex,
};

/// Builder for creating multisig transaction proposals.
///
/// # Example
///
/// ```ignore
/// use miden_multisig_client::TransactionType;
///
/// let proposal = ProposalBuilder::new(TransactionType::AddCosigner { new_commitment })
///     .build(&mut miden_client, &node_rpc, &mut guardian_client, &account, key_manager)
///     .await?;
/// ```
pub struct ProposalBuilder {
    transaction_type: TransactionType,
    approval_expiration_delta: Option<NonZeroU32>,
}

/// Per-proposal settings a caller may set when proposing a transaction.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProposalOptions {
    /// Blocks after the block the proposal binds by which the transaction must be
    /// included; past that the approvers' signatures no longer authorize it. The
    /// summary binds it, so the executing party can neither shorten nor extend it.
    /// At most [`MAX_APPROVAL_EXPIRATION_DELTA`](crate::MAX_APPROVAL_EXPIRATION_DELTA)
    /// blocks, the furthest a transaction can expire after its reference block.
    /// `None` means the approval never expires, the upstream default.
    pub approval_expiration_delta: Option<NonZeroU32>,
}

/// What the account's auth procedure rejects after a signer or guardian change,
/// checked before any signature is collected: more approvers than
/// `ApproverSet::MAX_APPROVERS`, a repeated approver, and the guardian key among
/// the approvers. The TypeScript SDK runs the same checks through
/// `validateMultisigConfig`.
fn ensure_admissible_signer_set(signers: &[Word], guardian_commitment: Word) -> Result<()> {
    let max_approvers = usize::from(ApproverSet::MAX_APPROVERS);
    if signers.len() > max_approvers {
        return Err(MultisigError::InvalidConfig(format!(
            "too many signers ({}): a multisig account holds at most {max_approvers}",
            signers.len()
        )));
    }
    let mut seen = std::collections::HashSet::with_capacity(signers.len());
    if let Some(duplicate) = signers.iter().find(|signer| !seen.insert(**signer)) {
        return Err(MultisigError::InvalidConfig(format!(
            "duplicate signer commitment: {}",
            word_to_hex(duplicate)
        )));
    }
    if signers.contains(&guardian_commitment) {
        return Err(MultisigError::InvalidConfig(
            "GUARDIAN commitment must be different from all signer commitments".to_string(),
        ));
    }
    Ok(())
}

/// The rules a threshold change has to satisfy before anything is executed.
///
/// Separate from the builder so they can be tested without a client: every one
/// of them rejects before the first network call, and a caller that trips one
/// should learn why rather than watch a transaction fail.
fn validate_threshold_change(
    current_threshold: u32,
    current_signers: &[Word],
    requested_signers: &[Word],
    new_threshold: u32,
) -> Result<()> {
    // Compared as a set, then built from the account's own ordering, so a
    // caller that lists the same signers in another order cannot silently
    // repack the storage indices.
    let mut requested_sorted: Vec<Word> = requested_signers.to_vec();
    let mut current_sorted: Vec<Word> = current_signers.to_vec();
    requested_sorted.sort_by_key(word_to_hex);
    current_sorted.sort_by_key(word_to_hex);
    if requested_sorted != current_sorted {
        return Err(MultisigError::InvalidConfig(
            "UpdateSigners changes the threshold only; use AddCosigner or RemoveCosigner to change the signer set".to_string(),
        ));
    }

    if new_threshold < 1 || new_threshold as usize > current_signers.len() {
        return Err(MultisigError::InvalidConfig(format!(
            "invalid threshold {}: must be between 1 and {}",
            new_threshold,
            current_signers.len()
        )));
    }

    if new_threshold == current_threshold {
        return Err(MultisigError::InvalidConfig(format!(
            "threshold is already {}",
            new_threshold
        )));
    }

    Ok(())
}

impl ProposalBuilder {
    /// Creates a new proposal builder for the given transaction type.
    pub fn new(transaction_type: TransactionType) -> Self {
        Self {
            transaction_type,
            approval_expiration_delta: None,
        }
    }

    /// Applies `options` to this builder.
    pub fn with_options(mut self, options: ProposalOptions) -> Self {
        self.approval_expiration_delta = options.approval_expiration_delta;
        self
    }

    /// Builds and submits the proposal to GUARDIAN.
    pub async fn build(
        self,
        miden_client: &mut MidenSdkClient,
        node_rpc: &Arc<dyn NodeRpcClient>,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        match self.transaction_type {
            TransactionType::AddCosigner { new_commitment } => {
                self.build_add_cosigner(
                    miden_client,
                    guardian_client,
                    account,
                    new_commitment,
                    key_manager,
                )
                .await
            }
            TransactionType::RemoveCosigner { commitment } => {
                self.build_remove_cosigner(
                    miden_client,
                    guardian_client,
                    account,
                    commitment,
                    key_manager,
                )
                .await
            }
            TransactionType::P2ID {
                recipient,
                faucet_id,
                amount,
                note_type,
                heights,
            } => {
                self.build_p2id(
                    miden_client,
                    guardian_client,
                    account,
                    recipient,
                    faucet_id,
                    amount,
                    note_type,
                    heights,
                    key_manager,
                )
                .await
            }
            TransactionType::ConsumeNotes { ref note_ids, .. } => {
                self.build_consume_notes(
                    miden_client,
                    node_rpc,
                    guardian_client,
                    account,
                    note_ids.clone(),
                    key_manager,
                )
                .await
            }
            TransactionType::SwitchGuardian {
                ref new_endpoint,
                new_commitment,
            } => {
                self.build_switch_guardian(
                    miden_client,
                    guardian_client,
                    account,
                    new_commitment,
                    new_endpoint.clone(),
                    key_manager,
                )
                .await
            }
            TransactionType::UpdateProcedureThreshold {
                procedure,
                new_threshold,
            } => {
                self.build_update_procedure_threshold(
                    miden_client,
                    guardian_client,
                    account,
                    procedure,
                    new_threshold,
                    key_manager,
                )
                .await
            }
            TransactionType::UpdateSigners {
                new_threshold,
                ref signer_commitments,
            } => {
                self.build_update_signers(
                    miden_client,
                    guardian_client,
                    account,
                    new_threshold,
                    signer_commitments,
                    key_manager,
                )
                .await
            }
            TransactionType::Custom => Err(MultisigError::UnsupportedTransactionType(
                "cannot create a proposal for a custom transaction type".to_string(),
            )),
        }
    }

    fn ensure_response_commitment(proposal: &Proposal, response_commitment: &str) -> Result<()> {
        let response_commitment = ensure_hex_prefix(response_commitment);
        if hex_body_eq(&proposal.id, &response_commitment) {
            return Ok(());
        }

        Err(MultisigError::GuardianServer(format!(
            "GUARDIAN returned proposal commitment {} but transaction summary commitment is {}",
            response_commitment, proposal.id
        )))
    }

    async fn fresh_auth_args(&self, miden_client: &MidenSdkClient) -> Result<MultisigAuthArgs> {
        proposer_auth_args(
            miden_client,
            generate_salt(),
            self.approval_expiration_delta,
        )
        .await
    }

    async fn build_add_cosigner(
        &self,
        miden_client: &mut MidenSdkClient,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        new_commitment: Word,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let current_threshold = account.threshold()?;
        let mut current_signers = account.cosigner_commitments();
        let required_signatures =
            account.effective_threshold_for_procedure(ProcedureName::UpdateSigners)? as usize;

        // Add the new signer
        current_signers.push(new_commitment);
        ensure_admissible_signer_set(&current_signers, account.guardian_commitment()?)?;

        // Keep same threshold
        let new_threshold = current_threshold as u64;

        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();

        // Build the transaction request (without signatures - we just want the summary)
        let (tx_request, _config_hash) = build_update_signers_transaction_request(
            new_threshold,
            &current_signers,
            &auth_args,
            std::iter::empty(),
            key_manager.scheme(),
        )?;

        // Execute to get the TransactionSummary
        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;

        // Sign the transaction summary commitment
        let tx_commitment = tx_summary.to_commitment();

        // Build proposal metadata
        let signer_commitments_hex: Vec<String> = current_signers.iter().map(word_to_hex).collect();

        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            proposal_type: None,
            new_threshold: Some(new_threshold),
            signer_commitments_hex: signer_commitments_hex.clone(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: None,
            faucet_id_hex: None,
            amount: None,
            note_type: None,
            reclaim_height: None,
            timelock_height: None,
            note_ids_hex: Vec::new(),
            consume_notes_metadata_version: None,
            consume_notes_notes: Vec::new(),
            new_guardian_pubkey_hex: None,
            new_guardian_endpoint: None,
            target_procedure: None,
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        // Build the payload using ProposalPayload
        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_add_signer_metadata(
                new_threshold,
                signer_commitments_hex.clone(),
                word_to_hex(&salt),
            )
            .with_required_signatures(required_signatures);

        // Push proposal to GUARDIAN
        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        // Build the Proposal
        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::AddCosigner { new_commitment },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }

    /// Changes the signing threshold, leaving the signer set as it is.
    ///
    /// The on-chain procedure takes a set and a threshold together, so this is
    /// the same call `build_add_cosigner` makes with the set left alone. A
    /// membership change is refused here rather than served: deriving the new
    /// set from the current one is what makes add and remove safe, and a
    /// caller-supplied set would give that up for no gain, since this variant
    /// exists to move the threshold.
    async fn build_update_signers(
        &self,
        miden_client: &mut MidenSdkClient,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        new_threshold: u32,
        requested_signers: &[Word],
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let current_threshold = account.threshold()?;
        let current_signers = account.cosigner_commitments();
        let required_signatures =
            account.effective_threshold_for_procedure(ProcedureName::UpdateSigners)? as usize;

        validate_threshold_change(
            current_threshold,
            &current_signers,
            requested_signers,
            new_threshold,
        )?;

        let new_threshold = new_threshold as u64;
        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();

        let (tx_request, _config_hash) = build_update_signers_transaction_request(
            new_threshold,
            &current_signers,
            &auth_args,
            std::iter::empty(),
            key_manager.scheme(),
        )?;

        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;
        let tx_commitment = tx_summary.to_commitment();

        let signer_commitments_hex: Vec<String> = current_signers.iter().map(word_to_hex).collect();

        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            // Carried explicitly, unlike add and remove. All three wire types
            // parse back into `UpdateSigners`, so the variant cannot name itself
            // and export refuses to guess; without this the proposal would be
            // signable but not exportable.
            proposal_type: Some("change_threshold".to_string()),
            new_threshold: Some(new_threshold),
            signer_commitments_hex: signer_commitments_hex.clone(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: None,
            faucet_id_hex: None,
            amount: None,
            note_type: None,
            reclaim_height: None,
            timelock_height: None,
            note_ids_hex: Vec::new(),
            consume_notes_metadata_version: None,
            consume_notes_notes: Vec::new(),
            new_guardian_pubkey_hex: None,
            new_guardian_endpoint: None,
            target_procedure: None,
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_threshold_metadata(
                new_threshold,
                signer_commitments_hex.clone(),
                word_to_hex(&salt),
            )
            .with_required_signatures(required_signatures);

        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::UpdateSigners {
                new_threshold: new_threshold as u32,
                signer_commitments: current_signers,
            },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }

    async fn build_remove_cosigner(
        &self,
        miden_client: &mut MidenSdkClient,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        commitment_to_remove: Word,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let current_threshold = account.threshold()?;
        let current_signers = account.cosigner_commitments();
        let required_signatures =
            account.effective_threshold_for_procedure(ProcedureName::UpdateSigners)? as usize;

        // Remove the signer
        let new_signers: Vec<Word> = current_signers
            .iter()
            .filter(|&c| c != &commitment_to_remove)
            .copied()
            .collect();

        if new_signers.len() == current_signers.len() {
            return Err(MultisigError::InvalidConfig(
                "commitment to remove not found in signers".to_string(),
            ));
        }

        // Adjust threshold if needed (can't be more than signers)
        let new_threshold = std::cmp::min(current_threshold as u64, new_signers.len() as u64);

        if new_signers.is_empty() {
            return Err(MultisigError::InvalidConfig(
                "cannot remove last signer".to_string(),
            ));
        }

        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();

        // Build the transaction request
        let (tx_request, _config_hash) = build_update_signers_transaction_request(
            new_threshold,
            &new_signers,
            &auth_args,
            std::iter::empty(),
            key_manager.scheme(),
        )?;

        // Execute to get the TransactionSummary
        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;

        // Sign the transaction summary commitment
        let tx_commitment = tx_summary.to_commitment();

        // Build proposal metadata
        let signer_commitments_hex: Vec<String> = new_signers.iter().map(word_to_hex).collect();

        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            proposal_type: None,
            new_threshold: Some(new_threshold),
            signer_commitments_hex: signer_commitments_hex.clone(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: None,
            faucet_id_hex: None,
            amount: None,
            note_type: None,
            reclaim_height: None,
            timelock_height: None,
            note_ids_hex: Vec::new(),
            consume_notes_metadata_version: None,
            consume_notes_notes: Vec::new(),
            new_guardian_pubkey_hex: None,
            new_guardian_endpoint: None,
            target_procedure: None,
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        // Build the payload using ProposalPayload
        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_remove_signer_metadata(
                new_threshold,
                signer_commitments_hex.clone(),
                word_to_hex(&salt),
            )
            .with_required_signatures(required_signatures);

        // Push proposal to GUARDIAN
        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        // Build the Proposal
        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::RemoveCosigner {
                commitment: commitment_to_remove,
            },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }

    #[allow(clippy::too_many_arguments)]
    async fn build_p2id(
        &self,
        miden_client: &mut MidenSdkClient,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        recipient: AccountId,
        faucet_id: AccountId,
        amount: u64,
        note_type: NoteType,
        heights: P2ideHeights,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let required_signatures =
            account.effective_threshold_for_procedure(ProcedureName::SendAsset)? as usize;

        let asset = build_transfer_asset(faucet_id, amount)?;

        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();

        // Build the P2ID transaction request (no signature advice needed for proposal)
        let tx_request = build_p2id_transaction_request(
            account.inner(),
            recipient,
            vec![asset.into()],
            note_type,
            heights,
            &auth_args,
            std::iter::empty(),
        )?;

        // Execute to get the TransactionSummary
        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;

        // Sign the transaction summary commitment
        let tx_commitment = tx_summary.to_commitment();

        // Build proposal metadata
        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            proposal_type: None,
            new_threshold: None,
            signer_commitments_hex: Vec::new(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: Some(recipient.to_string()),
            faucet_id_hex: Some(faucet_id.to_string()),
            amount: Some(amount),
            note_type: (note_type != NoteType::Public).then(|| note_type.to_string()),
            reclaim_height: heights.reclaim,
            timelock_height: heights.timelock,
            note_ids_hex: Vec::new(),
            consume_notes_metadata_version: None,
            consume_notes_notes: Vec::new(),
            new_guardian_pubkey_hex: None,
            new_guardian_endpoint: None,
            target_procedure: None,
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        // Build the payload using ProposalPayload
        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_payment_metadata(
                recipient.to_string(),
                faucet_id.to_string(),
                amount,
                word_to_hex(&salt),
                note_type,
                heights,
            )
            .with_required_signatures(required_signatures);

        // Push proposal to GUARDIAN
        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        // Build the Proposal
        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::P2ID {
                recipient,
                faucet_id,
                amount,
                note_type,
                heights,
            },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }

    async fn build_consume_notes(
        &self,
        miden_client: &mut MidenSdkClient,
        node_rpc: &Arc<dyn NodeRpcClient>,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        note_ids: Vec<NoteId>,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let required_signatures =
            account.effective_threshold_for_procedure(ProcedureName::ReceiveAsset)? as usize;

        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();

        // Fetch notes from the proposer's local store for v2 embedding (FR-012).
        let fetched_notes =
            crate::transaction::consume::fetch_notes_from_store(miden_client, &note_ids).await?;
        // Canonical consumption mode is authenticated (issue #409): the summary
        // this proposal signs must be the one every cosigner's rebuild
        // reproduces, so the notes are authenticated here first.
        crate::transaction::ensure_notes_authenticated(miden_client, node_rpc, &fetched_notes)
            .await?;
        let serialized_notes: Vec<crate::proposal::SerializedNote> = fetched_notes
            .iter()
            .map(crate::proposal::SerializedNote::from_note)
            .collect();

        let tx_request = crate::transaction::build_consume_notes_transaction_request_from_notes(
            fetched_notes,
            &auth_args,
            std::iter::empty(),
        )?;

        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;
        let tx_commitment = tx_summary.to_commitment();

        let note_ids_hex: Vec<String> = note_ids.iter().map(|id| id.to_hex()).collect();
        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            proposal_type: None,
            new_threshold: None,
            signer_commitments_hex: Vec::new(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: None,
            faucet_id_hex: None,
            amount: None,
            note_type: None,
            reclaim_height: None,
            timelock_height: None,
            note_ids_hex: note_ids_hex.clone(),
            consume_notes_metadata_version: Some(
                crate::proposal::CONSUME_NOTES_METADATA_VERSION_V2,
            ),
            consume_notes_notes: serialized_notes.clone(),
            new_guardian_pubkey_hex: None,
            new_guardian_endpoint: None,
            target_procedure: None,
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        let notes_base64: Vec<String> = serialized_notes
            .into_iter()
            .map(crate::proposal::SerializedNote::into_inner)
            .collect();

        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_note_consumption_metadata_v2(note_ids_hex, notes_base64, word_to_hex(&salt))
            .with_required_signatures(required_signatures);

        // FR-011: cap covers only the metadata fragment, not the full payload.
        if let Some(meta) = payload.metadata.as_ref() {
            let serialized_len = serde_json::to_vec(meta)
                .map_err(MultisigError::Serialization)?
                .len();
            if serialized_len > crate::proposal::MAX_CONSUME_NOTES_METADATA_BYTES {
                return Err(MultisigError::ConsumeNotesMetadataOversize {
                    limit: crate::proposal::MAX_CONSUME_NOTES_METADATA_BYTES,
                    actual: serialized_len,
                });
            }
        }

        // Push proposal to GUARDIAN
        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        // Clone notes for the runtime TransactionType; metadata keeps its own copy.
        let notes_for_tx_type = metadata.consume_notes_notes.clone();
        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::ConsumeNotes {
                note_ids,
                metadata_version: Some(crate::proposal::CONSUME_NOTES_METADATA_VERSION_V2),
                notes: notes_for_tx_type,
            },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }

    #[allow(clippy::too_many_arguments)]
    async fn build_switch_guardian(
        &self,
        miden_client: &mut MidenSdkClient,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        new_guardian_pubkey: Word,
        new_guardian_endpoint: String,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let required_signatures =
            account.effective_threshold_for_procedure(ProcedureName::UpdateGuardian)? as usize;
        ensure_admissible_signer_set(&account.cosigner_commitments(), new_guardian_pubkey)?;

        verify_endpoint_commitment(
            &new_guardian_endpoint,
            new_guardian_pubkey,
            key_manager.scheme(),
        )
        .await?;

        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();

        // Build the GUARDIAN update transaction request (no signatures for proposal)
        let tx_request = build_update_guardian_transaction_request(
            new_guardian_pubkey,
            key_manager.scheme(),
            &auth_args,
            std::iter::empty(),
        )?;

        // Execute to get the TransactionSummary
        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;

        // Sign the transaction summary commitment
        let tx_commitment = tx_summary.to_commitment();

        // Build proposal metadata
        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            proposal_type: None,
            new_threshold: None,
            signer_commitments_hex: Vec::new(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: None,
            faucet_id_hex: None,
            amount: None,
            note_type: None,
            reclaim_height: None,
            timelock_height: None,
            note_ids_hex: Vec::new(),
            consume_notes_metadata_version: None,
            consume_notes_notes: Vec::new(),
            new_guardian_pubkey_hex: Some(word_to_hex(&new_guardian_pubkey)),
            new_guardian_endpoint: Some(new_guardian_endpoint.clone()),
            target_procedure: None,
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        // Build the payload using ProposalPayload
        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_guardian_update_metadata(
                word_to_hex(&new_guardian_pubkey),
                new_guardian_endpoint.clone(),
                word_to_hex(&salt),
            )
            .with_required_signatures(required_signatures);

        // Push proposal to GUARDIAN
        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        // Build the Proposal
        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::SwitchGuardian {
                new_endpoint: new_guardian_endpoint,
                new_commitment: new_guardian_pubkey,
            },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }

    async fn build_update_procedure_threshold(
        &self,
        miden_client: &mut MidenSdkClient,
        guardian_client: &mut GuardianClient,
        account: &MultisigAccount,
        procedure: ProcedureName,
        new_threshold: u32,
        key_manager: &dyn KeyManager,
    ) -> Result<Proposal> {
        let account_id = account.id();
        let required_signatures = account
            .effective_threshold_for_procedure(ProcedureName::UpdateProcedureThreshold)?
            as usize;

        let auth_args = self.fresh_auth_args(miden_client).await?;
        let salt = auth_args.salt();
        let tx_request = build_update_procedure_threshold_transaction_request(
            procedure,
            new_threshold,
            &auth_args,
            std::iter::empty(),
        )?;
        let tx_summary = execute_for_summary_at_tip(miden_client, account_id, tx_request).await?;
        let tx_commitment = tx_summary.to_commitment();

        let metadata = ProposalMetadata {
            tx_summary_json: Some(tx_summary.to_json()),
            proposal_type: None,
            new_threshold: Some(new_threshold as u64),
            signer_commitments_hex: Vec::new(),
            salt_hex: Some(word_to_hex(&salt)),
            recipient_hex: None,
            faucet_id_hex: None,
            amount: None,
            note_type: None,
            reclaim_height: None,
            timelock_height: None,
            note_ids_hex: Vec::new(),
            consume_notes_metadata_version: None,
            consume_notes_notes: Vec::new(),
            new_guardian_pubkey_hex: None,
            new_guardian_endpoint: None,
            target_procedure: Some(procedure.to_string()),
            required_signatures: Some(required_signatures),
            signers: vec![key_manager.commitment_hex()],
            ..Default::default()
        };

        let payload = ProposalPayload::new(&tx_summary)
            .with_signature(key_manager, tx_commitment)
            .with_procedure_threshold_metadata(procedure, new_threshold as u64, word_to_hex(&salt))
            .with_required_signatures(required_signatures);

        let nonce = account.nonce() + 1;
        let response = guardian_client
            .push_delta_proposal(&account_id, nonce, &payload.to_json())
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to push proposal: {}", e))
            })?;

        let proposal = Proposal::new(
            tx_summary,
            nonce,
            TransactionType::UpdateProcedureThreshold {
                procedure,
                new_threshold,
            },
            metadata,
        );
        Self::ensure_response_commitment(&proposal, &response.commitment)?;

        Ok(proposal)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use miden_protocol::account::AccountCodePatch;
    use miden_protocol::account::AccountStoragePatch;
    use miden_protocol::account::delta::{AccountDelta, AccountVaultDelta};
    use miden_protocol::transaction::{
        InputNotes, RawOutputNotes, TransactionSummary, TransactionSummaryUserParams,
    };
    use miden_protocol::{Felt, ZERO};

    fn signer(byte: u8) -> Word {
        crate::keystore::word_from_hex(&format!("0x{}", format!("{byte:02x}").repeat(32)))
            .expect("valid word")
    }

    #[test]
    fn threshold_change_accepts_the_same_set_in_any_order() {
        let current = vec![signer(1), signer(2), signer(3)];
        let reordered = vec![signer(3), signer(1), signer(2)];
        assert!(validate_threshold_change(2, &current, &reordered, 3).is_ok());
    }

    #[test]
    fn threshold_change_rejects_a_membership_change() {
        let current = vec![signer(1), signer(2)];
        let with_extra = vec![signer(1), signer(2), signer(3)];
        let error = validate_threshold_change(2, &current, &with_extra, 2)
            .expect_err("a different signer set is not a threshold change");
        assert!(error.to_string().contains("AddCosigner or RemoveCosigner"));

        let swapped = vec![signer(1), signer(9)];
        assert!(validate_threshold_change(2, &current, &swapped, 1).is_err());
    }

    #[test]
    fn threshold_change_rejects_a_threshold_outside_the_signer_count() {
        let current = vec![signer(1), signer(2), signer(3)];
        // Above the signer count no quorum could ever be reached.
        assert!(validate_threshold_change(2, &current, &current, 4).is_err());
        // Zero would leave the account unguarded.
        assert!(validate_threshold_change(2, &current, &current, 0).is_err());
        assert!(validate_threshold_change(2, &current, &current, 3).is_ok());
        assert!(validate_threshold_change(2, &current, &current, 1).is_ok());
    }

    #[test]
    fn threshold_change_rejects_a_no_op() {
        let current = vec![signer(1), signer(2), signer(3)];
        let error = validate_threshold_change(2, &current, &current, 2)
            .expect_err("proposing the threshold it already has spends a quorum for nothing");
        assert!(error.to_string().contains("already"));
    }

    fn test_proposal() -> Proposal {
        let account_id =
            AccountId::from_hex("0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b").expect("valid account id");
        let account_delta = AccountDelta::new(
            account_id,
            AccountStoragePatch::default(),
            AccountVaultDelta::default(),
            AccountCodePatch::default(),
            Felt::ZERO,
        )
        .expect("valid delta");
        let tx_summary = TransactionSummary::new(
            account_delta,
            InputNotes::new(Vec::new()).expect("empty input notes"),
            RawOutputNotes::new(Vec::new()).expect("empty output notes"),
            miden_protocol::block::BlockNumber::from(0),
            Word::default(),
            0,
            TransactionSummaryUserParams::new([
                ZERO,
                ZERO,
                Felt::new_unchecked(9),
                ZERO,
                ZERO,
                ZERO,
            ]),
        );

        Proposal::new(
            tx_summary,
            1,
            TransactionType::ConsumeNotes {
                note_ids: vec![miden_protocol::note::NoteId::from_raw(Word::from([
                    Felt::new_unchecked(1),
                    ZERO,
                    ZERO,
                    ZERO,
                ]))],
                metadata_version: None,
                notes: Vec::new(),
            },
            ProposalMetadata {
                note_ids_hex: vec![
                    "0x0100000000000000000000000000000000000000000000000000000000000000"
                        .to_string(),
                ],
                required_signatures: Some(1),
                ..Default::default()
            },
        )
    }

    #[test]
    fn ensure_response_commitment_rejects_mismatch() {
        let proposal = test_proposal();
        let result = ProposalBuilder::ensure_response_commitment(
            &proposal,
            "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
        );

        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("transaction summary commitment")
        );
    }

    mod multisig_auth_args {
        use super::*;
        use crate::client::test_support::{guarded_multisig_account, p2id_note_for, test_wallet};
        use guardian_shared::SignatureScheme;
        use miden_client::transaction::TransactionRequest;
        use miden_protocol::asset::FungibleAsset;
        use miden_protocol::block::BlockNumber;
        use miden_protocol::crypto::SequentialCommit;
        use miden_standards::account::auth::MultisigAuthArgs;

        fn auth_args() -> MultisigAuthArgs {
            MultisigAuthArgs::new(BlockNumber::from(7), Word::from([1u32, 2, 3, 4]))
        }

        /// The request must carry the three-word auth args itself: a declared fee
        /// conversion salt would let miden-client commit its own auth arg over them.
        /// It must also declare the block they bind, or it cannot execute at a later
        /// chain tip.
        fn assert_carries_auth_args(request: &TransactionRequest) {
            let commitment = auth_args().to_commitment();
            assert_eq!(request.fee_conversion_salt(), None);
            assert_eq!(*request.auth_arg(), Some(commitment));
            let preimage = request
                .advice_map()
                .get(&commitment)
                .expect("the auth-args preimage is in the advice map");
            assert_eq!(preimage.to_vec(), auth_args().to_elements());
            assert_eq!(
                request.block_numbers().iter().copied().collect::<Vec<_>>(),
                vec![auth_args().bound_block_num()],
                "the request declares exactly the block its auth args bind"
            );
        }

        #[test]
        fn signer_update_request_carries_the_auth_args() {
            let (request, _) = build_update_signers_transaction_request(
                1,
                &[Word::from([5u32, 6, 7, 8])],
                &auth_args(),
                std::iter::empty(),
                SignatureScheme::Falcon,
            )
            .expect("the signer-update request builds");

            assert_carries_auth_args(&request);
        }

        #[test]
        fn p2id_request_carries_the_auth_args() {
            let recipient = AccountId::from_hex("0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b")
                .expect("valid recipient id");

            let request = build_p2id_transaction_request(
                &guarded_multisig_account(),
                recipient,
                vec![FungibleAsset::mock(100)],
                NoteType::Public,
                P2ideHeights::default(),
                &auth_args(),
                std::iter::empty(),
            )
            .expect("the p2id request builds");

            assert_carries_auth_args(&request);
        }

        #[test]
        fn consume_notes_request_carries_the_auth_args() {
            let note = p2id_note_for(&test_wallet(1), 1, NoteType::Public);

            let request = crate::transaction::build_consume_notes_transaction_request_from_notes(
                vec![note],
                &auth_args(),
                std::iter::empty(),
            )
            .expect("the consume-notes request builds");

            assert_carries_auth_args(&request);
        }

        #[test]
        fn switch_guardian_request_carries_the_auth_args() {
            let request = build_update_guardian_transaction_request(
                Word::from([1u32, 1, 1, 1]),
                SignatureScheme::Falcon,
                &auth_args(),
                std::iter::empty(),
            )
            .expect("the switch-guardian request builds");

            assert_carries_auth_args(&request);
        }

        #[test]
        fn update_procedure_threshold_request_carries_the_auth_args() {
            let request = build_update_procedure_threshold_transaction_request(
                ProcedureName::SendAsset,
                2,
                &auth_args(),
                std::iter::empty(),
            )
            .expect("the procedure-threshold request builds");

            assert_carries_auth_args(&request);
        }
    }
}

#[cfg(test)]
mod signer_set_guard {
    use super::*;

    fn signer(n: u32) -> Word {
        Word::from([n, n, n, n])
    }

    #[test]
    fn accepts_distinct_signers_without_the_guardian() {
        ensure_admissible_signer_set(&[signer(1), signer(2)], signer(9)).unwrap();
    }

    #[test]
    fn rejects_more_signers_than_the_account_holds() {
        let signers: Vec<Word> = (1..=u32::from(ApproverSet::MAX_APPROVERS) + 1)
            .map(signer)
            .collect();
        let error = ensure_admissible_signer_set(&signers, signer(0))
            .unwrap_err()
            .to_string();
        assert!(error.contains("too many signers"), "{error}");
    }

    #[test]
    fn rejects_a_repeated_signer() {
        let error = ensure_admissible_signer_set(&[signer(1), signer(1)], signer(9))
            .unwrap_err()
            .to_string();
        assert!(error.contains("duplicate signer commitment"), "{error}");
    }

    #[test]
    fn rejects_the_guardian_among_the_signers() {
        let error = ensure_admissible_signer_set(&[signer(1), signer(9)], signer(9))
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("GUARDIAN commitment must be different"),
            "{error}"
        );
    }
}