miden-standards 0.17.0

Standards of the Miden protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::num::NonZeroU32;

use miden_protocol::account::component::{
    AccountComponentCode,
    AccountComponentMetadata,
    FeltSchema,
    SchemaType,
    StorageSchema,
    StorageSlotSchema,
};
use miden_protocol::account::{
    AccountComponent,
    AccountComponentName,
    AccountProcedureRoot,
    StorageMap,
    StorageMapKey,
    StorageSlot,
    StorageSlotName,
};
use miden_protocol::block::BlockNumber;
use miden_protocol::crypto::SequentialCommit;
use miden_protocol::errors::AccountError;
use miden_protocol::utils::sync::LazyLock;
use miden_protocol::{EMPTY_WORD, Felt, WORD_SIZE, Word, ZERO};

use super::{Approver, ApproverSet, FeeConversionInfo};
use crate::account::account_component_code;
use crate::procedure_root;

account_component_code!(MULTISIG_CODE, "miden-standards-auth-multisig.masp");

// PROCEDURE ROOTS
// ================================================================================================

/// MASL library namespace used for procedure-root lookups. Distinct from [`AuthMultisig::NAME`],
/// which mirrors the standards-side MASM module path.
const MULTISIG_LIBRARY_PATH: &str = "miden::standards::components::auth::multisig";

// Initialize the procedure root of the `set_procedure_threshold` procedure only once. It gates
// edits to per-procedure overrides, so [`AuthMultisig::new`] uses it to reject overrides that
// exceed its own threshold.
procedure_root!(
    MULTISIG_SET_PROCEDURE_THRESHOLD,
    MULTISIG_LIBRARY_PATH,
    AuthMultisig::SET_PROCEDURE_THRESHOLD_PROC_NAME,
    AuthMultisig::code()
);

// CONSTANTS
// ================================================================================================

pub(super) static THRESHOLD_CONFIG_SLOT_NAME: LazyLock<StorageSlotName> = LazyLock::new(|| {
    StorageSlotName::new("miden::standards::auth::multisig::threshold_config")
        .expect("storage slot name should be valid")
});

pub(super) static APPROVER_PUBKEYS_SLOT_NAME: LazyLock<StorageSlotName> = LazyLock::new(|| {
    StorageSlotName::new("miden::standards::auth::multisig::approver_public_keys")
        .expect("storage slot name should be valid")
});

pub(super) static APPROVER_SCHEME_ID_SLOT_NAME: LazyLock<StorageSlotName> = LazyLock::new(|| {
    StorageSlotName::new("miden::standards::auth::multisig::approver_schemes")
        .expect("storage slot name should be valid")
});

pub(super) static EXECUTED_TRANSACTIONS_SLOT_NAME: LazyLock<StorageSlotName> =
    LazyLock::new(|| {
        StorageSlotName::new("miden::standards::auth::multisig::executed_transactions")
            .expect("storage slot name should be valid")
    });

static PROCEDURE_THRESHOLDS_SLOT_NAME: LazyLock<StorageSlotName> = LazyLock::new(|| {
    StorageSlotName::new("miden::standards::auth::multisig::procedure_thresholds")
        .expect("storage slot name should be valid")
});

// MULTISIG AUTHENTICATION COMPONENT
// ================================================================================================

/// Configuration for [`AuthMultisig`] component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthMultisigConfig {
    approver_set: ApproverSet,
    proc_thresholds: BTreeMap<AccountProcedureRoot, u32>,
}

impl AuthMultisigConfig {
    /// Creates a new configuration from the given approver set.
    pub fn new(approver_set: ApproverSet) -> Self {
        Self {
            approver_set,
            proc_thresholds: BTreeMap::new(),
        }
    }

