miden-multisig-client 0.14.4

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

use std::collections::HashSet;

use guardian_client::DeltaObject;
use guardian_shared::FromJson;
use guardian_shared::hex::FromHex;
use guardian_shared::{ProposalSignature, SignatureScheme};
use miden_protocol::account::AccountId;
use miden_protocol::crypto::dsa::ecdsa_k256_keccak::{
    PublicKey as EcdsaPublicKey, Signature as EcdsaSignature,
};
use miden_protocol::crypto::dsa::falcon512_poseidon2::Signature as Poseidon2FalconSignature;
use miden_protocol::note::NoteId;
use miden_protocol::transaction::TransactionSummary;
use miden_protocol::utils::serde::Deserializable;
use miden_protocol::{Felt, Word};
use serde_json::Value;

use crate::error::{MultisigError, Result};
use crate::keystore::{ensure_hex_prefix, word_from_hex};
use crate::payload::ProposalPayload;
use crate::procedures::ProcedureName;

/// Status of a proposal in the signing workflow.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProposalStatus {
    Pending,
    Ready,
    Finalized,
}

impl ProposalStatus {
    pub fn is_ready(&self) -> bool {
        matches!(self, ProposalStatus::Ready)
    }

    pub fn is_pending(&self) -> bool {
        matches!(self, ProposalStatus::Pending)
    }
}

/// Types of transactions supported by the multisig SDK.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransactionType {
    P2ID {
        recipient: AccountId,
        faucet_id: AccountId,
        amount: u64,
    },
    ConsumeNotes {
        note_ids: Vec<NoteId>,
    },
    AddCosigner {
        new_commitment: Word,
    },
    RemoveCosigner {
        commitment: Word,
    },
    SwitchGuardian {
        new_endpoint: String,
        new_commitment: Word,
    },
    UpdateProcedureThreshold {
        procedure: ProcedureName,
        new_threshold: u32,
    },
    UpdateSigners {
        new_threshold: u32,
        signer_commitments: Vec<Word>,
    },
}

impl TransactionType {
    /// Creates a P2ID transfer transaction.
    pub fn transfer(recipient: AccountId, faucet_id: AccountId, amount: u64) -> Self {
        Self::P2ID {
            recipient,
            faucet_id,
            amount,
        }
    }

    /// Creates a ConsumeNotes transaction.
    pub fn consume_notes(note_ids: Vec<NoteId>) -> Self {
        Self::ConsumeNotes { note_ids }
    }

    /// Creates an AddCosigner transaction.
    pub fn add_cosigner(new_commitment: Word) -> Self {
        Self::AddCosigner { new_commitment }
    }

    /// Creates a RemoveCosigner transaction.
    pub fn remove_cosigner(commitment: Word) -> Self {
        Self::RemoveCosigner { commitment }
    }

    /// Creates a SwitchGuardian transaction.
    pub fn switch_guardian(new_endpoint: impl Into<String>, new_commitment: Word) -> Self {
        Self::SwitchGuardian {
            new_endpoint: new_endpoint.into(),
            new_commitment,
        }
    }

    /// Creates an UpdateProcedureThreshold transaction.
    pub fn update_procedure_threshold(procedure: ProcedureName, new_threshold: u32) -> Self {
        Self::UpdateProcedureThreshold {
            procedure,
            new_threshold,
        }
    }

    /// Creates an UpdateSigners transaction.
    pub fn update_signers(new_threshold: u32, signer_commitments: Vec<Word>) -> Self {
        Self::UpdateSigners {
            new_threshold,
            signer_commitments,
        }
    }

    pub(crate) fn proposal_type(&self) -> Option<&'static str> {
        match self {
            Self::P2ID { .. } => Some("p2id"),
            Self::ConsumeNotes { .. } => Some("consume_notes"),
            Self::AddCosigner { .. } => Some("add_signer"),
            Self::RemoveCosigner { .. } => Some("remove_signer"),
            Self::SwitchGuardian { .. } => Some("switch_guardian"),
            Self::UpdateProcedureThreshold { .. } => Some("update_procedure_threshold"),
            Self::UpdateSigners { .. } => None,
        }
    }

    /// Returns a stable transaction type name for diagnostics and flow checks.
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::P2ID { .. } => "P2ID",
            Self::ConsumeNotes { .. } => "ConsumeNotes",
            Self::AddCosigner { .. } => "AddCosigner",
            Self::RemoveCosigner { .. } => "RemoveCosigner",
            Self::SwitchGuardian { .. } => "SwitchGuardian",
            Self::UpdateProcedureThreshold { .. } => "UpdateProcedureThreshold",
            Self::UpdateSigners { .. } => "UpdateSigners",
        }
    }

    /// Returns true when execution can proceed without a GUARDIAN acknowledgment.
    pub fn supports_offline_execution(&self) -> bool {
        matches!(self, Self::SwitchGuardian { .. })
    }

    /// Returns true when execution requires a GUARDIAN acknowledgment signature.
    pub fn requires_guardian_ack(&self) -> bool {
        !self.supports_offline_execution()
    }
}

