miden-multisig-client 0.18.0

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
//! Internal helper functions for GUARDIAN client interactions.

use crate::guardian_endpoint::verify_endpoint_commitment;
use guardian_client::GuardianClient;
#[cfg(test)]
use guardian_shared::FromJson;
use guardian_shared::SignatureScheme;
use guardian_shared::ToJson;
use miden_client::account::Account;
use miden_client::rpc::domain::account::GetAccountRequest;
use miden_client::rpc::{GrpcError, RpcError};
use miden_client::transaction::{TransactionRequest, TransactionSummary};
use miden_protocol::Word;
use miden_protocol::account::AccountId;
use miden_protocol::utils::serde::Serializable;

use super::MultisigClient;
use crate::account::MultisigAccount;
use crate::builder::create_miden_client;
use crate::error::{MultisigError, Result, error_chain};
use crate::execution::build_final_transaction_request;
use crate::keystore::word_from_hex;
use crate::proposal::{Proposal, ProposalVerification, TransactionType};
use crate::transaction::word_to_hex;
use crate::transaction::{proposal_auth_args, summary_approval_expiration_block_num, summary_salt};

/// True for note-less storage-config transactions, whose post-submit state miden-client persists
/// incorrectly for private accounts, so local state must be rebuilt from the proven delta instead.
fn rebuilds_local_state_from_delta(transaction_type: &TransactionType) -> bool {
    match transaction_type {
        TransactionType::AddCosigner { .. }
        | TransactionType::RemoveCosigner { .. }
        | TransactionType::UpdateSigners { .. }
        | TransactionType::UpdateProcedureThreshold { .. }
        | TransactionType::SwitchGuardian { .. } => true,
        TransactionType::P2ID { .. }
        | TransactionType::ConsumeNotes { .. }
        | TransactionType::Custom => false,
    }
}

impl MultisigClient {
    /// Creates a GUARDIAN client (unauthenticated).
    pub(crate) async fn create_guardian_client(&self) -> Result<GuardianClient> {
        GuardianClient::connect(&self.guardian_endpoint)
            .await
            .map_err(|e| MultisigError::GuardianConnection(e.to_string()))
    }

    /// Creates an authenticated GUARDIAN client.
    pub(crate) async fn create_authenticated_guardian_client(&self) -> Result<GuardianClient> {
        let client = self.create_guardian_client().await?;
        Ok(client.with_signer(self.key_manager.clone()))
    }

    pub(crate) async fn get_on_chain_account_commitment(
        &self,
        account_id: AccountId,
    ) -> Result<Word> {
        let rpc_client = self.node_rpc_client();
        let (_, proof) = rpc_client
            .get_account(account_id, GetAccountRequest::new())
            .await
            .map_err(|e| match e {
                RpcError::RequestError {
                    error_kind: GrpcError::NotFound,
                    ..
                } => {
                    MultisigError::MidenClient(format!("account {} not found on chain", account_id))
                }
                other => MultisigError::miden_rpc_with_context(
                    format!("failed to fetch on-chain commitment for account {account_id}"),
                    other,
                ),
            })?;

        Ok(proof.account_witness().state_commitment())
    }

    pub(crate) async fn try_get_on_chain_account_commitment(
        &self,
        account_id: AccountId,
    ) -> Result<Option<Word>> {
        let rpc_client = self.node_rpc_client();
        match rpc_client
            .get_account(account_id, GetAccountRequest::new())
            .await
        {
            Ok((_, proof)) => {
                let commitment = proof.account_witness().state_commitment();
                if commitment == Word::default() {
                    Ok(None)
                } else {
                    Ok(Some(commitment))
                }
            }
            Err(RpcError::RequestError {
                error_kind: GrpcError::NotFound,
                ..
            }) => Ok(None),
            Err(e) => Err(MultisigError::miden_rpc_with_context(
                format!("failed to fetch on-chain commitment for account {account_id}"),
                e,
            )),
        }
    }

    /// Returns a reference to the current account, or error if none loaded.
    pub(crate) fn require_account(&self) -> Result<&MultisigAccount> {
        self.account
            .as_ref()
            .ok_or_else(|| MultisigError::MissingConfig("no account loaded".to_string()))
    }