    /// Attaches a per-procedure threshold map. Each procedure threshold must be at least 1 and
    /// at most the number of approvers.
    pub fn with_proc_thresholds(
        mut self,
        proc_thresholds: Vec<(AccountProcedureRoot, u32)>,
    ) -> Result<Self, AccountError> {
        let num_approvers = self.approver_set.approvers().len() as u32;
        let mut thresholds = BTreeMap::new();
        for (proc_root, threshold) in proc_thresholds {
            if threshold == 0 {
                return Err(AccountError::other("procedure threshold must be at least 1"));
            }
            if threshold > num_approvers {
                return Err(AccountError::other(
                    "procedure threshold cannot be greater than number of approvers",
                ));
            }
            // The map keys the threshold by procedure root, so a repeated root is a caller mistake
            // rather than a silent overwrite.
            if thresholds.insert(proc_root, threshold).is_some() {
                return Err(AccountError::other(
                    "duplicate procedure roots are not allowed in the procedure threshold map",
                ));
            }
        }
        self.proc_thresholds = thresholds;
        Ok(self)
    }

    pub fn approver_set(&self) -> &ApproverSet {
        &self.approver_set
    }

    pub fn approvers(&self) -> &[Approver] {
        self.approver_set.approvers()
    }

    pub fn default_threshold(&self) -> u32 {
        self.approver_set.threshold().get()
    }

    pub fn proc_thresholds(&self) -> &BTreeMap<AccountProcedureRoot, u32> {
        &self.proc_thresholds
    }
}

