Skip to main content

bark/
recovery.rs

1//! Wallet recovery from seed.
2//!
3//! As a wallet creates or receives VTXOs it posts their ids to a mailbox keyed
4//! by a dedicated, seed-derived recovery key (see
5//! [`Wallet::post_recovery_vtxo_ids`]). Recovering the seed re-derives that key
6//! and reads back every posted id to rebuild the spendable VTXO set.
7
8use std::collections::{BTreeMap, HashMap, HashSet};
9
10use anyhow::Context;
11use bitcoin::Amount;
12use bitcoin::secp256k1::{Keypair, PublicKey};
13use log::{debug, info, warn};
14
15use ark::{ProtocolEncoding, Vtxo, VtxoId};
16use ark::attestations::VtxoStatusAttestation;
17use ark::mailbox::MailboxAuthorization;
18use ark::vtxo::Full;
19use bitcoin_ext::BlockHeight;
20use server_rpc::TryFromBytes;
21use server_rpc::protos::{self, VtxoSpendState};
22use server_rpc::protos::mailbox_server::mailbox_message::Message;
23
24use crate::Wallet;
25use crate::vtxo::VtxoState;
26
27/// Consecutive unused key indices we tolerate before concluding a VTXO isn't ours.
28const STOP_GAP: u32 = 50;
29
30#[derive(Debug, Default, Clone)]
31pub struct RecoveryReportEntry(HashMap<VtxoId, Option<Amount>>);
32
33impl RecoveryReportEntry {
34	pub fn is_empty(&self) -> bool {
35		self.0.is_empty()
36	}
37
38	pub fn len(&self) -> usize {
39		self.0.len()
40	}
41
42	pub fn ids(&self) -> impl Iterator<Item = VtxoId> {
43		self.0.keys().cloned()
44	}
45
46	pub fn total_amount(&self) -> Amount {
47		self.0.values().filter_map(|a| *a).sum()
48	}
49
50	fn insert(&mut self, vtxo_id: VtxoId, amount: Option<Amount>) {
51		if !self.0.contains_key(&vtxo_id) {
52			self.0.insert(vtxo_id, amount);
53		}
54	}
55
56	fn remove(&mut self, vtxo_id: VtxoId) {
57		self.0.remove(&vtxo_id);
58	}
59}
60
61/// Summary of a recovery scan over the seed-derived recovery mailbox.
62///
63/// `skipped` vs `failed` is the load-bearing distinction: a `skipped` VTXO was
64/// *decided* not to be spendable (spent, exited on-chain, or reported
65/// non-spendable), whereas a `failed` VTXO could not be decided due to an error.
66/// A non-empty `failed` or `foreign` set means funds may be missing, so it must
67/// not be taken for a complete recovery. Ids are kept (not counted) so a caller
68/// can log or retry the exact VTXOs.
69#[derive(Debug, Default, Clone)]
70pub struct RecoveryReport {
71	/// Spendable VTXOs that were successfully re-imported.
72	recovered: RecoveryReportEntry,
73	/// VTXOs deliberately left out: spent into a newer recovered VTXO, exited
74	/// on-chain, or reported non-spendable by the server.
75	skipped: RecoveryReportEntry,
76	/// VTXOs we could not decide on due to an error (fetch, validation, or no
77	/// usable spend state). Not known to be spent, so funds may be missing.
78	failed: RecoveryReportEntry,
79	/// VTXOs found in the mailbox whose key we could not derive within the gap
80	/// limit. Only the seed owner can post here, so these are most likely our own
81	/// VTXOs whose key sits beyond [`STOP_GAP`]; their presence means funds may be
82	/// missing and the scan can't be reported complete.
83	foreign: RecoveryReportEntry,
84	/// VTXOs that have been fully exited on-chain.
85	exited: RecoveryReportEntry,
86}
87
88impl RecoveryReport {
89	/// Whether the scan accounted for every VTXO in the mailbox.
90	///
91	/// A `failed` VTXO or `foreign` id both mean funds may be missing, so neither
92	/// may be present. `failed` is retryable; a `foreign` id instead needs a wider
93	/// gap limit to be matched.
94	pub fn is_complete(&self) -> bool {
95		self.failed.is_empty() && self.foreign.is_empty()
96	}
97
98	pub fn recovered(&self) -> &RecoveryReportEntry {
99		&self.recovered
100	}
101
102	pub fn push_recovered(&mut self, vtxo: &Vtxo<Full>) {
103		self.failed.remove(vtxo.id());
104		self.recovered.insert(vtxo.id(), Some(vtxo.amount()));
105	}
106
107	pub fn skipped(&self) -> &RecoveryReportEntry {
108		&self.skipped
109	}
110
111	pub fn push_skipped(&mut self, vtxo: &Vtxo<Full>) {
112		self.failed.remove(vtxo.id());
113		self.skipped.insert(vtxo.id(), Some(vtxo.amount()));
114	}
115
116	pub fn foreign(&self) -> &RecoveryReportEntry {
117		&self.foreign
118	}
119
120	pub fn push_foreign(&mut self, vtxo: &Vtxo<Full>) {
121		self.failed.remove(vtxo.id());
122		self.foreign.insert(vtxo.id(), Some(vtxo.amount()));
123	}
124
125	pub fn failed(&self) -> &RecoveryReportEntry {
126		&self.failed
127	}
128
129	pub fn push_failed(&mut self, id: VtxoId, amount: Option<Amount>) {
130		self.failed.insert(id, amount);
131	}
132
133	pub fn exited(&self) -> &RecoveryReportEntry {
134		&self.exited
135	}
136
137	pub fn push_exited(&mut self, vtxo: &Vtxo<Full>) {
138		self.failed.remove(vtxo.id());
139		self.exited.insert(vtxo.id(), Some(vtxo.amount()));
140	}
141}
142
143/// A recovered VTXO paired with the key that proves we own it.
144///
145/// The pairing invariant — `keypair` is `vtxo`'s owner key — is enforced by
146/// [`OwnedVtxo::new`], so the rest of recovery can rely on it.
147pub(crate) struct OwnedVtxo {
148	vtxo: Vtxo<Full>,
149	keypair: Keypair,
150}
151
152impl OwnedVtxo {
153	/// Pair a VTXO with its owner keypair. The sole constructor, so the
154	/// `keypair`-owns-`vtxo` invariant holds everywhere [`OwnedVtxo`] is used.
155	fn new(vtxo: Vtxo<Full>, keypair: Keypair) -> Self {
156		debug_assert_eq!(
157			vtxo.user_pubkey(), keypair.public_key(),
158			"OwnedVtxo keypair must match the VTXO's owner pubkey",
159		);
160		OwnedVtxo { vtxo, keypair }
161	}
162}
163
164/// Ordering key for recovered VTXOs: ascending by expiry height, then arkoor
165/// chain length ([`Vtxo::exit_depth`]).
166///
167/// Expiry is inherited within an arkoor chain, so `exit_depth` breaks the tie,
168/// ordering ancestors before descendants. [`Wallet::recover_from_mailbox`]
169/// walks the sorted set in reverse (descendants first) so a VTXO spent into a
170/// newer one is seen as already-spent and skipped.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
172struct ChainOrder {
173	expiry: BlockHeight,
174	depth: u16,
175}
176
177impl ChainOrder {
178	fn of(vtxo: &Vtxo<Full>) -> Self {
179		ChainOrder { expiry: vtxo.expiry_height(), depth: vtxo.exit_depth() }
180	}
181}
182
183impl Wallet {
184	fn mailbox_request(&self, checkpoint: u64) -> protos::mailbox_server::MailboxRequest {
185		let expiry = chrono::Local::now() + std::time::Duration::from_secs(60);
186		let auth = MailboxAuthorization::new(&self.recovery_mailbox_keypair(), expiry);
187		let mailbox_id = auth.mailbox();
188
189		protos::mailbox_server::MailboxRequest {
190			mailbox_id: mailbox_id.serialize(),
191			authorization: Some(auth.serialize()),
192			checkpoint,
193		}
194	}
195
196	async fn fetch_valid_owned_vtxos(&self, report: &mut RecoveryReport, ids: &[VtxoId]) ->
197		anyhow::Result<Vec<OwnedVtxo>>
198	{
199		// Drain the whole mailbox into a candidate set. The mailbox isn't
200		// de-duplicated, so track the ids we've fetched and skip any repeats.
201		let mut candidates = HashMap::new();
202
203		for id in ids {
204			match self.fetch_vtxo(*id).await {
205				Ok(vtxo) => {
206					candidates.insert(*id, vtxo);
207				},
208				Err(e) => {
209					warn!("Could not fetch recovery vtxo {id}: {:#}", e);
210					report.push_failed(*id, None);
211				}
212			}
213		}
214
215		// Resolve ownership over the complete candidate set in one pass.
216		let candidates = candidates.into_values().collect();
217		let owned = self.resolve_owned_vtxos(candidates, report).await?;
218
219		// Order by (expiry, arkoor chain length) so the caller can walk newest-first.
220		let mut vtxos = BTreeMap::<ChainOrder, Vec<OwnedVtxo>>::new();
221		for owned in owned {
222			vtxos.entry(ChainOrder::of(&owned.vtxo)).or_default().push(owned);
223		}
224
225		Ok(vtxos.into_values().flatten().collect())
226	}
227
228
229	/// Page the recovery mailbox and collect the distinct VTXO ids it references.
230	///
231	/// Reads the whole mailbox from checkpoint 0 (independent of the regular
232	/// mailbox checkpoint), taking ids from `RecoveryVtxoIds` and `Arkoor`
233	/// messages and de-duplicating them into a `HashSet`. Fetching the VTXOs,
234	/// validating them, resolving ownership, and ordering are left to the caller.
235	async fn read_mailbox_recovery_vtxo_ids(&self) -> anyhow::Result<(HashSet<VtxoId>, u64)> {
236		let (mut srv, _) = self.require_server().await?;
237
238		// Drain the whole mailbox into a candidate set. The mailbox isn't
239		// de-duplicated, so track the ids we've fetched and skip any repeats.
240		let mut ids = HashSet::new();
241
242		let mut iteration = 0;
243		let mut checkpoint = 0u64;
244		loop {
245			iteration += 1;
246
247			let req = self.mailbox_request(checkpoint);
248			let resp = srv.mailbox_client.read_mailbox(req).await
249				.context("error reading recovery mailbox")?.into_inner();
250
251			debug!("Recovery mailbox returned {} messages on iteration {iteration}", resp.messages.len());
252
253			let prev_checkpoint = checkpoint;
254			for msg in &resp.messages {
255				match &msg.message {
256					Some(Message::RecoveryVtxoIds(m)) => {
257						checkpoint = checkpoint.max(msg.checkpoint);
258						for raw in &m.vtxo_ids {
259							let Ok(id) = VtxoId::from_bytes(raw.clone()) else {
260								warn!("Ignoring undecodable recovery vtxo id: {raw:?}");
261								continue;
262							};
263							ids.insert(id);
264						}
265					},
266					Some(Message::Arkoor(m)) => {
267						checkpoint = checkpoint.max(msg.checkpoint);
268						for raw in &m.vtxos {
269							let Ok(vtxo) = Vtxo::<Full>::from_bytes(raw.clone()) else {
270								warn!("Ignoring undecodable vtxo: {raw:?}");
271								continue;
272							};
273							ids.insert(vtxo.id());
274						}
275					},
276					Some(Message::RoundParticipationCompleted(_)) |
277					Some(Message::IncomingLightningPayment(_)) |
278					Some(Message::LightningSendFinished(_)) => {},
279					None => {
280						warn!("Recovery mailbox returned a message with no content: {msg:?}");
281					},
282				}
283			}
284
285			if !resp.have_more {
286				break;
287			}
288
289			// The server wants us to keep paging, but the checkpoint didn't
290			// advance, so the next request would be identical and we'd loop
291			// forever. Stop rather than spin on the same page.
292			if checkpoint == prev_checkpoint {
293				warn!("Recovery mailbox iteration {iteration} made no progress \
294					at checkpoint {checkpoint}; stopping");
295				break;
296			}
297		}
298
299		Ok((ids, checkpoint))
300	}
301
302	/// Fetch the full [`Vtxo<Full>`] for `id` from the server.
303	///
304	/// The recovery mailbox only stores ids, so we ask the server for the full
305	/// VTXO data. The result is untrusted until validated by the caller.
306	async fn fetch_vtxo(&self, id: VtxoId) -> anyhow::Result<Vtxo<Full>> {
307		let (mut srv, _) = self.require_server().await?;
308		let resp = srv.client.get_vtxo(protos::GetVtxoRequest {
309			vtxo_id: id.to_bytes().to_vec(),
310		}).await.with_context(|| format!("error fetching vtxo {id} from server"))?.into_inner();
311
312		Vtxo::<Full>::deserialize(&resp.vtxo)
313			.with_context(|| format!("server returned an undecodable vtxo for {id}"))
314	}
315
316	/// Check if a VTXO is confirmed on-chain.
317	///
318	/// If it is, we store it as exited and return `true`.
319	/// If we could not confirm the exit status, we consider it is not exited yet and return `false`.
320	async fn check_vtxo_onchain_status(&self, report: &mut RecoveryReport, vtxo: &Vtxo<Full>) -> anyhow::Result<bool> {
321		// An off-chain VTXO's tx is only confirmed once it has been exited,
322		// so if we see it on-chain the funds live in the on-chain wallet and
323		// it must not be recovered as spendable. The server's spend status
324		// doesn't capture unilateral exits, so we check the chain ourselves.
325		match self.inner.chain.tx_confirmed(vtxo.point().txid).await {
326			Ok(Some(height)) => {
327				self.store_vtxos(&vec![vtxo.clone()], &VtxoState::Exited).await?;
328				self.exit_mgr().start_exit_for_vtxos_including_non_standard(&vec![vtxo.to_bare()]).await?;
329				report.push_exited(vtxo);
330				debug!("Skipping recovery vtxo {}: confirmed on-chain at height {height} (exited)", vtxo.id());
331				Ok(true)
332			},
333			// If we could not confirm the exit status, we consider it is not exited yet.
334			// If it actually is, next wallet sync will handle it properly
335			Ok(None) | Err(_) => Ok(false),
336		}
337	}
338
339	/// Query the server for `id`'s spend state.
340	///
341	/// `keypair` is the VTXO's owner key, used to build the attestation that
342	/// proves to the server we control the VTXO (required by the endpoint).
343	async fn check_vtxo_server_status(
344		&self,
345		report: &mut RecoveryReport,
346		vtxo: &Vtxo<Full>,
347		keypair: &Keypair,
348	) -> anyhow::Result<bool> {
349		let (mut srv, _) = self.require_server().await?;
350		let vtxo_id = vtxo.id();
351		let attestation = VtxoStatusAttestation::new(vtxo_id, keypair);
352		let resp = srv.client.get_vtxo_status(protos::GetVtxoStatusRequest {
353			vtxo_id: vtxo_id.to_bytes().to_vec(),
354			attestation: attestation.serialize(),
355		}).await.with_context(|| format!("error fetching status for vtxo {vtxo_id}"))?.into_inner();
356
357		let spend_state = protos::VtxoSpendState::try_from(resp.spend_state)
358			.map_err(|_| anyhow::anyhow!(
359				"server returned unknown spend state {} for vtxo {vtxo_id}", resp.spend_state,
360			));
361
362		// The server is the authority on whether it was spent elsewhere.
363		// Matched exhaustively (no catch-all) so a new spend state forces an
364		// explicit decision rather than being silently skipped.
365		match spend_state {
366			Ok(VtxoSpendState::Spendable) => return Ok(false),
367			// Decided not to belong in the spendable set.
368			Ok(state @ (
369				VtxoSpendState::Spent
370				| VtxoSpendState::Unclaimed
371				| VtxoSpendState::Unregistered
372				| VtxoSpendState::HtlcRecvUnclaimed
373			)) => {
374				debug!("Recovery vtxo {vtxo_id} not spendable ({state:?}), skipping");
375				report.push_skipped(vtxo);
376			},
377			// No usable answer from the server — treat as a failure to be
378			// retried, not a clean skip.
379			Ok(VtxoSpendState::Unspecified) => {
380				warn!("Server returned an unspecified spend state for recovery vtxo {vtxo_id}");
381				report.push_failed(vtxo_id, Some(vtxo.amount()));
382			},
383			Err(e) => {
384				warn!("Could not get status for recovery vtxo {vtxo_id}: {:#}", e);
385				report.push_failed(vtxo_id, Some(vtxo.amount()));
386			},
387		}
388
389		Ok(true)
390	}
391
392	/// Work out which of `vtxos` this wallet owns, pairing each with its owner
393	/// keypair and persisting the keys revealed along the way.
394	///
395	/// Order-independent: VTXOs whose key was already revealed match directly;
396	/// the rest are matched by walking the unrevealed key space once. Each match
397	/// reveals every key up to it and extends the [`STOP_GAP`] window, so a later
398	/// match can pull in an earlier VTXO a single forward pass would miss.
399	///
400	/// Idempotent: only keys at or below a match are persisted, so an unmatched
401	/// probe leaves no trace and a retry can't ratchet the key index. Owned VTXOs
402	/// that fail validation go to `report.failed`; unmatched ones to `report.foreign`.
403	async fn resolve_owned_vtxos(
404		&self,
405		vtxos: Vec<Vtxo<Full>>,
406		report: &mut RecoveryReport,
407	) -> anyhow::Result<Vec<OwnedVtxo>> {
408		// VTXOs we still need to match, indexed by owner pubkey. A pubkey can back
409		// more than one VTXO, so keep a list per key.
410		let mut pending = HashMap::<PublicKey, Vec<Vtxo<Full>>>::new();
411		let mut matched = Vec::<(Vtxo<Full>, Keypair)>::new();
412
413		for vtxo in vtxos {
414			match self.pubkey_keypair(&vtxo.user_pubkey()).await? {
415				Some((_idx, keypair)) => matched.push((vtxo, keypair)),
416				None => pending.entry(vtxo.user_pubkey()).or_default().push(vtxo),
417			}
418		}
419
420		// Walk the unrevealed key space once, extending the window on every match.
421		let start_idx = self.inner.db.get_last_vtxo_key_index().await?.map(|i| i + 1).unwrap_or(0);
422		let mut frontier = start_idx.saturating_add(STOP_GAP);
423		let mut gap = Vec::<(u32, PublicKey)>::new();
424		let mut idx = start_idx;
425		while idx <= frontier && !pending.is_empty() {
426			let keypair = self.inner.seed.derive_vtxo_keypair(idx);
427			let pubkey = keypair.public_key();
428			if let Some(owned_vtxos) = pending.remove(&pubkey) {
429				// Reveal this key and the unmatched gap keys below it, mirroring the
430				// wallet's sequential key issuance.
431				for (i, pk) in gap.drain(..) {
432					self.inner.db.store_vtxo_key(i, pk).await?;
433				}
434				self.inner.db.store_vtxo_key(idx, pubkey).await?;
435				frontier = idx.saturating_add(STOP_GAP);
436				matched.extend(owned_vtxos.into_iter().map(|v| (v, keypair)));
437			} else {
438				gap.push((idx, pubkey));
439			}
440			// Stop at the end of the key space rather than overflowing; reaching it
441			// would mean scanning the entire u32 range, far beyond any real wallet.
442			let Some(next_idx) = idx.checked_add(1) else { break };
443			idx = next_idx;
444		}
445
446		// Anything still pending never matched within the gap limit, so it's not ours.
447		for vtxo in pending.into_values().flatten() {
448			report.push_foreign(&vtxo);
449		}
450
451		// Validate the matched VTXOs. A validation error (anchor not yet visible,
452		// or invalid) is a non-decision, so it's a failure, not a clean skip.
453		let mut owned = Vec::with_capacity(matched.len());
454		for (vtxo, keypair) in matched {
455			if let Err(e) = self.validate_vtxo(&vtxo).await {
456				warn!("Could not validate recovery vtxo {}: {:#}", vtxo.id(), e);
457				report.push_failed(vtxo.id(), Some(vtxo.amount()));
458			} else {
459				owned.push(OwnedVtxo::new(vtxo, keypair));
460			}
461		}
462
463		Ok(owned)
464	}
465
466	async fn inner_recover_vtxos(
467		&self,
468		report: &mut RecoveryReport,
469		ids: impl IntoIterator<Item = VtxoId>,
470	) -> anyhow::Result<()> {
471		let ids = ids.into_iter().collect::<Vec<_>>();
472		let owned = self.fetch_valid_owned_vtxos(report, &ids).await?;
473
474		// Ancestor ids of the (newer) VTXOs we've already processed, so we can
475		// skip any older recovered VTXO that was spent into a newer one.
476		let mut spent = HashSet::<VtxoId>::new();
477
478		for o in owned {
479			let id = o.vtxo.id();
480
481			// A descendant we already processed marks this one as spent.
482			if spent.contains(&id) {
483				debug!("Skipping recovery vtxo {id}: spent into a newer recovered vtxo");
484				report.push_skipped(&o.vtxo);
485				continue;
486			}
487
488			// Add all the ancestor VTXO ids to the spent set
489			spent.extend(o.vtxo.ancestor_ids());
490
491			if self.check_vtxo_onchain_status(report, &o.vtxo).await? {
492				continue;
493			}
494
495			// The server is the authority on whether it was spent elsewhere.
496			// Matched exhaustively (no catch-all) so a new spend state forces an
497			// explicit decision rather than being silently skipped.
498			if self.check_vtxo_server_status(report, &o.vtxo, &o.keypair).await? {
499				continue;
500			}
501
502			// NB we don't use store_spendable_vtxos to avoid posting the vtxo again
503			match self.store_vtxos([&o.vtxo], &VtxoState::Spendable).await {
504				Ok(()) => {
505					report.push_recovered(&o.vtxo);
506					debug!("Recovered spendable vtxo {id} ({})", o.vtxo.amount());
507				},
508				Err(e) => {
509					warn!("Failed to store recovered vtxo {id}: {:#}", e);
510					report.push_failed(id, Some(o.vtxo.amount()));
511				},
512			}
513		}
514
515		Ok(())
516	}
517
518	pub async fn recover_vtxos(&self, ids: impl IntoIterator<Item = VtxoId>)
519		-> anyhow::Result<RecoveryReport>
520	{
521		let mut report = RecoveryReport::default();
522		self.inner_recover_vtxos(&mut report, ids).await?;
523		Ok(report)
524	}
525
526	/// Rebuild the wallet's spendable VTXO set from the seed-derived recovery
527	/// mailbox.
528	///
529	/// Reads every posted id, fetches the full VTXOs, keeps the ones we own
530	/// (deriving their keys), then imports those still spendable. Returns a
531	/// [`RecoveryReport`] (see it for why recovered/skipped/failed matters).
532	///
533	/// VTXOs are consumed newest-first so one spent into a newer recovered VTXO
534	/// is seen as already-spent and skipped; the server is consulted for the rest,
535	/// since a VTXO can also be spent outside our set (round, offboard, or arkoor
536	/// to a third party).
537	pub(crate) async fn recover_from_mailbox(&self) -> anyhow::Result<RecoveryReport> {
538		let mut report = RecoveryReport::default();
539
540		// Read all owned vtxos, de-duplicated
541		let (ids, checkpoint) = self.read_mailbox_recovery_vtxo_ids().await?;
542		debug!("Found {} distinct vtxo ids in the recovery mailbox", ids.len());
543
544		self.inner_recover_vtxos(&mut report, ids).await?;
545
546		// Unmatched ids in our own seed-derived mailbox are suspicious: most
547		// likely an owned VTXO whose key sits beyond the gap limit (funds may be
548		// missing), not a stranger's id. Retrying won't help these — only a wider
549		// gap limit can match them — so they get their own warning.
550		if !report.foreign.is_empty() {
551			warn!(
552				"Recovery mailbox held {} vtxo(s) not derivable from this seed within the \
553				gap limit ({STOP_GAP}); if any are ours they were not recovered: {:?}",
554				report.foreign.len(), report.foreign,
555			);
556		}
557
558		if report.is_complete() {
559			info!(
560				"Recovered {} spendable vtxos from the recovery mailbox ({} skipped)",
561				report.recovered.len(), report.skipped.len(),
562			);
563		}
564
565		// We retry 3 times to recover the failed VTXOs.
566		for _ in 0..3 {
567			if report.failed.is_empty() {
568				break;
569			}
570
571			let ids = report.failed.ids().collect::<Vec<_>>();
572			self.inner_recover_vtxos(&mut report, ids).await?;
573		}
574
575		if !report.failed.is_empty() {
576			warn!(
577				"Recovery incomplete: recovered {} spendable vtxos, but {} could not be \
578				checked due to errors; funds may be missing — retry recovery to recover \
579				them ({} skipped). Failed vtxos: {:?}",
580				report.recovered.len(), report.failed.len(),
581				report.skipped.len(), report.failed,
582			);
583		}
584
585		// We store the last checkpoint we processed so we can resume from there next time.
586		self.inner.db.store_mailbox_checkpoint(checkpoint).await?;
587
588		Ok(report)
589	}
590}
591
592#[cfg(test)]
593mod test {
594	use super::*;
595	use bitcoin::Amount;
596	use bitcoin::hashes::Hash;
597
598	fn dummy_id(vout: u32) -> VtxoId {
599		bitcoin::OutPoint::new(bitcoin::Txid::all_zeros(), vout).into()
600	}
601
602	/// `is_complete` hinges on whether any VTXO went unaccounted for: a `skipped`
603	/// VTXO is a clean decision, whereas a `failed` VTXO or a `foreign` id both
604	/// mean funds may be missing and the scan is incomplete.
605	#[test]
606	fn recovery_report_completeness() {
607		let clean = RecoveryReport {
608			recovered: RecoveryReportEntry(HashMap::from([(dummy_id(0), Some(Amount::from_sat(1000)))])),
609			skipped: RecoveryReportEntry(HashMap::from([(dummy_id(1), Some(Amount::from_sat(1000)))])),
610			foreign: RecoveryReportEntry(HashMap::new()),
611			failed: RecoveryReportEntry(HashMap::new()),
612			exited: RecoveryReportEntry(HashMap::new()),
613		};
614		assert!(clean.is_complete(),
615			"recovered and skipped VTXOs are clean decisions, not failures");
616
617		assert!(RecoveryReport::default().is_complete(),
618			"an empty report is trivially complete");
619		assert!(!RecoveryReport {
620			failed: RecoveryReportEntry(HashMap::from([(dummy_id(0), Some(Amount::from_sat(1000)))])),
621			..Default::default()
622		}.is_complete(), "a failed VTXO means recovery is incomplete");
623		assert!(!RecoveryReport {
624			foreign: RecoveryReportEntry(HashMap::from([(dummy_id(2), Some(Amount::from_sat(1000)))])),
625			..Default::default()
626		}.is_complete(), "a foreign id is likely an owned VTXO beyond the gap limit, so recovery is incomplete");
627	}
628}
629