/// Metadata needed to reconstruct and finalize a proposal.
#[derive(Debug, Clone, Default)]
pub struct ProposalMetadata {
    pub tx_summary_json: Option<Value>,
    pub proposal_type: Option<String>,
    pub new_threshold: Option<u64>,
    pub signer_commitments_hex: Vec<String>,
    pub salt_hex: Option<String>,

    pub recipient_hex: Option<String>,
    pub faucet_id_hex: Option<String>,
    pub amount: Option<u64>,

    pub note_ids_hex: Vec<String>,

    pub new_guardian_pubkey_hex: Option<String>,
    pub new_guardian_endpoint: Option<String>,
    pub target_procedure: Option<String>,

    pub required_signatures: Option<usize>,
    pub signers: Vec<String>,
}

impl ProposalMetadata {
    /// Converts salt hex to Word.
    pub fn salt(&self) -> Result<Word> {
        match &self.salt_hex {
            Some(value) => word_from_hex(value).map_err(MultisigError::InvalidConfig),
            None => Ok(Word::from([Felt::new(0); 4])),
        }
    }

    /// Converts signer commitments to Words.
    pub fn signer_commitments(&self) -> Result<Vec<Word>> {
        let mut seen = HashSet::new();
        let mut commitments = Vec::with_capacity(self.signer_commitments_hex.len());

        for hex in &self.signer_commitments_hex {
            let commitment = word_from_hex(hex).map_err(MultisigError::InvalidConfig)?;
            let key = ensure_hex_prefix(hex).to_lowercase();
            if !seen.insert(key) {
                return Err(MultisigError::InvalidConfig(format!(
                    "duplicate signer commitment in metadata: {}",
                    hex
                )));
            }
            commitments.push(commitment);
        }

        Ok(commitments)
    }

    /// Converts note ID hex strings to NoteIds.
    pub fn note_ids(&self) -> Result<Vec<NoteId>> {
        self.note_ids_hex
            .iter()
            .map(|hex| {
                let word = word_from_hex(hex).map_err(MultisigError::InvalidConfig)?;
                Ok(NoteId::from_raw(word))
            })
            .collect()
    }