/// An [`AccountComponent`] implementing a multisig authentication.
///
/// It enforces a threshold of approver signatures for every transaction, with optional
/// per-procedure threshold overrides.
///
/// # Auth args
///
/// The transaction's auth args are the commitment to [`MultisigAuthArgs`].
///
/// # Fees
///
/// Before authenticating, `auth_tx_multisig` pays the transaction fee via
/// `miden::standards::fee::pay_fee`: it creates a public TX_FEE note (see
/// [`TxFeeNote`](crate::note::TxFeeNote)) funded from the account's vault, so on
/// fee-charging chains the account must hold a sufficient balance of the native fee asset. The
/// conversion info from the auth args must name the reference block's fee asset at rate 1/1 (see
/// [`FeeConversionInfo::one_to_one`](super::FeeConversionInfo::one_to_one)). On chains with a
/// zero verification base fee no note is created. The fee note is created before the transaction
/// summary, so it is covered by the approver signatures.
///
/// # Expiration
///
/// Two independent expirations apply, and the earlier one ends the transaction's validity.
///
/// The approval expiration defines how long the signature stays usable. It is set with
/// [`MultisigAuthArgs::with_approval_expiration_delta`] and is measured from the block the
/// summary binds, and is bound by the summary itself.
///
/// The transaction's own expiration delta is a freshness bound: a procedure that reads mutable
/// foreign state through FPI caps how stale that read may be.
///
/// Neither is set by default: the signatures of an approval without an expiration stay usable for
/// as long as the summary they cover can be reproduced.
///
/// # Privacy
///
/// Approvers using [`AuthScheme::EcdsaK256Keccak`][scheme] disclose their public key and signature
/// at proving time and therefore do not get public-key privacy; approvers using
/// [`Falcon512Poseidon2`][falcon] do. See [`Approver`](super::Approver) for details.
///
/// [scheme]: miden_protocol::account::auth::AuthScheme::EcdsaK256Keccak
/// [falcon]: miden_protocol::account::auth::AuthScheme::Falcon512Poseidon2
///
/// # Security: private accounts and state withholding
///
/// A private account's state lives off-chain; the chain only holds a commitment to it. Whoever
/// advances the account must share the new state with the other approvers, otherwise those
/// approvers can no longer reconstruct the state behind the on-chain commitment and are
/// permanently locked out (and the signers retaining the state can drain its assets). This is a
/// data-availability problem inherent to private state, not an authorization one: the threshold
/// controls who *can* advance the state, not whether the resulting state is *shared*. A
/// per-procedure threshold of one lets a single approver do this; more generally, any quorum
/// smaller than the full approver set can advance the state and withhold it from the excluded
/// approvers.
///
/// The only configurations that fully prevent withholding are a public account (state is on-chain,
/// so nothing can be withheld), unanimity (`threshold == number of approvers`, so every approver
/// signs and therefore sees every state transition), or pairing the multisig with a guardian via
/// [`AuthGuardedMultisig`](super::AuthGuardedMultisig), whose guardian co-signs every transaction
/// and forwards the new state. For a private `m`-of-`n` wallet among mutually distrusting
/// approvers, prefer the guarded variant. The [`create_multisig_wallet`] helper enforces a related
/// bound: on private accounts it rejects per-procedure thresholds below the default.
///
/// [`create_multisig_wallet`]: crate::account::wallets::create_multisig_wallet
///
/// # Security: growing the signer set does not re-scale overrides
///
/// Per-procedure threshold overrides are absolute signature counts, not ratios. Updating the signer
/// set (via the `update_signers_and_threshold` account procedure) does not re-scale existing
/// overrides: the only cross-check is that each override stays `<= num_approvers`, which keeps it
/// reachable but never raises it. Growing the approver set therefore silently lowers the effective
/// signing ratio of every override (e.g. a `2`-of-`2` override becomes `2`-of-`n`). To preserve the
/// intended security level, re-evaluate the affected overrides and, where appropriate, raise them
/// via `set_procedure_threshold` in the same transaction that grows the signer set.
///
/// # Security: a raised override is only as strong as the threshold of `set_procedure_threshold`
///
/// An override can demand *more* signatures for a sensitive operation than the default, but that
/// extra protection is only as strong as the threshold guarding the procedure that can lower it,
/// `set_procedure_threshold`. That guard is `set_procedure_threshold`'s own override if one is set,
/// otherwise the default threshold; it is *not* necessarily the default. A group meeting that guard
/// can strip a stronger override in two transactions: first they lower it, then, in a later
/// transaction, they run the now-cheaper operation. Two transactions are required because the
/// signatures needed are read from the state as of the start of the transaction, so a lowered
/// override only takes effect in the next one.
///
/// For example, with 5 signers, a default of 2, `set_procedure_threshold` left at the default, and
/// a transfer requiring 4: two signers cannot transfer directly, but they can lower the transfer's
/// override to 2 in one transaction and transfer in the next.
///
/// It follows that setting an override higher than the threshold of `set_procedure_threshold`
/// (which may be the default) is pointless, because the excess signatures can always be removed by
/// that smaller group. To make a raised override hold, raise `set_procedure_threshold`'s own
/// threshold to at least that value, so undoing the protection costs as many signatures as the
/// operation it guards. [`AuthMultisig::new`] enforces this by rejecting any configuration whose
/// override exceeds the threshold of `set_procedure_threshold`. Note that
/// `update_signers_and_threshold` can also weaken an override by growing the signer set (see
/// above), so protect it the same way where relevant.
///
/// # Security: a lowered override authorizes changes to the procedure's output notes
///
/// The transaction threshold is derived only from the called account procedures, but a
/// transaction script can also change output notes without calling one: it can add attachments to
/// any output note, and add assets that were removed from the vault but not yet placed in a note.
/// These changes do not raise the threshold, so an override below the default lets that smaller
/// group of approvers also change the notes the procedure creates.
///
/// For example, a procedure with an override of 1 creates a note with a fixed recipient and
/// asset. A single approver can still add a secret attachment that the recipient cannot
/// reconstruct, so the recipient cannot consume the note. Or the approver can add a
/// [`NetworkAccountTarget`](crate::note::NetworkAccountTarget) attachment, which makes the account
/// fund a fee sponsorship for a network account the approver chooses.
///
/// To prevent this, a procedure with a lowered override should seal every note it creates with
/// `miden::protocol::output_note::seal`, after it adds its own assets and attachments. A sealed
/// note rejects further assets and attachments. The auth procedure cannot check this, so the
/// protection holds only when the procedure itself seals its notes.
#[derive(Debug)]
pub struct AuthMultisig {
    config: AuthMultisigConfig,
}

