miden-multisig-client 0.15.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
//! 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::{GrpcClient, GrpcError, NodeRpcClient, 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, TransactionType};
use crate::transaction::word_to_hex;

/// 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 = GrpcClient::new(&self.miden_endpoint, 10_000);
        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::MidenClient(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 = GrpcClient::new(&self.miden_endpoint, 10_000);
        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::MidenClient(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 proposals metadata reconstructs the same tx_summary commitment.
    pub(crate) async fn verify_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
            )));
        }

        // 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()?;
        let signer_commitments = proposal.metadata.signer_commitments()?;

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

        let reconstructed = crate::transaction::execute_for_summary(
            &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(())
    }

    #[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.
    ///
    /// 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).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::MidenClient(format!(
                        "failed to get account before execution: {}",
                        e
                    ))
                })?
                .ok_or_else(|| {
                    MultisigError::MissingConfig("account not found before execution".to_string())
                })?;

            let tx_result = self
                .miden_client
                .execute_transaction(account_id, tx_request)
                .await
                .map_err(|e| {
                    MultisigError::TransactionExecution(format!(
                        "transaction execution failed: {:?}",
                        e
                    ))
                })?;

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

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

            let account_delta = tx_result.account_delta();
            let rebuilt: Account = if account_delta.is_full_state() {
                Account::try_from(account_delta).map_err(|e| {
                    MultisigError::MidenClient(format!(
                        "failed to build account from full state delta: {}",
                        e
                    ))
                })?
            } else {
                let mut acc = base_account;
                acc.apply_delta(account_delta).map_err(|e| {
                    MultisigError::MidenClient(format!(
                        "failed to apply transaction delta to account: {}",
                        e
                    ))
                })?;
                acc
            };

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

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

            rebuilt
        } else {
            self.miden_client
                .submit_new_transaction(account_id, tx_request)
                .await
                .map_err(|e| {
                    MultisigError::TransactionExecution(format!(
                        "transaction execution failed: {:?}",
                        e
                    ))
                })?;

            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(())
    }

    /// 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).await?;
        Ok(())
    }

    /// Adds an account to miden-client if it doesn't exist, or updates it if it does.
    pub(crate) async fn add_or_update_account(
        &mut self,
        account: &Account,
        imported: 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, imported)
                .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::AccountId;
    use miden_protocol::account::delta::{AccountDelta, AccountStorageDelta, AccountVaultDelta};
    use miden_protocol::transaction::{InputNotes, RawOutputNotes, TransactionSummary};
    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,
            AccountStorageDelta::default(),
            AccountVaultDelta::default(),
            Felt::ZERO,
        )
        .unwrap();
        TransactionSummary::new(
            delta,
            InputNotes::new(Vec::new()).unwrap(),
            RawOutputNotes::new(Vec::new()).unwrap(),
            Word::default(),
        )
        .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"
        );
    }
}