    pub(crate) fn to_transaction_type(&self, proposal_type: &str) -> Result<TransactionType> {
        if proposal_type.is_empty() {
            return Err(MultisigError::InvalidConfig(
                "proposal metadata.proposal_type is required".to_string(),
            ));
        }

        match proposal_type {
            "consume_notes" => {
                if self.note_ids_hex.is_empty() {
                    return Err(MultisigError::InvalidConfig(
                        "consume_notes proposal requires metadata.note_ids".to_string(),
                    ));
                }
                Ok(TransactionType::ConsumeNotes {
                    note_ids: self.note_ids()?,
                })
            }
            "p2id" => {
                let recipient_str = self.recipient_hex.as_ref().ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "p2id proposal requires metadata.recipient_id".to_string(),
                    )
                })?;
                let faucet_str = self.faucet_id_hex.as_ref().ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "p2id proposal requires metadata.faucet_id".to_string(),
                    )
                })?;
                let parsed_amount = self.amount.ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "p2id proposal requires metadata.amount".to_string(),
                    )
                })?;
                let recipient = AccountId::from_hex(recipient_str).map_err(|e| {
                    MultisigError::InvalidConfig(format!("invalid recipient: {}", e))
                })?;
                let faucet_id = AccountId::from_hex(faucet_str).map_err(|e| {
                    MultisigError::InvalidConfig(format!("invalid faucet_id: {}", e))
                })?;
                Ok(TransactionType::P2ID {
                    recipient,
                    faucet_id,
                    amount: parsed_amount,
                })
            }
            "switch_guardian" => {
                let pubkey_hex = self.new_guardian_pubkey_hex.as_ref().ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "switch_guardian proposal requires metadata.new_guardian_pubkey"
                            .to_string(),
                    )
                })?;
                let endpoint = self.new_guardian_endpoint.as_ref().ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "switch_guardian proposal requires metadata.new_guardian_endpoint"
                            .to_string(),
                    )
                })?;
                let new_commitment =
                    word_from_hex(pubkey_hex).map_err(MultisigError::InvalidConfig)?;
                Ok(TransactionType::SwitchGuardian {
                    new_endpoint: endpoint.clone(),
                    new_commitment,
                })
            }
            "update_procedure_threshold" => {
                let threshold = self.new_threshold.ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "update_procedure_threshold proposal requires metadata.target_threshold"
                            .to_string(),
                    )
                })?;
                let procedure_name = self.target_procedure.as_ref().ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "update_procedure_threshold proposal requires metadata.target_procedure"
                            .to_string(),
                    )
                })?;
                let procedure = procedure_name
                    .parse()
                    .map_err(MultisigError::InvalidConfig)?;
                Ok(TransactionType::UpdateProcedureThreshold {
                    procedure,
                    new_threshold: threshold as u32,
                })
            }
            "add_signer" => {
                let threshold = self.new_threshold.ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "add_signer proposal requires metadata.target_threshold".to_string(),
                    )
                })?;
                let proposed_signers = self.signer_commitments()?;
                if proposed_signers.is_empty() {
                    return Err(MultisigError::InvalidConfig(
                        "add_signer proposal requires metadata.signer_commitments".to_string(),
                    ));
                }
                Ok(TransactionType::UpdateSigners {
                    new_threshold: threshold as u32,
                    signer_commitments: proposed_signers,
                })
            }
            "remove_signer" => {
                let threshold = self.new_threshold.ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "remove_signer proposal requires metadata.target_threshold".to_string(),
                    )
                })?;
                let proposed_signers = self.signer_commitments()?;
                if proposed_signers.is_empty() {
                    return Err(MultisigError::InvalidConfig(
                        "remove_signer proposal requires metadata.signer_commitments".to_string(),
                    ));
                }
                Ok(TransactionType::UpdateSigners {
                    new_threshold: threshold as u32,
                    signer_commitments: proposed_signers,
                })
            }
            "change_threshold" => {
                let threshold = self.new_threshold.ok_or_else(|| {
                    MultisigError::InvalidConfig(
                        "change_threshold proposal requires metadata.target_threshold".to_string(),
                    )
                })?;
                let proposed_signers = self.signer_commitments()?;
                if proposed_signers.is_empty() {
                    return Err(MultisigError::InvalidConfig(
                        "change_threshold proposal requires metadata.signer_commitments"
                            .to_string(),
                    ));
                }
                Ok(TransactionType::UpdateSigners {
                    new_threshold: threshold as u32,
                    signer_commitments: proposed_signers,
                })
            }
            other => Err(MultisigError::UnknownTransactionType(other.to_string())),
        }
    }
}

/// A proposal signature entry.
#[derive(Debug, Clone)]
pub struct ProposalSignatureEntry {
    pub signer_commitment: String,
    pub signature_hex: String,
    pub scheme: SignatureScheme,
    pub public_key_hex: Option<String>,
}

impl ProposalSignatureEntry {
    fn validate(&self) -> Result<()> {
        word_from_hex(&self.signer_commitment).map_err(MultisigError::InvalidConfig)?;

        let signature_hex = ensure_hex_prefix(&self.signature_hex);
        match self.scheme {
            SignatureScheme::Falcon => {
                Poseidon2FalconSignature::from_hex(&signature_hex).map_err(|e| {
                    MultisigError::Signature(format!("invalid proposal signature: {}", e))
                })?;
            }
            SignatureScheme::Ecdsa => {
                let signature_bytes =
                    hex::decode(signature_hex.trim_start_matches("0x")).map_err(|e| {
                        MultisigError::Signature(format!("invalid ECDSA signature hex: {}", e))
                    })?;
                EcdsaSignature::read_from_bytes(&signature_bytes).map_err(|e| {
                    MultisigError::Signature(format!(
                        "invalid ECDSA proposal signature bytes: {}",
                        e
                    ))
                })?;

                let public_key_hex = self.public_key_hex.as_ref().ok_or_else(|| {
                    MultisigError::Signature(
                        "ECDSA proposal signatures require a public key".to_string(),
                    )
                })?;
                let public_key_bytes = hex::decode(public_key_hex.trim_start_matches("0x"))
                    .map_err(|e| {
                        MultisigError::Signature(format!("invalid ECDSA public key hex: {}", e))
                    })?;
                EcdsaPublicKey::read_from_bytes(&public_key_bytes).map_err(|e| {
                    MultisigError::Signature(format!(
                        "invalid ECDSA proposal public key bytes: {}",
                        e
                    ))
                })?;
            }
        }

        Ok(())
    }
}