impl AuthMultisig {
    /// The name of the component.
    pub const NAME: &'static str = "miden::standards::auth::multisig";

    /// The name of the procedure that edits per-procedure threshold overrides.
    const SET_PROCEDURE_THRESHOLD_PROC_NAME: &'static str = "set_procedure_threshold";

    /// Returns the canonical [`AccountComponentName`] of this component.
    pub const fn name() -> AccountComponentName {
        AccountComponentName::from_static_str(Self::NAME)
    }

    /// Returns the [`AccountComponentCode`] of this component.
    pub fn code() -> &'static AccountComponentCode {
        &MULTISIG_CODE
    }

    /// Returns the procedure root of the `set_procedure_threshold` account procedure.
    pub fn set_procedure_threshold_root() -> AccountProcedureRoot {
        *MULTISIG_SET_PROCEDURE_THRESHOLD
    }

    /// Creates a new [`AuthMultisig`] component from the provided configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if a per-procedure override exceeds the threshold that guards
    /// `set_procedure_threshold` (its own override if set, otherwise the default threshold). Such
    /// an override is not enforceable, since a group meeting that lower threshold can strip it
    /// via `set_procedure_threshold`; see the type-level security notes.
    pub fn new(config: AuthMultisigConfig) -> Result<Self, AccountError> {
        // The threshold that must be met to edit overrides via `set_procedure_threshold`: its own
        // override if configured, otherwise the default threshold.
        let setter_threshold = config
            .proc_thresholds()
            .get(&Self::set_procedure_threshold_root())
            .copied()
            .unwrap_or_else(|| config.default_threshold());

        for &threshold in config.proc_thresholds().values() {
            if threshold > setter_threshold {
                return Err(AccountError::other(format!(
                    "per-procedure threshold override of {threshold} exceeds the threshold of \
                     {setter_threshold} that guards set_procedure_threshold; such an override can \
                     be removed by a smaller quorum. Raise the set_procedure_threshold override to \
                     at least {threshold} to make it enforceable"
                )));
            }
        }

        Ok(Self { config })
    }

    /// Returns the [`StorageSlotName`] where the threshold configuration is stored.
    pub fn threshold_config_slot() -> &'static StorageSlotName {
        &THRESHOLD_CONFIG_SLOT_NAME
    }

    /// Returns the [`StorageSlotName`] where the approver public keys are stored.
    pub fn approver_public_keys_slot() -> &'static StorageSlotName {
        &APPROVER_PUBKEYS_SLOT_NAME
    }

    // Returns the [`StorageSlotName`] where the approver scheme IDs are stored.
    pub fn approver_scheme_ids_slot() -> &'static StorageSlotName {
        &APPROVER_SCHEME_ID_SLOT_NAME
    }

    /// Returns the [`StorageSlotName`] where the executed transactions are stored.
    pub fn executed_transactions_slot() -> &'static StorageSlotName {
        &EXECUTED_TRANSACTIONS_SLOT_NAME
    }

    /// Returns the [`StorageSlotName`] where the procedure thresholds are stored.
    pub fn procedure_thresholds_slot() -> &'static StorageSlotName {
        &PROCEDURE_THRESHOLDS_SLOT_NAME
    }

    /// Returns the storage slot schema for the threshold configuration slot.
    pub fn threshold_config_slot_schema() -> (StorageSlotName, StorageSlotSchema) {
        (
            Self::threshold_config_slot().clone(),
            StorageSlotSchema::value(
                "Threshold configuration",
                [
                    FeltSchema::u32("threshold"),
                    FeltSchema::u32("num_approvers"),
                    FeltSchema::new_void(),
                    FeltSchema::new_void(),
                ],
            ),
        )
    }

    /// Returns the storage slot schema for the approver public keys slot.
    pub fn approver_public_keys_slot_schema() -> (StorageSlotName, StorageSlotSchema) {
        (
            Self::approver_public_keys_slot().clone(),
            StorageSlotSchema::map(
                "Approver public keys",
                SchemaType::u32(),
                SchemaType::pub_key(),
            ),
        )
    }

    // Returns the storage slot schema for the approver scheme IDs slot.
    pub fn approver_auth_scheme_slot_schema() -> (StorageSlotName, StorageSlotSchema) {
        (
            Self::approver_scheme_ids_slot().clone(),
            StorageSlotSchema::map(
                "Approver scheme IDs",
                SchemaType::u32(),
                SchemaType::auth_scheme(),
            ),
        )
    }

    /// Returns the storage slot schema for the executed transactions slot.
    pub fn executed_transactions_slot_schema() -> (StorageSlotName, StorageSlotSchema) {
        (
            Self::executed_transactions_slot().clone(),
            StorageSlotSchema::map(
                "Executed transactions",
                SchemaType::native_word(),
                SchemaType::native_word(),
            ),
        )
    }

    /// Returns the storage slot schema for the procedure thresholds slot.
    pub fn procedure_thresholds_slot_schema() -> (StorageSlotName, StorageSlotSchema) {
        (
            Self::procedure_thresholds_slot().clone(),
            StorageSlotSchema::map(
                "Procedure thresholds",
                SchemaType::native_word(),
                SchemaType::u32(),
            ),
        )
    }

    /// Returns the [`AccountComponentMetadata`] for this component.
    pub fn component_metadata() -> AccountComponentMetadata {
        let storage_schema = StorageSchema::new([
            Self::threshold_config_slot_schema(),
            Self::approver_public_keys_slot_schema(),
            Self::approver_auth_scheme_slot_schema(),
            Self::executed_transactions_slot_schema(),
            Self::procedure_thresholds_slot_schema(),
        ])
        .expect("storage schema should be valid");

        AccountComponentMetadata::new(Self::NAME)
            .with_description("Multisig authentication component using hybrid signature schemes")
            .with_storage_schema(storage_schema)
    }
}