    pub(crate) fn ensure_proposal_account_id(
        proposal_account_id: &str,
        expected_account_id: &AccountId,
    ) -> Result<()> {
        if proposal_account_id.eq_ignore_ascii_case(&expected_account_id.to_string()) {
            return Ok(());
        }

        Err(MultisigError::InvalidConfig(format!(
            "proposal is for account {} instead of {}",
            proposal_account_id, expected_account_id
        )))
    }

    /// Gets the GUARDIAN acknowledgment signature for a transaction.
    ///
    /// This pushes the delta to GUARDIAN and retrieves the server's signature.
    pub(crate) async fn get_guardian_ack_signature(
        &mut self,
        account: &MultisigAccount,
        nonce: u64,
        tx_summary: &TransactionSummary,
        tx_summary_commitment: Word,
    ) -> Result<crate::execution::SignatureAdvice> {
        let account_id = account.id();
        let prev_commitment = format!(
            "0x{}",
            hex::encode(Serializable::to_bytes(&account.commitment()))
        );

        // Push delta to GUARDIAN to get acknowledgment signature
        let mut guardian_client = self.create_authenticated_guardian_client().await?;
        let delta_payload = tx_summary.to_json();

        let push_response = guardian_client
            .push_delta(&account_id, nonce, &prev_commitment, &delta_payload)
            .await
            .map_err(|e| MultisigError::GuardianServer(format!("failed to push delta: {}", e)))?;

        // Get GUARDIAN ack signature
        let ack_sig = push_response.ack_sig.ok_or_else(|| {
            MultisigError::GuardianServer(
                "GUARDIAN did not return acknowledgment signature".to_string(),
            )
        })?;
        let ack_scheme = push_response
            .delta
            .as_ref()
            .and_then(|delta| delta.ack_scheme.as_deref())
            .ok_or_else(|| {
                MultisigError::GuardianServer(
                    "GUARDIAN did not return acknowledgment scheme".to_string(),
                )
            })
            .and_then(|ack_scheme| {
                SignatureScheme::from(ack_scheme).map_err(MultisigError::GuardianServer)
            })?;

        let (guardian_commitment_hex, raw_pubkey) = guardian_client
            .get_pubkey(Some(ack_scheme.as_str()))
            .await
            .map_err(|e| {
                MultisigError::GuardianServer(format!("failed to get GUARDIAN commitment: {}", e))
            })?;

        let guardian_commitment =
            word_from_hex(&guardian_commitment_hex).map_err(MultisigError::HexDecode)?;
        let expected_guardian_commitment = account.guardian_commitment()?;
        if guardian_commitment != expected_guardian_commitment {
            return Err(MultisigError::GuardianServer(format!(
                "GUARDIAN public key commitment {} does not match account commitment {}",
                word_to_hex(&guardian_commitment),
                word_to_hex(&expected_guardian_commitment)
            )));
        }

        let ack_signature = ack_scheme
            .parse_signature_hex(&ack_sig)
            .map_err(MultisigError::Signature)?;
        ack_scheme
            .build_signature_advice_entry(
                guardian_commitment,
                tx_summary_commitment,
                &ack_signature,
                push_response
                    .delta
                    .as_ref()
                    .and_then(|delta| delta.ack_pubkey.as_deref())
                    .or(raw_pubkey.as_deref()),
            )
            .map_err(MultisigError::Signature)
    }

    /// Verifies that a proposal's metadata reconstructs the same tx_summary
    /// commitment, and records the outcome on the proposal: `Verified`, or
    /// `Failed` with the message and whether the failure looked transient.
    /// Returns the error as well, so strict callers keep failing closed and
    /// listings can keep going with the outcome recorded.
    pub(crate) async fn verify_proposal_summary_binding(
        &mut self,
        proposal: &mut Proposal,
    ) -> Result<()> {
        let outcome = self.check_proposal_summary_binding(proposal).await;
        proposal.verification = match &outcome {
            Ok(()) => ProposalVerification::Verified,
            Err(e) => ProposalVerification::Failed {
                retryable: crate::rpc::is_transient_multisig_error(e)
                    || crate::transaction::is_stale_chain_error(e),
                message: e.to_string(),
            },
        };
        outcome
    }

