miden-multisig-client 0.17.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
//! Wallet-facing orchestration of the note-recovery primitives.
//!
//! After key-based recovery the local Miden store starts empty (or, in a
//! shared store, its global cursors may already be past this account's
//! notes). Each recovery primitive rescans one source normal forward sync
//! would skip: the private-note transport backlog, the notes embedded in
//! pending consume-notes proposals, and the chain's historical public notes
//! for the account's tag. [`MultisigClient::recover_notes`] runs them as a
//! single flow and finishes with a normal sync so recovered notes are
//! verified and ready to consume.

use std::time::Duration;

use super::MultisigClient;
use super::proposal_note_import::{NoteImportOutcome, NoteImportSource, NoteImportStatus};
use super::public_note_backfill::{PublicBackfillOptions, PublicBackfillReport};
use super::recovery::TransportRecoveryReport;
use crate::error::{MultisigError, Result, error_chain};

/// Deadline for [`MultisigClient::preserve_pre_switch_proposal_notes`]: no
/// client in the stack applies request deadlines, and a half-dead old
/// GUARDIAN must not stall the switch. Mirror of the TS SDK's
/// `PRE_SWITCH_IMPORT_TIMEOUT_MS`.
pub const PRE_SWITCH_IMPORT_TIMEOUT: Duration = Duration::from_secs(30);

/// Options for [`MultisigClient::recover_notes`]. The default runs every
/// strategy over the full chain history and syncs afterwards; pass `None` to
/// the method for exactly that.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NoteRecoveryOptions {
    /// Rescan the private-note transport backlog
    /// ([`MultisigClient::drain_private_note_backlog`]). Default `true`.
    pub transport_drain: bool,
    /// Import the notes embedded in pending consume-notes proposals
    /// ([`MultisigClient::import_notes_from_proposals`]). Default `true`.
    pub proposal_import: bool,
    /// Scan chain history for public notes addressed at the account's tag
    /// ([`MultisigClient::backfill_public_notes_by_tag`]). Default `true`.
    pub public_backfill: bool,
    /// Block range for the public backfill; the default scans genesis
    /// through the current chain tip.
    pub backfill: PublicBackfillOptions,
    /// Run a normal sync after the strategies so imported notes are verified
    /// and show up as consumable. Default `true`.
    pub sync_after: bool,
}

impl Default for NoteRecoveryOptions {
    fn default() -> Self {
        Self {
            transport_drain: true,
            proposal_import: true,
            public_backfill: true,
            backfill: PublicBackfillOptions::default(),
            sync_after: true,
        }
    }
}

impl NoteRecoveryOptions {
    /// The guardian-switch slice of the flow: only the proposal-embedded
    /// note import runs. Internal — the public entry point is
    /// [`MultisigClient::preserve_pre_switch_proposal_notes`], which adds
    /// the switch-specific safety contract around this slice. Every field
    /// is listed on purpose (no `..Default::default()`): adding a strategy
    /// must force a compile-time decision about the switch path.
    pub(crate) fn for_guardian_switch() -> Self {
        Self {
            transport_drain: false,
            proposal_import: true,
            public_backfill: false,
            backfill: PublicBackfillOptions::default(),
            sync_after: false,
        }
    }
}

/// One step of the note-recovery flow, used to attribute
/// [`RecoveryStepProblem`]s.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryStep {
    /// The private-note transport backlog drain.
    TransportDrain,
    /// The proposal-embedded note import.
    ProposalImport,
    /// The historical public-note backfill.
    PublicBackfill,
    /// The final verifying sync.
    Sync,
}

impl RecoveryStep {
    /// Stable string form, shared with the TS SDK's `step` union.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::TransportDrain => "transport-drain",
            Self::ProposalImport => "proposal-import",
            Self::PublicBackfill => "public-backfill",
            Self::Sync => "sync",
        }
    }
}