impl From<AuthMultisig> for AccountComponent {
    fn from(multisig: AuthMultisig) -> Self {
        let mut storage_slots = Vec::with_capacity(5);

        // Threshold config slot (value: [threshold, num_approvers, 0, 0])
        let num_approvers = multisig.config.approvers().len() as u32;
        storage_slots.push(StorageSlot::with_value(
            AuthMultisig::threshold_config_slot().clone(),
            Word::from([multisig.config.default_threshold(), num_approvers, 0, 0]),
        ));

        // Approver public keys slot (map)
        let map_entries = multisig.config.approvers().iter().enumerate().map(|(i, approver)| {
            (StorageMapKey::from_index(i as u32), Word::from(approver.pub_key()))
        });

        // Safe to unwrap because we know that the map keys are unique.
        storage_slots.push(StorageSlot::with_map(
            AuthMultisig::approver_public_keys_slot().clone(),
            StorageMap::with_entries(map_entries).unwrap(),
        ));

        // Approver scheme IDs slot (map): [index, 0, 0, 0] => [scheme_id, 0, 0, 0]
        let scheme_id_entries =
            multisig.config.approvers().iter().enumerate().map(|(i, approver)| {
                (
                    StorageMapKey::from_index(i as u32),
                    Word::from([approver.auth_scheme() as u32, 0, 0, 0]),
                )
            });

        storage_slots.push(StorageSlot::with_map(
            AuthMultisig::approver_scheme_ids_slot().clone(),
            StorageMap::with_entries(scheme_id_entries).unwrap(),
        ));

        // Executed transactions slot (map)
        let executed_transactions = StorageMap::default();
        storage_slots.push(StorageSlot::with_map(
            AuthMultisig::executed_transactions_slot().clone(),
            executed_transactions,
        ));

        // Procedure thresholds slot (map: PROC_ROOT -> threshold)
        let proc_threshold_roots = StorageMap::with_entries(
            multisig.config.proc_thresholds().iter().map(|(proc_root, threshold)| {
                (StorageMapKey::from_raw(proc_root.as_word()), Word::from([*threshold, 0, 0, 0]))
            }),
        )
        .unwrap();
        storage_slots.push(StorageSlot::with_map(
            AuthMultisig::procedure_thresholds_slot().clone(),
            proc_threshold_roots,
        ));

        let metadata = AuthMultisig::component_metadata();

        AccountComponent::new(AuthMultisig::code().clone(), storage_slots, metadata).expect(
            "Multisig auth component should satisfy the requirements of a valid account component",
        )
    }
}