/// A proposal for a multisig transaction.
#[derive(Debug, Clone)]
pub struct Proposal {
    pub id: String,
    pub nonce: u64,
    pub transaction_type: TransactionType,
    pub status: ProposalStatus,
    pub tx_summary: TransactionSummary,
    pub signatures: Vec<ProposalSignatureEntry>,
    pub metadata: ProposalMetadata,
}

impl Proposal {
    pub fn from(delta: &DeltaObject) -> Result<Self> {
        let payload: ProposalPayload = serde_json::from_str(&delta.delta_payload)?;

        let tx_summary = TransactionSummary::from_json(&payload.tx_summary).map_err(|e| {
            MultisigError::MidenClient(format!("failed to parse tx_summary: {}", e))
        })?;

        let metadata_payload = payload.metadata.clone().ok_or_else(|| {
            MultisigError::InvalidConfig("proposal is missing metadata".to_string())
        })?;
        let proposal_type = metadata_payload.proposal_type.clone();
        let required_signatures = metadata_payload.required_signatures.ok_or_else(|| {
            MultisigError::InvalidConfig(
                "proposal metadata.required_signatures is required".to_string(),
            )
        })?;
        let required_signatures: usize = usize::try_from(required_signatures).map_err(|_| {
            MultisigError::InvalidConfig(
                "proposal metadata.required_signatures exceeds platform limits".to_string(),
            )
        })?;

        let new_threshold = metadata_payload.target_threshold;
        let signer_commitments_hex = metadata_payload.signer_commitments;
        let salt_hex = metadata_payload.salt;
        let recipient_hex = metadata_payload.recipient_id;
        let faucet_id_hex = metadata_payload.faucet_id;
        let amount = metadata_payload.amount.as_deref().map(|value| {
            value.parse::<u64>().map_err(|e| {
                MultisigError::InvalidConfig(format!(
                    "invalid metadata.amount value '{}': {}",
                    value, e
                ))
            })
        });
        let amount = match amount {
            Some(parsed) => Some(parsed?),
            None => None,
        };
        let note_ids_hex = metadata_payload.note_ids;

        let new_guardian_pubkey_hex = metadata_payload.new_guardian_pubkey;
        let new_guardian_endpoint = metadata_payload.new_guardian_endpoint;
        let target_procedure = metadata_payload.target_procedure;

        let mut metadata = ProposalMetadata {
            tx_summary_json: Some(payload.tx_summary.clone()),
            proposal_type: Some(proposal_type.clone()),
            new_threshold,
            signer_commitments_hex: signer_commitments_hex.clone(),
            salt_hex,
            recipient_hex: recipient_hex.clone(),
            faucet_id_hex: faucet_id_hex.clone(),
            amount,
            note_ids_hex: note_ids_hex.clone(),
            new_guardian_pubkey_hex: new_guardian_pubkey_hex.clone(),
            new_guardian_endpoint: new_guardian_endpoint.clone(),
            target_procedure: target_procedure.clone(),
            required_signatures: Some(required_signatures),
            signers: Vec::new(),
        };
        let transaction_type = metadata.to_transaction_type(&proposal_type)?;

        let mut seen_signers = HashSet::new();
        let mut signatures = Vec::with_capacity(payload.signatures.len());
        for signature in &payload.signatures {
            let (scheme, signature_hex, public_key_hex) = match &signature.signature {
                ProposalSignature::Falcon { signature } => {
                    (SignatureScheme::Falcon, signature.clone(), None)
                }
                ProposalSignature::Ecdsa {
                    signature,
                    public_key,
                } => (
                    SignatureScheme::Ecdsa,
                    signature.clone(),
                    public_key.clone(),
                ),
            };

            let entry = ProposalSignatureEntry {
                signer_commitment: signature.signer_id.clone(),
                signature_hex,
                scheme,
                public_key_hex,
            };
            entry.validate()?;

            if !seen_signers.insert(entry.signer_commitment.to_lowercase()) {
                return Err(MultisigError::InvalidConfig(format!(
                    "duplicate proposal signature for signer {}",
                    entry.signer_commitment
                )));
            }

            metadata.signers.push(entry.signer_commitment.clone());
            signatures.push(entry);
        }

        let commitment = tx_summary.to_commitment();
        let id = format!("0x{}", hex::encode(word_to_bytes(&commitment)));

        let mut proposal = Proposal {
            id,
            nonce: delta.nonce,
            transaction_type,
            status: ProposalStatus::Pending,
            tx_summary,
            signatures,
            metadata,
        };
        proposal.refresh_status();
        Ok(proposal)
    }