impl std::fmt::Display for RecoveryStep {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A step of the recovery flow that could not run (or, for the final sync,
/// did not finish). The flow always continues with the remaining steps; a
/// problem here means the corresponding report field is `None` (or `synced`
/// is `false`) and rerunning the flow may recover more.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecoveryStepProblem {
    /// The step that failed.
    pub step: RecoveryStep,
    /// Human-readable cause.
    pub reason: String,
    /// Whether rerunning the flow can plausibly make this step succeed.
    /// Failures reaching this level are I/O failures against GUARDIAN, the
    /// node, or the local store; all but store failures are marked
    /// retryable. The flow is idempotent, so retrying is always safe.
    pub retryable: bool,
}

/// Result of [`MultisigClient::recover_notes`].
///
/// Each strategy's field holds its primitive's own report and is `Some`
/// exactly when the strategy was enabled and ran; an enabled strategy that
/// could not run at all is a [`RecoveryStepProblem`] instead. Step problems
/// never abort the flow.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoteRecoveryReport {
    /// Report of the transport backlog drain, when that strategy ran.
    pub transport: Option<TransportRecoveryReport>,
    /// Per-note outcomes of the proposal-embedded import, when that strategy
    /// ran.
    pub proposal_import: Option<Vec<NoteImportOutcome>>,
    /// Report of the historical public-note backfill, when that strategy
    /// ran.
    pub backfill: Option<PublicBackfillReport>,
    /// Steps that could not run or finish. Empty on a fully clean flow.
    pub problems: Vec<RecoveryStepProblem>,
    /// Whether the final verifying sync completed.
    pub synced: bool,
    /// Total note records newly added to the local store by this flow: the
    /// drain's imports plus every `imported` outcome from the proposal
    /// import and the backfill.
    pub imported: usize,
    /// Whether rerunning the flow can plausibly recover more: any step
    /// problem, per-note outcome, or strategy report marked retryable.
    pub retryable: bool,
}