// MULTISIG AUTH ARGS
// ================================================================================================

/// The inputs the multisig authentication components receive through the transaction's auth args.
///
/// ```text
/// AUTH_ARGS: [BLOCK_WORD, SALT, CONVERSION_INFO]
/// ```
///
/// where `BLOCK_WORD` is `[bound_block_num, approval_expiration_block_num, 0, 0]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MultisigAuthArgs {
    bound_block_num: BlockNumber,
    approval_expiration_block_num: Option<BlockNumber>,
    salt: Word,
    conversion_info: Option<FeeConversionInfo>,
}

impl MultisigAuthArgs {
    /// Creates new multisig auth args binding the summary to the given block.
    ///
    /// The signers approve a transaction summary that commits to `bound_block_num`, so the party
    /// executing the transaction must pass the same block number, no matter how far the chain has
    /// advanced since. The block must be at or before the transaction's reference block and must
    /// be tracked by the transaction's partial blockchain, since that is the only way the kernel
    /// can read its commitment.
    ///
    /// The approval does not expire unless [`Self::with_approval_expiration_delta`] sets an
    /// expiration.
    ///
    /// `salt` is bound by the transaction summary and is what makes otherwise identical
    /// transactions distinguishable, which is what the replay protection of the multisig
    /// components relies on. It should be chosen at random.
    pub fn new(bound_block_num: BlockNumber, salt: Word) -> Self {
        Self {
            bound_block_num,
            approval_expiration_block_num: None,
            salt,
            conversion_info: None,
        }
    }

    /// Returns new multisig auth args whose approval expires `delta` blocks after the bound block.
    ///
    /// The transaction must be included by block `bound_block_num + delta`. The expiration is bound
    /// by the transaction summary, so the party executing the transaction can neither shorten nor
    /// extend it.
    ///
    /// # Errors
    ///
    /// Returns an error if `bound_block_num + delta` exceeds [`BlockNumber::MAX`].
    pub fn with_approval_expiration_delta(
        mut self,
        delta: NonZeroU32,
    ) -> Result<Self, AccountError> {
        let expiration_block_num =
            self.bound_block_num.as_u32().checked_add(delta.get()).ok_or_else(|| {
                AccountError::other(
                    "approval expiration block number exceeds the maximum block number",
                )
            })?;

        self.approval_expiration_block_num = Some(BlockNumber::from(expiration_block_num));
        Ok(self)
    }

    /// Returns new multisig auth args carrying the conversion info the fee payment needs.
    ///
    /// Must be [`FeeConversionInfo::one_to_one`] built with the reference block's fee faucet.
    /// Anything else, or no conversion info at all, aborts on chains that charge a non-zero
    /// verification base fee.
    #[must_use]
    pub fn with_conversion_info(mut self, conversion_info: FeeConversionInfo) -> Self {
        self.conversion_info = Some(conversion_info);
        self
    }

    // PUBLIC ACCESSORS
    // --------------------------------------------------------------------------------------------

    /// Returns the number of the block the transaction summary binds.
    pub fn bound_block_num(&self) -> BlockNumber {
        self.bound_block_num
    }