    /// Creates a new Proposal
    pub fn new(
        tx_summary: TransactionSummary,
        nonce: u64,
        transaction_type: TransactionType,
        mut metadata: ProposalMetadata,
    ) -> Self {
        let commitment = tx_summary.to_commitment();
        let id = format!("0x{}", hex::encode(word_to_bytes(&commitment)));

        let signatures_required = metadata
            .required_signatures
            .unwrap_or(metadata.signer_commitments_hex.len());
        metadata
            .required_signatures
            .get_or_insert(signatures_required);
        if metadata.proposal_type.is_none() {
            metadata.proposal_type = transaction_type.proposal_type().map(str::to_string);
        }

        let mut proposal = Self {
            id,
            nonce,
            transaction_type,
            status: ProposalStatus::Pending,
            tx_summary,
            signatures: Vec::new(),
            metadata,
        };
        proposal.refresh_status();
        proposal
    }

    pub fn has_signed(&self, signer_commitment_hex: &str) -> bool {
        self.metadata
            .signers
            .iter()
            .any(|s| s.eq_ignore_ascii_case(signer_commitment_hex))
    }

    pub fn signatures_collected(&self) -> usize {
        self.metadata.signers.len()
    }

    pub fn signatures_required(&self) -> usize {
        self.metadata
            .required_signatures
            .unwrap_or(self.metadata.signer_commitments_hex.len())
    }

    pub fn signature_counts(&self) -> (usize, usize) {
        (self.signatures_collected(), self.signatures_required())
    }

    pub fn signatures_needed(&self) -> usize {
        self.signatures_required()
            .saturating_sub(self.signatures_collected())
    }

    /// Returns the commitment hex strings of signers who haven't signed yet.
    pub fn missing_signers(&self) -> Vec<String> {
        if !self.status.is_pending() {
            return Vec::new();
        }

        let signed: HashSet<_> = self
            .metadata
            .signers
            .iter()
            .map(|s| s.to_lowercase())
            .collect();

        self.metadata
            .signer_commitments_hex
            .iter()
            .filter(|c| !signed.contains(&c.to_lowercase()))
            .cloned()
            .collect()
    }