impl MultisigClient {
    /// Runs the note-recovery strategies as a single wallet-facing flow,
    /// typically right after key-based recovery loaded the account (via
    /// [`MultisigClient::pull_account`]).
    ///
    /// With `None` every strategy runs — the private-note transport backlog
    /// drain, the proposal-embedded note import, and the historical
    /// public-note backfill over the whole chain — followed by a normal sync
    /// that verifies whatever was imported. Pass [`NoteRecoveryOptions`] to
    /// choose strategies, bound the backfill's block range, or skip the
    /// final sync.
    ///
    /// No strategy failure aborts the flow: each primitive already reports
    /// per-note and per-source problems instead of throwing, and a strategy
    /// that cannot run at all (GUARDIAN unreachable while listing proposals,
    /// chain tip unresolvable, a broken local store) becomes a
    /// [`RecoveryStepProblem`] while the remaining strategies still run. The
    /// flow is idempotent — rerunning re-imports nothing that already
    /// arrived — so a report with `retryable: true` can simply be retried.
    ///
    /// # Errors
    ///
    /// Only for preconditions: no account is loaded, or the requested
    /// backfill range is inverted.
    ///
    /// # Example
    ///
    /// ```ignore
    /// client.pull_account(account_id).await?;
    /// let report = client.recover_notes(None).await?;
    /// println!("recovered {} notes", report.imported);
    /// ```
    pub async fn recover_notes(
        &mut self,
        options: Option<NoteRecoveryOptions>,
    ) -> Result<NoteRecoveryReport> {
        let options = options.unwrap_or_default();
        let account_id = self.require_account()?.id();
        if let (Some(from), Some(to)) = (options.backfill.from_block, options.backfill.to_block)
            && from > to
        {
            return Err(MultisigError::InvalidConfig(format!(
                "backfill range is inverted: from_block {from} > to_block {to}"
            )));
        }

        let mut report = NoteRecoveryReport {
            transport: None,
            proposal_import: None,
            backfill: None,
            problems: Vec::new(),
            synced: false,
            imported: 0,
            retryable: false,
        };

        if options.transport_drain {
            match self.drain_private_note_backlog().await {
                Ok(drain) => report.transport = Some(drain),
                // The drain's contract: an `Err` means the local store
                // itself failed, which a rerun is unlikely to fix.
                Err(e) => report.problems.push(RecoveryStepProblem {
                    step: RecoveryStep::TransportDrain,
                    reason: error_chain(&e),
                    retryable: false,
                }),
            }
        }

        if options.proposal_import {
            // The lenient listing isolates per-proposal parse/binding
            // failures as skip reasons, so one corrupt proposal cannot block
            // recovering notes from the healthy ones; those skips surface as
            // `Invalid` outcomes alongside the per-note ones.
            match self.list_proposals_isolating_failures().await {
                Ok((proposals, skipped)) => {
                    let mut outcomes: Vec<NoteImportOutcome> = skipped
                        .into_iter()
                        .map(|(identifier, reason)| NoteImportOutcome {
                            identifier,
                            source: NoteImportSource::Proposal,
                            status: NoteImportStatus::Invalid,
                            retryable: false,
                            reason: Some(reason),
                        })
                        .collect();
                    outcomes.extend(self.import_notes_from_proposals(&proposals).await);
                    report.proposal_import = Some(outcomes);
                }
                Err(e) => report.problems.push(RecoveryStepProblem {
                    step: RecoveryStep::ProposalImport,
                    reason: format!("failed to list pending proposals: {}", error_chain(&e)),
                    retryable: true,
                }),
            }
        }

        if options.public_backfill {
            // Importing a proof into a store that has never seen the chain
            // fails, and neither key-based recovery nor `pull_account` syncs
            // on its own — so sync the chain state first. Incremental, so
            // cheap when the store is already synced.
            let synced_for_backfill = match self.miden_client.sync_chain().await {
                Ok(_) => true,
                Err(e) => {
                    report.problems.push(RecoveryStepProblem {
                        step: RecoveryStep::PublicBackfill,
                        reason: format!(
                            "failed to sync the chain state the backfill imports against: {}",
                            error_chain(&e)
                        ),
                        retryable: true,
                    });
                    false
                }
            };
            if synced_for_backfill {
                match self
                    .backfill_public_notes_by_tag(account_id, Some(options.backfill))
                    .await
                {
                    Ok(backfill) => report.backfill = Some(backfill),
                    // With the fully-explicit range validated above, an `Err`
                    // here is normally the chain-tip lookup (a node RPC
                    // failure, worth retrying); an invalid-range error
                    // against the resolved tip is a caller error and is not.
                    Err(e) => {
                        let retryable = !matches!(e, MultisigError::InvalidConfig(_));
                        report.problems.push(RecoveryStepProblem {
                            step: RecoveryStep::PublicBackfill,
                            reason: error_chain(&e),
                            retryable,
                        });
                    }
                }
            }
        }

        if options.sync_after {
            match self.sync().await {
                Ok(()) => report.synced = true,
                Err(e) => report.problems.push(RecoveryStepProblem {
                    step: RecoveryStep::Sync,
                    reason: format!("recovery imports succeeded but the verifying sync failed; rerun a sync: {}", error_chain(&e)),
                    retryable: true,
                }),
            }
        }

        let imported_outcomes = |outcomes: &[NoteImportOutcome]| {
            outcomes
                .iter()
                .filter(|o| o.status == NoteImportStatus::Imported)
                .count()
        };
        report.imported = report.transport.as_ref().map_or(0, |t| t.imported)
            + report
                .proposal_import
                .as_ref()
                .map_or(0, |o| imported_outcomes(o))
            + report
                .backfill
                .as_ref()
                .map_or(0, |b| imported_outcomes(&b.outcomes));
        report.retryable = report.problems.iter().any(|p| p.retryable)
            || report.transport.as_ref().is_some_and(|t| t.retryable)
            || report
                .proposal_import
                .as_ref()
                .is_some_and(|o| o.iter().any(|o| o.retryable))
            || report.backfill.as_ref().is_some_and(|b| b.retryable);

        Ok(report)
    }