    /// Returns the first reference block at which the approvers' signatures are no longer valid,
    /// or `None` if the approval does not expire.
    pub fn approval_expiration_block_num(&self) -> Option<BlockNumber> {
        self.approval_expiration_block_num
    }

    /// Returns the salt bound by the transaction summary.
    pub fn salt(&self) -> Word {
        self.salt
    }

    /// Returns the fee conversion info, or `None` if none was committed - in which case the fee
    /// payment aborts on fee-charging chains.
    pub fn conversion_info(&self) -> Option<FeeConversionInfo> {
        self.conversion_info
    }
}

impl SequentialCommit for MultisigAuthArgs {
    type Commitment = Word;

    fn to_elements(&self) -> Vec<Felt> {
        let conversion_info = self.conversion_info.map_or(EMPTY_WORD, |info| info.to_word());
        let approval_expiration = self.approval_expiration_block_num.map_or(Felt::ZERO, Felt::from);

        let mut elements = Vec::with_capacity(3 * WORD_SIZE);
        elements.extend([Felt::from(self.bound_block_num), approval_expiration, ZERO, ZERO]);
        elements.extend(self.salt.iter());
        elements.extend(conversion_info.iter());
        elements
    }
}

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

#[cfg(test)]
mod tests {
    use alloc::string::ToString;

    use miden_protocol::account::auth::AuthSecretKey;
    use miden_protocol::account::{AccountBuilder, auth};

    use super::*;
    use crate::account::wallets::BasicWallet;

    /// Test multisig component setup with various configurations
    #[test]
    fn test_multisig_component_setup() {
        // Create test secret keys
        let sec_key_1 = AuthSecretKey::new_falcon512_poseidon2();
        let sec_key_2 = AuthSecretKey::new_falcon512_poseidon2();
        let sec_key_3 = AuthSecretKey::new_falcon512_poseidon2();

        // Create approvers list for multisig config
        let approvers = vec![
            Approver::new(sec_key_1.public_key().to_commitment(), sec_key_1.auth_scheme()),
            Approver::new(sec_key_2.public_key().to_commitment(), sec_key_2.auth_scheme()),
            Approver::new(sec_key_3.public_key().to_commitment(), sec_key_3.auth_scheme()),
        ];

        let threshold = 2u32;

        // Create multisig component
        let approver_set =
            ApproverSet::new(approvers.clone(), threshold).expect("invalid approver set");
        let multisig_component = AuthMultisig::new(AuthMultisigConfig::new(approver_set))
            .expect("multisig component creation failed");

        // Build account with multisig component
        let account = AccountBuilder::new([0; 32])
            .with_component(multisig_component)
            .with_component(BasicWallet)
            .build()
            .expect("account building failed");

        // Verify config slot: [threshold, num_approvers, 0, 0]
        let config_slot = account
            .storage()
            .get_item(AuthMultisig::threshold_config_slot())
            .expect("config storage slot access failed");
        assert_eq!(config_slot, Word::from([threshold, approvers.len() as u32, 0, 0]));

        // Verify approver pub keys slot
        for (i, approver) in approvers.iter().enumerate() {
            let stored_pub_key = account
                .storage()
                .get_map_item(
                    AuthMultisig::approver_public_keys_slot(),
                    StorageMapKey::from_index(i as u32),
                )
                .expect("approver public key storage map access failed");
            assert_eq!(stored_pub_key, Word::from(approver.pub_key()));
        }

        // Verify approver scheme IDs slot
        for (i, approver) in approvers.iter().enumerate() {
            let stored_scheme_id = account
                .storage()
                .get_map_item(
                    AuthMultisig::approver_scheme_ids_slot(),
                    StorageMapKey::from_index(i as u32),
                )
                .expect("approver scheme ID storage map access failed");
            assert_eq!(stored_scheme_id, Word::from([approver.auth_scheme() as u32, 0, 0, 0]));
        }
    }