    async fn check_proposal_summary_binding(&mut self, proposal: &Proposal) -> Result<()> {
        let tx_summary_commitment = proposal.tx_summary.to_commitment();

        let proposal_id_commitment = word_to_hex(&tx_summary_commitment);
        if !proposal.id.eq_ignore_ascii_case(&proposal_id_commitment) {
            return Err(MultisigError::InvalidConfig(format!(
                "proposal id {} does not match tx_summary commitment {}",
                proposal.id, proposal_id_commitment
            )));
        }

        // The anchor arrives from an untrusted party via GUARDIAN. Nothing here
        // executes against it, since the rebuild below runs at the tip, but it
        // has to name the block the signed summary binds: the TypeScript SDK
        // rebuilds at the block it names, and 0.18.0-rc.1 clients re-execute
        // at it. ChainAnchor deserialization already enforced internal
        // header/chain consistency.
        let chain_anchor = proposal.metadata.chain_anchor()?;
        if chain_anchor.block_commitment() != proposal.tx_summary.block_commitment() {
            return Err(MultisigError::InvalidConfig(format!(
                "proposal {} chain_anchor does not match the block commitment bound \
                 into its tx_summary",
                proposal.id
            )));
        }

        // Custom proposal types (issue #266) have no per-type reconstruction
        // recipe; the id ↔ tx_summary commitment match above is the only
        // available integrity guarantee for an opaque proposal. Guard the one
        // piece of transport metadata that gates readiness: a malformed payload
        // must not declare fewer required signatures than the account threshold,
        // or it could mark a custom proposal ready with too few cosigners.
        if matches!(proposal.transaction_type, TransactionType::Custom) {
            let account_threshold = self.require_account()?.threshold()? as usize;
            let declared = proposal
                .metadata
                .required_signatures
                .unwrap_or(account_threshold);
            if declared < account_threshold {
                return Err(MultisigError::InvalidConfig(format!(
                    "custom proposal {} declares {} required signatures, below the account threshold {}",
                    proposal.id, declared, account_threshold
                )));
            }
            return Ok(());
        }

        let account = self.require_account()?.clone();
        let salt = proposal.metadata.salt()?;
        if summary_salt(&proposal.tx_summary) != salt {
            return Err(MultisigError::InvalidConfig(format!(
                "proposal {} metadata salt does not match the salt bound into its tx_summary",
                proposal.id
            )));
        }
        let signer_commitments = proposal.metadata.signer_commitments()?;
        // The rebuild reads the chain's fee faucet from the synced protocol
        // configuration and executes at the tip, so the store has to have
        // synced to the block the summary binds; a cosigner that has only
        // just pulled the account has not.
        crate::transaction::sync_to_block(
            &mut self.miden_client,
            proposal.tx_summary.block_number(),
        )
        .await?;
        let auth_args = proposal_auth_args(&self.miden_client, &proposal.tx_summary).await?;

        // A consume-notes summary commits to *authenticated* consumption
        // (see `ensure_notes_authenticated`), which miden-client decides
        // from this store alone. Put the store in that mode before the
        // rebuild, or a cosigner that never held these notes reproduces a
        // different commitment (issue #409).
        if let TransactionType::ConsumeNotes {
            metadata_version: Some(crate::proposal::CONSUME_NOTES_METADATA_VERSION_V2),
            notes,
            ..
        } = &proposal.transaction_type
        {
            let decoded = notes
                .iter()
                .map(crate::proposal::SerializedNote::to_note)
                .collect::<Result<Vec<_>>>()?;
            let node_rpc = self.node_rpc_client();
            crate::transaction::ensure_notes_authenticated(
                &mut self.miden_client,
                &node_rpc,
                &decoded,
            )
            .await?;
        }

        let tx_request = build_final_transaction_request(
            &self.miden_client,
            &proposal.transaction_type,
            account.inner(),
            &auth_args,
            Vec::new(),
            proposal.metadata.new_threshold,
            Some(signer_commitments.as_slice()),
            self.key_manager.scheme(),
        )
        .await?;

        let reconstructed = crate::transaction::execute_for_summary_at_tip(
            &mut self.miden_client,
            account.id(),
            tx_request,
        )
        .await?;

        if reconstructed.to_commitment() != tx_summary_commitment {
            return Err(MultisigError::InvalidConfig(format!(
                "proposal {} metadata does not match tx_summary",
                proposal.id
            )));
        }

        Ok(())
    }