    fn refresh_status(&mut self) {
        let signatures_required = self.signatures_required();
        self.status =
            if self.metadata.signers.len() >= signatures_required && signatures_required > 0 {
                ProposalStatus::Ready
            } else {
                ProposalStatus::Pending
            };
    }
}
/// Converts a Word to bytes.
fn word_to_bytes(word: &Word) -> Vec<u8> {
    word.iter()
        .flat_map(|felt| felt.as_canonical_u64().to_le_bytes())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use miden_protocol::account::delta::{AccountDelta, AccountStorageDelta, AccountVaultDelta};
    use miden_protocol::transaction::{InputNotes, RawOutputNotes};

    fn create_test_tx_summary() -> TransactionSummary {
        // Use a minimal valid account ID
        let account_id = AccountId::from_hex("0x7bfb0f38b0fafa103f86a805594170").unwrap();
        let delta = AccountDelta::new(
            account_id,
            AccountStorageDelta::default(),
            AccountVaultDelta::default(),
            Felt::ZERO,
        )
        .expect("Valid empty delta");

        TransactionSummary::new(
            delta,
            InputNotes::new(Vec::new()).unwrap(),
            RawOutputNotes::new(Vec::new()).unwrap(),
            Word::default(),
        )
    }

    #[test]
    fn test_word_from_hex_roundtrip() {
        let original = "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
        let word = word_from_hex(original).expect("hex should decode");
        let bytes = word_to_bytes(&word);
        let result = format!("0x{}", hex::encode(bytes));
        assert_eq!(original, result);
    }

    #[test]
    fn test_word_from_hex_rejects_non_canonical_field_element() {
        let invalid = format!("0x{}{}", "ff".repeat(8), "00".repeat(24));
        let err = word_from_hex(&invalid).expect_err("non-canonical field element should fail");
        assert!(err.contains("invalid field element"));
    }

    #[test]
    fn test_proposal_status_checks() {
        let pending = ProposalStatus::Pending;
        assert!(pending.is_pending());
        assert!(!pending.is_ready());

        let ready = ProposalStatus::Ready;
        assert!(ready.is_ready());
        assert!(!ready.is_pending());
    }

    #[test]
    fn test_transaction_type_transfer() {
        // Use valid Miden AccountId format
        let recipient = AccountId::from_hex("0x7bfb0f38b0fafa103f86a805594170").unwrap();
        let faucet_id = AccountId::from_hex("0x7bfb0f38b0fafa103f86a805594171").unwrap();
        let amount = 1000u64;

        let tx = TransactionType::transfer(recipient, faucet_id, amount);

        assert_eq!(
            tx,
            TransactionType::P2ID {
                recipient,
                faucet_id,
                amount
            }
        );
    }

    #[test]
    fn test_transaction_type_consume_notes() {
        let note_id = NoteId::from_raw(Word::default());
        let tx = TransactionType::consume_notes(vec![note_id]);

        assert_eq!(
            tx,
            TransactionType::ConsumeNotes {
                note_ids: vec![note_id]
            }
        );
    }

    #[test]
    fn test_transaction_type_add_cosigner() {
        let commitment = Word::default();
        let tx = TransactionType::add_cosigner(commitment);

        assert_eq!(
            tx,
            TransactionType::AddCosigner {
                new_commitment: commitment
            }
        );
    }

    #[test]
    fn test_transaction_type_remove_cosigner() {
        let commitment = Word::default();
        let tx = TransactionType::remove_cosigner(commitment);

        assert_eq!(tx, TransactionType::RemoveCosigner { commitment });
    }

    #[test]
    fn test_transaction_type_switch_guardian() {
        let endpoint = "http://new-guardian.example.com";
        let commitment = Word::default();

        let tx = TransactionType::switch_guardian(endpoint, commitment);

        assert_eq!(
            tx,
            TransactionType::SwitchGuardian {
                new_endpoint: endpoint.to_string(),
                new_commitment: commitment
            }
        );
    }

    #[test]
    fn test_transaction_type_switch_guardian_rejects_non_canonical_commitment() {
        let metadata = ProposalMetadata {
            new_guardian_pubkey_hex: Some(format!("0x{}{}", "ff".repeat(8), "00".repeat(24))),
            new_guardian_endpoint: Some("http://new-guardian.example.com".to_string()),
            ..Default::default()
        };

        let err = metadata
            .to_transaction_type("switch_guardian")
            .expect_err("non-canonical GUARDIAN commitment should be rejected");
        assert!(err.to_string().contains("invalid field element"));
    }

    #[test]
    fn test_transaction_type_update_signers() {
        let threshold = 2u32;
        let signers = vec![Word::default()];

        let tx = TransactionType::update_signers(threshold, signers.clone());

        assert_eq!(
            tx,
            TransactionType::UpdateSigners {
                new_threshold: threshold,
                signer_commitments: signers
            }
        );
    }

    #[test]
    fn test_transaction_type_requires_guardian_ack() {
        let recipient = AccountId::from_hex("0x7bfb0f38b0fafa103f86a805594170").unwrap();
        let faucet_id = AccountId::from_hex("0x7bfb0f38b0fafa103f86a805594171").unwrap();

        assert!(TransactionType::transfer(recipient, faucet_id, 1).requires_guardian_ack());
        assert!(
            !TransactionType::switch_guardian("http://new-guardian.example.com", Word::default())
                .requires_guardian_ack()
        );
    }

    #[test]
    fn test_transaction_type_supports_offline_execution() {
        let note_id = NoteId::from_raw(Word::default());
        assert!(!TransactionType::consume_notes(vec![note_id]).supports_offline_execution());
        assert!(
            TransactionType::switch_guardian("http://new-guardian.example.com", Word::default())
                .supports_offline_execution()
        );
    }

    #[test]
    fn test_proposal_signature_counts() {
        let pending = ProposalStatus::Pending;

        let proposal = Proposal {
            id: "0x123".to_string(),
            nonce: 1,
            transaction_type: TransactionType::add_cosigner(Word::default()),
            status: pending,
            tx_summary: create_test_tx_summary(),
            signatures: Vec::new(),
            metadata: ProposalMetadata {
                required_signatures: Some(3),
                signers: vec!["0xabc".to_string()],
                signer_commitments_hex: vec![
                    "0xabc".to_string(),
                    "0xdef".to_string(),
                    "0x123".to_string(),
                ],
                ..Default::default()
            },
        };

        assert_eq!(proposal.signature_counts(), (1, 3));
        assert_eq!(proposal.signatures_needed(), 2);
    }

    #[test]
    fn test_proposal_missing_signers() {
        let pending = ProposalStatus::Pending;

        let proposal = Proposal {
            id: "0x123".to_string(),
            nonce: 1,
            transaction_type: TransactionType::add_cosigner(Word::default()),
            status: pending,
            tx_summary: create_test_tx_summary(),
            signatures: Vec::new(),
            metadata: ProposalMetadata {
                signers: vec!["0xABC".to_string()], // uppercase to test case-insensitivity
                signer_commitments_hex: vec![
                    "0xabc".to_string(), // lowercase
                    "0xdef".to_string(),
                    "0x456".to_string(),
                ],
                ..Default::default()
            },
        };

        let missing = proposal.missing_signers();
        assert_eq!(missing.len(), 2);
        assert!(missing.contains(&"0xdef".to_string()));
        assert!(missing.contains(&"0x456".to_string()));
        // 0xabc should NOT be in missing (already signed)
        assert!(!missing.contains(&"0xabc".to_string()));
    }

    #[test]
    fn test_proposal_signatures_needed_when_ready() {
        let ready = ProposalStatus::Ready;

        let proposal = Proposal {
            id: "0x123".to_string(),
            nonce: 1,
            transaction_type: TransactionType::add_cosigner(Word::default()),
            status: ready,
            tx_summary: create_test_tx_summary(),
            signatures: Vec::new(),
            metadata: ProposalMetadata {
                required_signatures: Some(2),
                signers: vec!["0xabc".to_string(), "0xdef".to_string()],
                ..Default::default()
            },
        };

        assert_eq!(proposal.signatures_needed(), 0);
    }

    // ==================== ProposalMetadata parser tests ====================

    #[test]
    fn test_metadata_salt_valid() {
        let metadata = ProposalMetadata {
            salt_hex: Some(
                "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20".to_string(),
            ),
            ..Default::default()
        };

        let salt = metadata.salt().expect("salt should parse");
        // Verify it's not the default Word
        assert_ne!(salt, Word::default());
    }

    #[test]
    fn test_metadata_salt_rejects_non_canonical_field_element() {
        let metadata = ProposalMetadata {
            salt_hex: Some(format!("0x{}{}", "ff".repeat(8), "00".repeat(24))),
            ..Default::default()
        };

        let err = metadata
            .salt()
            .expect_err("non-canonical salt should be rejected");
        assert!(err.to_string().contains("invalid field element"));
    }

    #[test]
    fn test_metadata_salt_none_returns_default() {
        let metadata = ProposalMetadata::default();

        let salt = metadata.salt().expect("salt should return default");
        assert_eq!(salt, Word::default());
    }

    #[test]
    fn test_metadata_signer_commitments_valid() {
        let hex1 = "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
        let hex2 = "0x2122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40";

        let metadata = ProposalMetadata {
            signer_commitments_hex: vec![hex1.to_string(), hex2.to_string()],
            ..Default::default()
        };

        let commitments = metadata.signer_commitments().expect("should parse");
        assert_eq!(commitments.len(), 2);
    }

    #[test]
    fn test_metadata_signer_commitments_invalid_hex() {
        let metadata = ProposalMetadata {
            signer_commitments_hex: vec!["not_valid_hex".to_string()],
            ..Default::default()
        };

        assert!(metadata.signer_commitments().is_err());
    }

    #[test]
    fn test_metadata_note_ids_valid() {
        // NoteId is 32 bytes = 64 hex chars
        let note_hex = "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";

        let metadata = ProposalMetadata {
            note_ids_hex: vec![note_hex.to_string()],
            ..Default::default()
        };

        let note_ids = metadata.note_ids().expect("should parse");
        assert_eq!(note_ids.len(), 1);
    }
}