    /// Imports the notes embedded in the old GUARDIAN's pending
    /// consume-notes proposals while they are still reachable: pending
    /// proposals do not survive a guardian switch, making them the one
    /// recovery source [`MultisigClient::recover_notes`] loses once the
    /// client repoints (issue #417).
    ///
    /// Run automatically by [`MultisigClient::execute_proposal`] on the
    /// switch path, before the switch transaction executes; call it
    /// yourself before repointing a client by hand via
    /// [`MultisigClient::set_guardian_endpoint`]. Best-effort by contract:
    /// problems are logged and folded into the returned report, never
    /// raised, and the flow runs under [`PRE_SWITCH_IMPORT_TIMEOUT`] (on
    /// expiry it is cancelled and the switch proceeds), so a hung old
    /// GUARDIAN cannot block the switch. Returns `None` when the flow could
    /// not run or timed out. Full rationale and semantics: "Preserving
    /// Notes Across a Guardian Switch" in docs/MULTISIG_SDK.md.
    pub async fn preserve_pre_switch_proposal_notes(&mut self) -> Option<NoteRecoveryReport> {
        let flow = self.recover_notes(Some(NoteRecoveryOptions::for_guardian_switch()));
        match tokio::time::timeout(PRE_SWITCH_IMPORT_TIMEOUT, flow).await {
            Err(_elapsed) => {
                tracing::warn!(
                    timeout_secs = PRE_SWITCH_IMPORT_TIMEOUT.as_secs(),
                    "pre-switch proposal-note import timed out and was cancelled; notes \
                     embedded in pending proposals may be unrecoverable after the \
                     guardian switch"
                );
                None
            }
            Ok(Ok(report)) => {
                for problem in &report.problems {
                    tracing::warn!(
                        step = problem.step.as_str(),
                        reason = %problem.reason,
                        "pre-switch proposal-note import did not finish; notes embedded \
                         in pending proposals may be unrecoverable after the guardian \
                         switch"
                    );
                }
                // Per-note failures never reach `problems` — and this is the
                // last moment the notes are reachable, so "retryable" cannot
                // help: the source is gone once the client repoints. They
                // must be observable now.
                for outcome in report.proposal_import.iter().flatten().filter(|o| {
                    matches!(
                        o.status,
                        NoteImportStatus::Invalid | NoteImportStatus::Failed
                    )
                }) {
                    tracing::warn!(
                        identifier = %outcome.identifier,
                        status = outcome.status.as_str(),
                        reason = outcome.reason.as_deref().unwrap_or("unknown"),
                        "pre-switch import could not preserve an embedded note; it may \
                         be unrecoverable after the guardian switch"
                    );
                }
                Some(report)
            }
            Ok(Err(e)) => {
                tracing::warn!(
                    error = %error_chain(&e),
                    "pre-switch proposal-note import could not run; notes embedded in \
                     pending proposals may be unrecoverable after the guardian switch"
                );
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use miden_client::testing::mock::MockRpcApi;
    use miden_protocol::block::BlockNumber;
    use miden_protocol::note::NoteType;

    use super::super::recovery::TransportRecoveryStatus;
    use super::*;
    use crate::account::MultisigAccount;
    use crate::client::public_note_backfill::PublicBackfillOptions;
    use crate::client::test_support::{
        add_to_transport, mock_transport, offline_client, offline_client_with_node, p2id_note_for,
        test_wallet,
    };

    /// Loads `client` the way `pull_account` leaves it: the account is in
    /// the store (its note tag tracked) and cached as the current account.
    async fn load_account(client: &mut MultisigClient, seed: u8) {
        let account = test_wallet(seed);
        client.add_or_update_account(&account, true).await.unwrap();
        client.account = Some(MultisigAccount::new(account));
    }

    #[tokio::test]
    async fn recover_notes_requires_a_loaded_account() {
        let dir = tempfile::tempdir().unwrap();
        let mut client = offline_client(dir.path(), None).await;

        assert!(client.recover_notes(None).await.is_err());
    }

    #[tokio::test]
    async fn recover_notes_rejects_an_inverted_backfill_range() {
        let dir = tempfile::tempdir().unwrap();
        let mut client = offline_client(dir.path(), None).await;
        load_account(&mut client, 31).await;

        let err = client
            .recover_notes(Some(NoteRecoveryOptions {
                backfill: PublicBackfillOptions {
                    from_block: Some(BlockNumber::from(5u32)),
                    to_block: Some(BlockNumber::from(1u32)),
                },
                ..Default::default()
            }))
            .await
            .expect_err("inverted range must error");
        assert!(err.to_string().contains("inverted"));
    }

    /// The default flow keeps going when individual steps cannot run:
    /// GUARDIAN and the direct node channel are unreachable here, so the
    /// proposal listing, the backfill's tip lookup, and the final sync all
    /// fail — yet the transport drain still recovers its backlog, and every
    /// failed step lands in `problems` as retryable.
    #[tokio::test]
    async fn recover_notes_continues_past_failing_steps() {
        let dir = tempfile::tempdir().unwrap();
        let (node, api) = mock_transport();
        let mut client = offline_client(dir.path(), Some(api)).await;
        load_account(&mut client, 32).await;
        let account = client.account.as_ref().unwrap().inner().clone();
        add_to_transport(&node, p2id_note_for(&account, 1, NoteType::Private));

        let report = client.recover_notes(None).await.unwrap();

        let transport = report.transport.expect("drain ran");
        assert_eq!(transport.status, TransportRecoveryStatus::Completed);
        assert_eq!(transport.imported, 1);
        assert_eq!(report.proposal_import, None);
        assert_eq!(report.backfill, None);
        assert!(!report.synced);
        assert_eq!(report.imported, 1);
        assert!(report.retryable);

        let steps: Vec<RecoveryStep> = report.problems.iter().map(|p| p.step).collect();
        assert_eq!(
            steps,
            vec![
                RecoveryStep::ProposalImport,
                RecoveryStep::PublicBackfill,
                RecoveryStep::Sync,
            ]
        );
        assert!(report.problems.iter().all(|p| p.retryable));
    }

    #[tokio::test]
    async fn recover_notes_runs_only_the_selected_strategies() {
        let dir = tempfile::tempdir().unwrap();
        let (_node, api) = mock_transport();
        let mut client = offline_client(dir.path(), Some(api)).await;
        load_account(&mut client, 33).await;

        let report = client
            .recover_notes(Some(NoteRecoveryOptions {
                transport_drain: true,
                proposal_import: false,
                public_backfill: false,
                backfill: PublicBackfillOptions::default(),
                sync_after: false,
            }))
            .await
            .unwrap();

        let transport = report.transport.expect("drain ran");
        assert_eq!(transport.status, TransportRecoveryStatus::Completed);
        assert_eq!(report.proposal_import, None);
        assert_eq!(report.backfill, None);
        assert!(report.problems.is_empty());
        assert!(!report.synced);
        assert_eq!(report.imported, 0);
        assert!(!report.retryable);
    }

    /// The switch-guardian slice (issue #417) runs only the proposal-embedded
    /// note import: even with a transport backlog waiting, the drain, the
    /// backfill, and the verifying sync are all skipped — a switch executes
    /// against an intact local store, so they have nothing to recover — and
    /// an unreachable pre-switch GUARDIAN folds into the report instead of
    /// erroring, so it can never block the switch.
    #[tokio::test]
    async fn preserve_pre_switch_proposal_notes_runs_only_the_import_and_never_errors() {
        let dir = tempfile::tempdir().unwrap();
        let (node, api) = mock_transport();
        let mut client = offline_client(dir.path(), Some(api)).await;
        load_account(&mut client, 35).await;
        let account = client.account.as_ref().unwrap().inner().clone();
        add_to_transport(&node, p2id_note_for(&account, 1, NoteType::Private));

        let report = client
            .preserve_pre_switch_proposal_notes()
            .await
            .expect("best-effort flow reports instead of erroring");

        assert_eq!(
            report.transport, None,
            "transport drain must not run on the switch path"
        );
        assert_eq!(
            report.backfill, None,
            "public backfill must not run on the switch path"
        );
        assert!(!report.synced, "the switch flow owns its own syncs");
        assert_eq!(report.imported, 0);
        let steps: Vec<RecoveryStep> = report.problems.iter().map(|p| p.step).collect();
        assert_eq!(steps, vec![RecoveryStep::ProposalImport]);
        assert!(report.retryable);
    }

    /// With a reachable mock node the backfill strategy produces a real
    /// report, and a transport-less client reports the drain unavailable
    /// instead of failing the flow.
    #[tokio::test]
    async fn recover_notes_reports_backfill_and_unavailable_transport() {
        let dir = tempfile::tempdir().unwrap();
        let mut client =
            offline_client_with_node(dir.path(), Arc::new(MockRpcApi::default())).await;
        load_account(&mut client, 34).await;

        let report = client
            .recover_notes(Some(NoteRecoveryOptions {
                proposal_import: false,
                sync_after: false,
                ..Default::default()
            }))
            .await
            .unwrap();

        let transport = report.transport.expect("drain ran");
        assert_eq!(transport.status, TransportRecoveryStatus::Unavailable);
        let backfill = report.backfill.expect("backfill ran");
        assert_eq!(backfill.scanned_from, 0);
        assert!(backfill.uncovered.is_empty());
        assert!(report.problems.is_empty());
        assert_eq!(report.imported, 0);
        assert!(!report.retryable);
    }
}