    /// Test multisig component with minimum threshold (1 of 1)
    #[test]
    fn test_multisig_component_minimum_threshold() {
        let pub_key = AuthSecretKey::new_ecdsa_k256_keccak().public_key().to_commitment();
        let approvers = vec![Approver::new(pub_key, auth::AuthScheme::EcdsaK256Keccak)];
        let threshold = 1u32;

        let approver_set =
            ApproverSet::new(approvers.clone(), threshold).expect("invalid approver set");
        let multisig_component = AuthMultisig::new(AuthMultisigConfig::new(approver_set))
            .expect("multisig component creation failed");

        let account = AccountBuilder::new([0; 32])
            .with_component(multisig_component)
            .with_component(BasicWallet)
            .build()
            .expect("account building failed");

        // Verify storage layout
        let config_slot = account
            .storage()
            .get_item(AuthMultisig::threshold_config_slot())
            .expect("config storage slot access failed");
        assert_eq!(config_slot, Word::from([threshold, approvers.len() as u32, 0, 0]));

        let stored_pub_key = account
            .storage()
            .get_map_item(AuthMultisig::approver_public_keys_slot(), StorageMapKey::from_index(0))
            .expect("approver pub keys storage map access failed");
        assert_eq!(stored_pub_key, Word::from(pub_key));

        let stored_scheme_id = account
            .storage()
            .get_map_item(AuthMultisig::approver_scheme_ids_slot(), StorageMapKey::from_index(0))
            .expect("approver scheme IDs storage map access failed");
        assert_eq!(
            stored_scheme_id,
            Word::from([auth::AuthScheme::EcdsaK256Keccak as u32, 0, 0, 0])
        );
    }

    /// Test that a per-procedure threshold exceeding the number of approvers is rejected.
    #[test]
    fn test_proc_threshold_too_high() {
        let pub_key = AuthSecretKey::new_ecdsa_k256_keccak().public_key().to_commitment();
        let approvers = vec![Approver::new(pub_key, auth::AuthScheme::EcdsaK256Keccak)];
        let approver_set = ApproverSet::new(approvers, 1).expect("invalid approver set");

        let result = AuthMultisigConfig::new(approver_set)
            .with_proc_thresholds(vec![(BasicWallet::receive_asset_root(), 2)]);
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("procedure threshold cannot be greater than number of approvers")
        );
    }

    /// Test that an override exceeding the threshold guarding `set_procedure_threshold` (here the
    /// default, since it has no override of its own) is rejected by `AuthMultisig::new`, because a
    /// smaller quorum could lower it.
    #[test]
    fn test_proc_threshold_above_set_procedure_threshold_rejected() {
        let approvers = vec![
            Approver::new(
                AuthSecretKey::new_ecdsa_k256_keccak().public_key().to_commitment(),
                auth::AuthScheme::EcdsaK256Keccak,
            ),
            Approver::new(
                AuthSecretKey::new_ecdsa_k256_keccak().public_key().to_commitment(),
                auth::AuthScheme::EcdsaK256Keccak,
            ),
            Approver::new(
                AuthSecretKey::new_ecdsa_k256_keccak().public_key().to_commitment(),
                auth::AuthScheme::EcdsaK256Keccak,
            ),
        ];
        let approver_set = ApproverSet::new(approvers, 2).expect("invalid approver set");

        // The override (3) is within num_approvers, so `with_proc_thresholds` accepts it, but it
        // exceeds the default threshold (2) that guards `set_procedure_threshold`.
        let config = AuthMultisigConfig::new(approver_set)
            .with_proc_thresholds(vec![(BasicWallet::receive_asset_root(), 3)])
            .expect("an override within num_approvers is accepted by with_proc_thresholds");

        let err = AuthMultisig::new(config).unwrap_err();
        assert!(err.to_string().contains("exceeds the threshold"));
    }
}