    /// An expired approval aborts in the auth procedure only at execution.
    /// The summary carries the deadline, so callers check it against the sync
    /// height before assembling advice or requesting the GUARDIAN ack.
    pub(crate) async fn assert_approval_not_expired(
        &self,
        proposal_id: &str,
        summary: &TransactionSummary,
    ) -> Result<()> {
        let Some(expiration) = summary_approval_expiration_block_num(summary) else {
            return Ok(());
        };
        let sync_height = self.miden_client.get_sync_height().await.map_err(|e| {
            MultisigError::miden_client_with_context("failed to read the sync height", e)
        })?;
        if sync_height >= expiration {
            return Err(MultisigError::InvalidConfig(format!(
                "proposal {proposal_id} approval expired at block {expiration}; the chain is at \
                 block {sync_height}, so the collected signatures no longer authorize it"
            )));
        }
        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn proposal_id_from_delta_payload(delta_payload: &str) -> Result<String> {
        let payload_json: serde_json::Value = serde_json::from_str(delta_payload).map_err(|e| {
            MultisigError::InvalidConfig(format!("failed to parse proposal delta payload: {}", e))
        })?;
        let tx_summary_json = payload_json.get("tx_summary").ok_or_else(|| {
            MultisigError::InvalidConfig("missing tx_summary in delta payload".to_string())
        })?;
        let tx_summary = TransactionSummary::from_json(tx_summary_json).map_err(|e| {
            MultisigError::InvalidConfig(format!("failed to parse tx_summary: {}", e))
        })?;
        Ok(word_to_hex(&tx_summary.to_commitment()))
    }

    /// Finalizes a transaction by executing it on-chain and updating local state.
    ///
    /// This handles the common post-execution logic for all proposal types. The
    /// transaction executes at the chain tip; the request declares the block its
    /// summary binds (see [`crate::transaction::execute_for_summary_at_tip`]).
    ///
    /// Note-less storage-config changes on private accounts take a manual
    /// execute/prove/submit pipeline and rebuild the account from the proven
    /// delta: the standard submit path otherwise leaves stale local state
    /// (cleared storage-map entries linger) and stages SMT roots that block a
    /// corrective overwrite. Note-bearing transactions keep the standard path to
    /// preserve note tracking. A full-state delta (private accounts) converts
    /// directly into the account; an incremental delta is applied onto the base.
    ///
    /// For a `SwitchGuardian` the new endpoint is registered only when it
    /// actually differs from the current one. On an unchanged endpoint the
    /// pushed switch delta canonicalizes normally; re-registering would overwrite
    /// the pre-switch base and double-apply the delta. Post-submit `sync_state`
    /// failures are ignored because GUARDIAN may not have canonicalized yet.
    pub(crate) async fn finalize_transaction(
        &mut self,
        account_id: AccountId,
        tx_request: TransactionRequest,
        transaction_type: &TransactionType,
    ) -> Result<()> {
        if let TransactionType::SwitchGuardian {
            new_endpoint,
            new_commitment,
        } = transaction_type
        {
            verify_endpoint_commitment(new_endpoint, *new_commitment, self.key_manager.scheme())
                .await?;
        }

        let new_guardian_endpoint =
            if let TransactionType::SwitchGuardian { new_endpoint, .. } = transaction_type {
                Some(new_endpoint.clone())
            } else {
                None
            };

        let updated_account: Account = if rebuilds_local_state_from_delta(transaction_type) {
            let base_account: Account = self
                .miden_client
                .get_account(account_id)
                .await
                .map_err(|e| {
                    MultisigError::miden_client_with_context(
                        "failed to get account before execution",
                        e,
                    )
                })?
                .ok_or_else(|| {
                    MultisigError::MissingConfig("account not found before execution".to_string())
                })?;

            crate::transaction::prepare_tip_execution(&mut self.miden_client, &tx_request).await?;
            let tx_result = self
                .miden_client
                .execute_transaction(account_id, tx_request)
                .await
                .map_err(|e| {
                    MultisigError::transaction_execution_with_context(
                        "transaction execution failed",
                        e,
                    )
                })?;

            let proven = self
                .miden_client
                .prove_transaction(&tx_result)
                .await
                .map_err(|e| {
                    MultisigError::transaction_execution_with_context(
                        "transaction proving failed",
                        e,
                    )
                })?;

            self.miden_client
                .submit_proven_transaction(proven, &tx_result)
                .await
                .map_err(|e| {
                    MultisigError::transaction_execution_with_context(
                        "transaction submission failed",
                        e,
                    )
                })?;

            let account_patch = tx_result.account_patch();
            let rebuilt: Account = if base_account.is_new() && !account_patch.code().is_empty() {
                account_patch.try_to_new_account().map_err(|e| {
                    MultisigError::MidenClient(format!(
                        "failed to build account from full state patch: {}",
                        e
                    ))
                })?
            } else {
                let mut acc = base_account;
                acc.apply_patch(account_patch).map_err(|e| {
                    MultisigError::MidenClient(format!(
                        "failed to apply transaction patch to account: {}",
                        e
                    ))
                })?;
                acc
            };

            self.add_or_update_account(&rebuilt, true).await?;

            let _ = self.miden_client.sync_state().await;

            rebuilt
        } else {
            self.submit_transaction_at_tip(account_id, tx_request)
                .await?;

            let _ = self.miden_client.sync_state().await;

            self.miden_client
                .get_account(account_id)
                .await
                .map_err(|e| {
                    MultisigError::MidenClient(format!("failed to get updated account: {}", e))
                })?
                .ok_or_else(|| {
                    MultisigError::MissingConfig("account not found after execution".to_string())
                })?
        };

        if let Some(endpoint) = new_guardian_endpoint {
            let switching_endpoint = endpoint != self.guardian_endpoint;
            self.guardian_endpoint = endpoint;
            self.account = Some(MultisigAccount::new(updated_account.clone()));

            if switching_endpoint {
                self.register_on_guardian().await.map_err(|e| {
                    MultisigError::GuardianServer(format!(
                        "transaction executed successfully but failed to register on new GUARDIAN: {}",
                        e
                    ))
                })?;
            }
        } else {
            let multisig_account = MultisigAccount::new(updated_account);
            self.account = Some(multisig_account);
        }

        Ok(())
    }

    /// Executes a transaction at the chain tip, proves it, submits it, and
    /// applies the resulting store update, syncing first when the store is
    /// still below the block the request binds. Otherwise the same pipeline as
    /// miden-client's `submit_new_transaction`.
    pub(crate) async fn submit_transaction_at_tip(
        &mut self,
        account_id: AccountId,
        tx_request: TransactionRequest,
    ) -> Result<()> {
        crate::transaction::prepare_tip_execution(&mut self.miden_client, &tx_request).await?;
        let tx_result = self
            .miden_client
            .execute_transaction(account_id, tx_request)
            .await
            .map_err(|e| {
                MultisigError::transaction_execution_with_context("transaction execution failed", e)
            })?;

        let proven = self
            .miden_client
            .prove_transaction(&tx_result)
            .await
            .map_err(|e| {
                MultisigError::transaction_execution_with_context("transaction proving failed", e)
            })?;

        let submission_height = self
            .miden_client
            .submit_proven_transaction(proven, &tx_result)
            .await
            .map_err(|e| {
                MultisigError::transaction_execution_with_context(
                    "transaction submission failed",
                    e,
                )
            })?;

        let tx_update = self
            .miden_client
            .get_transaction_store_update(&tx_result, submission_height)
            .await
            .map_err(|e| {
                MultisigError::MidenClient(format!(
                    "failed to build store update for submitted transaction: {e}"
                ))
            })?;
        self.miden_client
            .apply_transaction_update(tx_update)
            .await
            .map_err(|e| {
                MultisigError::transaction_execution_with_context(
                    "failed to apply store update for submitted transaction",
                    e,
                )
            })?;

        Ok(())
    }

    /// Resets the miden-client by creating a new instance with a fresh database.
    pub async fn reset_miden_client(&mut self) -> Result<()> {
        self.miden_client = create_miden_client(
            &self.account_dir,
            &self.miden_endpoint,
            self.note_transport_endpoint.as_deref(),
            &self.prover_config,
            &self.rpc_config,
        )
        .await?;
        Ok(())
    }

    /// Adds an account to miden-client if it doesn't exist, or updates it if it does.
    ///
    /// `overwrite` is forwarded to miden-client's `add_account` (its
    /// parameter of the same name), but is currently inert: upstream only
    /// consults it for already-tracked accounts, and the existence pre-check
    /// here routes those through the update path, which always overwrites.
    /// This helper never surfaces upstream's `overwrite: false` protection
    /// (`AccountAlreadyTracked`).
    pub(crate) async fn add_or_update_account(
        &mut self,
        account: &Account,
        overwrite: bool,
    ) -> Result<()> {
        let account_id = account.id();

        let existing = self
            .miden_client
            .get_account(account_id)
            .await
            .map_err(|e| {
                MultisigError::MidenClient(format!("failed to check account: {}", error_chain(&e)))
            })?;

        if existing.is_some() {
            self.miden_client
                .add_account(account, true)
                .await
                .map_err(|e| {
                    MultisigError::MidenClient(format!(
                        "failed to update account: {}",
                        error_chain(&e)
                    ))
                })?;
        } else {
            self.miden_client
                .add_account(account, overwrite)
                .await
                .map_err(|e| {
                    MultisigError::MidenClient(format!(
                        "failed to add account: {}",
                        error_chain(&e)
                    ))
                })?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use guardian_shared::FromJson;
    use guardian_shared::ToJson;
    use miden_protocol::account::AccountCodePatch;
    use miden_protocol::account::AccountId;
    use miden_protocol::account::AccountStoragePatch;
    use miden_protocol::account::delta::{AccountDelta, AccountVaultDelta};
    use miden_protocol::transaction::{
        InputNotes, RawOutputNotes, TransactionSummary, TransactionSummaryUserParams,
    };
    use miden_protocol::{Felt, Word};

    use super::MultisigClient;

    fn tx_summary_json() -> serde_json::Value {
        let account_id = AccountId::from_hex("0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b").unwrap();
        let delta = AccountDelta::new(
            account_id,
            AccountStoragePatch::default(),
            AccountVaultDelta::default(),
            AccountCodePatch::default(),
            Felt::ZERO,
        )
        .unwrap();
        TransactionSummary::new(
            delta,
            InputNotes::new(Vec::new()).unwrap(),
            RawOutputNotes::new(Vec::new()).unwrap(),
            miden_protocol::block::BlockNumber::from(0),
            Word::default(),
            0,
            TransactionSummaryUserParams::new([Felt::ZERO; 6]),
        )
        .to_json()
    }

    #[test]
    fn proposal_id_from_delta_payload_returns_tx_summary_commitment() {
        let tx_summary = TransactionSummary::from_json(&tx_summary_json()).unwrap();
        let expected_id = crate::transaction::word_to_hex(&tx_summary.to_commitment());
        let delta_payload = serde_json::json!({
            "tx_summary": tx_summary_json(),
            "metadata": {
                "proposal_type": "change_threshold",
                "target_threshold": 1,
                "signer_commitments": []
            }
        })
        .to_string();

        let proposal_id = MultisigClient::proposal_id_from_delta_payload(&delta_payload).unwrap();

        assert_eq!(proposal_id, expected_id);
    }

    #[test]
    fn proposal_id_from_delta_payload_rejects_missing_tx_summary() {
        let result = MultisigClient::proposal_id_from_delta_payload("{\"metadata\":{}}");

        assert!(result.is_err());
    }

    #[test]
    fn ensure_proposal_account_id_accepts_matching_account() {
        let account_id = AccountId::from_hex("0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b").unwrap();

        let result = MultisigClient::ensure_proposal_account_id(
            "0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b",
            &account_id,
        );

        assert!(result.is_ok());
    }

    #[test]
    fn ensure_proposal_account_id_rejects_mismatched_account() {
        let account_id = AccountId::from_hex("0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b").unwrap();

        let error = MultisigClient::ensure_proposal_account_id(
            "0x8a8a8a8a8a8a8a010a8a8a8a8a8a8a",
            &account_id,
        )
        .unwrap_err();

        assert_eq!(
            error.to_string(),
            "invalid configuration: proposal is for account 0x8a8a8a8a8a8a8a010a8a8a8a8a8a8a instead of 0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b"
        );
    }
}