Skip to main content

breez_sdk_spark/sdk/
recover_funds.rs

1use std::{
2    collections::{HashMap, HashSet},
3    sync::Arc,
4};
5
6use bitcoin::{
7    Address, Amount, FeeRate, OutPoint, ScriptBuf, Transaction, WPubkeyHash,
8    address::NetworkUnchecked,
9    consensus::encode::{deserialize_hex, serialize_hex},
10    hashes::Hash,
11};
12use spark_wallet::{
13    ChainQuery, ChainResult, EXITING_STATUSES, Fee, SilentPaymentAddress, SparkWalletError,
14    TreeNode, TreeNodeStatus, WATCHTOWER_EXITED_STATUSES, WatchtowerExitLookup,
15    refund_sweep_input_fee, watchtower_exit_recovery_payout,
16};
17use tracing::{debug, error, info};
18
19use crate::{
20    ChainTransaction, CheckRecoverFundsRequest, CheckRecoverFundsResponse,
21    CooperativeRecoveryError, CooperativeRecoveryFailure, ExitLeafSelection, ExitTransactionStatus,
22    LeafRecovery, Network, PrepareRecoverFundsRequest, PrepareRecoverFundsResponse,
23    RecoverFundsLeaf, RecoverFundsRequest, RecoverFundsResponse, RecoveryMethod,
24    RecoveryRedoReason, RecoveryTransaction, RecoveryTxKind, RecoveryVerdict, SdkEvent,
25    SkippedLeaf, SkippedLeafReason, Storage, UpdateLeafRecovery, error::SdkError,
26    persist::ObjectCacheRepository, signer::CpfpSigner, utils::time::now_secs,
27};
28
29use super::{
30    BreezSdk,
31    chain_queries::{ChainQueries, StoredCheck, StoredInBlock, result_of, without_result},
32    unilateral_exit::{
33        UnilateralBuild, UnilateralQuote, check_recovery_transactions, has_stored_sweep, node_ids,
34        store_exited_leaf_checks,
35    },
36    watchtower_exit::{
37        MissingExit, OutputSpend, WatchtowerExit, build_recovery, output_spend,
38        outputs_from_storage,
39    },
40};
41
42#[macros::instance_span]
43#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
44#[allow(clippy::needless_pass_by_value)]
45impl BreezSdk {
46    /// Prepares a recovery of the selected leaves: how each is recovered, the
47    /// exact fees, and how much to fund. It records a recovery or sweep it finds
48    /// in a block, and takes those funds out of the total to recover.
49    pub async fn prepare_recover_funds(
50        &self,
51        request: PrepareRecoverFundsRequest,
52    ) -> Result<PrepareRecoverFundsResponse, SdkError> {
53        let fee_rate = request.fee_rate_sat_per_vbyte;
54        let destination = parse_destination(&request.destination, self.config.network)?;
55        self.spark_wallet.refresh_before_exit().await;
56        let mut queries = ChainQueries::new(self.chain_service.clone());
57        let stored = self
58            .checked_leaf_recoveries(&request.selection, &mut queries)
59            .await?;
60        let selection = self
61            .split_selection(request.selection, &stored, &mut queries)
62            .await?;
63
64        let mut leaves = Vec::new();
65        let mut skipped = selection.skipped;
66        let mut cooperative_fee_sats = 0u64;
67        for exit in selection.cooperative {
68            let Some(recovery) = build_recovery(&exit.output, &destination, fee_rate) else {
69                skipped.push(SkippedLeaf {
70                    leaf_id: exit.leaf_id,
71                    value_sats: exit.value_sats,
72                    reason: SkippedLeafReason::FeeExceedsValue,
73                });
74                continue;
75            };
76            cooperative_fee_sats = cooperative_fee_sats
77                .saturating_add(exit.exit_fee_sats())
78                .saturating_add(recovery.fee_sat);
79            leaves.push(RecoverFundsLeaf {
80                leaf_id: exit.leaf_id,
81                value_sats: exit.value_sats,
82                method: RecoveryMethod::Cooperative,
83            });
84        }
85        let cooperative_value_sats = total_value(&leaves);
86        let unilateral = match selection.unilateral {
87            Some(unilateral) => {
88                self.quote_unilateral_exit(
89                    &destination,
90                    fee_rate,
91                    request.funding_kind.as_ref(),
92                    request.funding_strategy.unwrap_or_default(),
93                    unilateral,
94                    &selection.not_unilateral,
95                    &stored,
96                    &mut queries,
97                )
98                .await?
99            }
100            None => UnilateralQuote::default(),
101        };
102        leaves.extend(unilateral.leaves);
103        skipped.extend(unilateral.skipped);
104
105        let response = PrepareRecoverFundsResponse {
106            leaves,
107            skipped,
108            recoverable_value_sats: cooperative_value_sats
109                .saturating_add(unilateral.recoverable_value_sats),
110            total_fee_sats: cooperative_fee_sats.saturating_add(unilateral.total_fee_sats),
111            cooperative_fee_sats,
112            cpfp_fee_sats: unilateral.cpfp_fee_sats,
113            fanout_fee_sats: unilateral.fanout_fee_sats,
114            refund_fee_sats: unilateral.refund_fee_sats,
115            sweep_fee_sats: unilateral.sweep_fee_sats,
116            funding: unilateral.funding,
117            fee_rate_sat_per_vbyte: fee_rate,
118            destination: request.destination,
119            exit_chain_state: unilateral.exit_chain_state,
120        };
121        debug!(
122            leaves = response.leaves.len(),
123            recoverable_value_sats = response.recoverable_value_sats,
124            total_fee_sats = response.total_fee_sats,
125            "prepare_recover_funds: quote ready"
126        );
127        self.take_out_finished_leaves(&stored).await;
128        Ok(response)
129    }
130
131    /// Builds and signs the recovery a `prepare_recover_funds` quote describes:
132    /// the operators co-sign each cooperative recovery, and `signer` signs the
133    /// spends of `funding_inputs` for the unilateral exit. Returns every
134    /// transaction in broadcast order, without broadcasting.
135    pub async fn recover_funds(
136        &self,
137        request: RecoverFundsRequest,
138        signer: Option<Arc<dyn CpfpSigner>>,
139    ) -> Result<RecoverFundsResponse, SdkError> {
140        let RecoverFundsRequest {
141            prepared,
142            funding_inputs,
143        } = request;
144        let fee_rate = prepared.fee_rate_sat_per_vbyte;
145        let destination = parse_destination(&prepared.destination, self.config.network)?;
146        let (cooperative, unilateral): (Vec<&RecoverFundsLeaf>, Vec<&RecoverFundsLeaf>) = prepared
147            .leaves
148            .iter()
149            .partition(|leaf| leaf.method == RecoveryMethod::Cooperative);
150
151        // Looked up first, so an unknown leaf fails the call before anything is
152        // signed.
153        let mut queries = ChainQueries::new(self.chain_service.clone());
154        let stored = self.leaf_recoveries().await?;
155        let (exits, failed) = self
156            .quoted_watchtower_exits(&cooperative, &stored, &mut queries)
157            .await?;
158
159        let unilateral = if unilateral.is_empty() {
160            UnilateralBuild::default()
161        } else {
162            let leaf_ids: Vec<String> =
163                unilateral.iter().map(|leaf| leaf.leaf_id.clone()).collect();
164            self.build_unilateral_exit(
165                &destination,
166                node_ids(&leaf_ids)?,
167                fee_rate,
168                funding_inputs.clone(),
169                prepared
170                    .funding
171                    .as_ref()
172                    .map_or(0, |funding| funding.single_utxo_sats),
173                prepared
174                    .funding
175                    .as_ref()
176                    .map(|funding| funding.strategy)
177                    .unwrap_or_default(),
178                &prepared.exit_chain_state,
179                signer.as_deref(),
180                &mut queries,
181            )
182            .await?
183        };
184
185        let cooperative = self
186            .cosign_cooperative_recoveries(exits, &destination, fee_rate, &mut queries)
187            .await;
188        let mut leaves = cooperative.leaves;
189        let recoverable_value_sats =
190            total_value(&leaves).saturating_add(unilateral.recoverable_value_sats);
191        leaves.extend(unilateral.leaves);
192        let mut transactions = cooperative.transactions;
193        transactions.extend(unilateral.transactions);
194        let response = RecoverFundsResponse {
195            recoverable_value_sats,
196            total_fee_sats: cooperative
197                .fee_sats
198                .saturating_add(unilateral.total_fee_sats),
199            cooperative_fee_sats: cooperative.fee_sats,
200            cpfp_fee_sats: unilateral.cpfp_fee_sats,
201            fanout_fee_sats: unilateral.fanout_fee_sats,
202            refund_fee_sats: unilateral.refund_fee_sats,
203            sweep_fee_sats: unilateral.sweep_fee_sats,
204            leaves,
205            failed: failed.into_iter().chain(cooperative.failed).collect(),
206            transactions,
207            funding_inputs,
208            fee_rate_sat_per_vbyte: fee_rate,
209            destination: prepared.destination,
210        };
211        debug!(
212            transactions = response.transactions.len(),
213            failed = response.failed.len(),
214            total_fee_sats = response.total_fee_sats,
215            "recover_funds: complete"
216        );
217        self.take_out_finished_leaves(&stored).await;
218        Ok(response)
219    }
220
221    /// Reads a recovery you kept back against the chain: which of its
222    /// transactions are now in a block, and whether it can still be finished as
223    /// it stands.
224    pub async fn check_recover_funds(
225        &self,
226        request: CheckRecoverFundsRequest,
227    ) -> Result<CheckRecoverFundsResponse, SdkError> {
228        let mut recovery = request.recovery;
229        let (mut cooperative, mut unilateral): (Vec<_>, Vec<_>) =
230            std::mem::take(&mut recovery.transactions)
231                .into_iter()
232                .partition(|tx| tx.kind == RecoveryTxKind::Cooperative);
233        let mut queries = ChainQueries::new(self.chain_service.clone());
234        let recovered = check_cooperative_recoveries(&mut queries, &mut cooperative).await?;
235        let diverged = check_recovery_transactions(&mut queries, &mut unilateral).await?;
236        recovery.transactions = cooperative.into_iter().chain(unilateral).collect();
237        self.record_finished(&recovery.transactions, recovered)
238            .await;
239
240        let verdict = if diverged {
241            RecoveryVerdict::Redo {
242                reason: RecoveryRedoReason::OnChainStateDiverged,
243            }
244        } else if recovery_done(&recovery.transactions, &mut queries).await {
245            RecoveryVerdict::Done
246        } else {
247            RecoveryVerdict::Valid
248        };
249        debug!(?verdict, "check_recover_funds: read back");
250        Ok(CheckRecoverFundsResponse { recovery, verdict })
251    }
252}
253
254#[derive(Default)]
255struct CooperativeRecoveries {
256    leaves: Vec<RecoverFundsLeaf>,
257    transactions: Vec<RecoveryTransaction>,
258    failed: Vec<CooperativeRecoveryFailure>,
259    fee_sats: u64,
260}
261
262struct RecoverySelection {
263    cooperative: Vec<WatchtowerExit>,
264    /// Leaves only a cooperative recovery reaches, and that have none to prepare.
265    skipped: Vec<SkippedLeaf>,
266    unilateral: Option<spark_wallet::ExitLeafSelection>,
267    /// Leaves that no unilateral exit recovers.
268    not_unilateral: HashSet<String>,
269}
270
271/// The leaves a sync has work for, by what the SDK does with each.
272#[derive(Default)]
273struct NewLeaves {
274    /// Leaves without a stored recovery. The SDK stores these as they are,
275    /// without a chain check.
276    to_recover: Vec<UpdateLeafRecovery>,
277    /// Leaves whose check is not complete. The SDK checks these with the chain
278    /// service: the operators report a recovered leaf the same whether or not
279    /// its recovery is in a block.
280    recovered: Vec<TreeNode>,
281    /// Leaves without a stored recovery. The SDK checks these with the chain
282    /// service: the operators report an exited leaf the same whether or not a
283    /// sweep of its refund is in a block.
284    exited: Vec<TreeNode>,
285}
286
287impl BreezSdk {
288    pub(crate) async fn recoverable_funds_sats(&self) -> Result<u64, SdkError> {
289        Ok(ObjectCacheRepository::new(self.storage.clone())
290            .fetch_recoverable_funds()
291            .await?
292            .unwrap_or_default())
293    }
294
295    /// The stored recoveries as prepare reads them. The SDK first checks that
296    /// the recovery or sweep of a finished leaf is still in a block: always for
297    /// a leaf `selection` names, and else while the transaction is not settled.
298    /// One the chain service no longer shows in a block is left out, so its
299    /// leaf is not finished for this call. Storage keeps it.
300    async fn checked_leaf_recoveries(
301        &self,
302        selection: &ExitLeafSelection,
303        queries: &mut ChainQueries,
304    ) -> Result<HashMap<String, LeafRecovery>, SdkError> {
305        let stored = self.leaf_recoveries().await?;
306        let named = named_leaf_ids(selection);
307        let finished = finished_transactions(&stored, named.as_ref());
308        let checks = queries.check_stored_in_block(&finished).await;
309        let (stored, moved) = after_finished_checks(stored, &checks);
310        for update in moved {
311            self.store_leaf_recovery(update).await;
312        }
313        Ok(stored)
314    }
315
316    pub(super) async fn leaf_recoveries(&self) -> Result<HashMap<String, LeafRecovery>, SdkError> {
317        leaf_recoveries(self.storage.as_ref()).await
318    }
319
320    pub(super) async fn store_leaf_recovery(&self, update: UpdateLeafRecovery) -> bool {
321        store_update(self.storage.as_ref(), update).await
322    }
323
324    /// Stores the recovery of each leaf that has none stored, then the total of the
325    /// funds to recover: the value of every leaf whose recovery or sweep the SDK
326    /// has not seen in a block. The funds of a recovered or exited leaf may have
327    /// left already, so the SDK checks such leaves with the chain service, in
328    /// batches, and stores what each batch established: a later sync continues
329    /// where a failed request stopped this one. Emits `RecoverableFunds` for a
330    /// leaf it stored without a check, or whose check it completed with funds
331    /// still to recover.
332    pub(super) async fn sync_recoverable_funds(&self) {
333        let leaves = match self.leaves_that_left_the_balance().await {
334            Ok(leaves) => leaves,
335            Err(e) => {
336                error!("Failed to list the leaves to recover: {e}");
337                return;
338            }
339        };
340        let mut stored = if leaves.is_empty() {
341            HashMap::new()
342        } else {
343            match self.leaf_recoveries().await {
344                Ok(stored) => stored,
345                Err(e) => {
346                    error!("Failed to read the stored leaf recoveries: {e}");
347                    return;
348                }
349            }
350        };
351        let new = new_leaves(&leaves, &stored);
352        let mut new_leaf_ids: HashSet<String> = HashSet::new();
353        for update in new.to_recover {
354            let leaf_id = update.leaf_id.clone();
355            if self.store_leaf_recovery(update).await {
356                new_leaf_ids.insert(leaf_id);
357            }
358        }
359        let mut queries = ChainQueries::for_sync(self.chain_service.clone());
360        new_leaf_ids.extend(
361            self.check_recovered_leaves(&new.recovered, &stored, &mut queries)
362                .await,
363        );
364        new_leaf_ids.extend(
365            store_exited_leaf_checks(
366                &new.exited,
367                self.config.network.into(),
368                &mut queries,
369                self.storage.as_ref(),
370            )
371            .await,
372        );
373        // The SDK stored what the checks above found, and it can have stored a
374        // recovery or sweep in one of the recovery calls meanwhile.
375        if !leaves.is_empty() {
376            stored = match self.leaf_recoveries().await {
377                Ok(stored) => stored,
378                Err(e) => {
379                    error!("Failed to read the stored leaf recoveries: {e}");
380                    return;
381                }
382            };
383        }
384        let (funds, found) = recoverable_funds(&leaves, &stored, &new_leaf_ids);
385
386        let repository = ObjectCacheRepository::new(self.storage.clone());
387        let stored_funds = match repository.fetch_recoverable_funds().await {
388            Ok(stored_funds) => stored_funds.unwrap_or_default(),
389            Err(e) => {
390                error!("Failed to read the recoverable funds: {e}");
391                0
392            }
393        };
394        if funds != stored_funds
395            && let Err(e) = repository.save_recoverable_funds(funds).await
396        {
397            error!("Failed to store the recoverable funds: {e}");
398        }
399        if found > 0 {
400            info!("Found {found} leaves with funds to recover");
401            self.event_emitter
402                .emit(&SdkEvent::RecoverableFunds {
403                    recoverable_funds_sats: funds,
404                })
405                .await;
406        }
407    }
408
409    /// Stores the spends in `recovered` and the sweeps in a block among
410    /// `transactions`, and takes their leaves out of the recoverable funds.
411    async fn record_finished(
412        &self,
413        transactions: &[RecoveryTransaction],
414        recovered: Vec<(String, ChainTransaction)>,
415    ) {
416        let swept = swept_leaves(transactions);
417        if recovered.is_empty() && swept.is_empty() {
418            return;
419        }
420        let stored = match self.leaf_recoveries().await {
421            Ok(stored) => stored,
422            Err(e) => {
423                error!("Failed to read the stored leaf recoveries: {e}");
424                return;
425            }
426        };
427        store_finished(self.storage.as_ref(), &stored, recovered, swept).await;
428        self.take_out_finished_leaves(&stored).await;
429    }
430
431    /// Takes each leaf whose recovery or sweep the SDK stored after it read
432    /// `before` out of the stored recoverable funds.
433    async fn take_out_finished_leaves(&self, before: &HashMap<String, LeafRecovery>) {
434        let leaves = match self.leaves_that_left_the_balance().await {
435            Ok(leaves) => leaves,
436            Err(e) => {
437                error!("Failed to list the leaves to recover: {e}");
438                return;
439            }
440        };
441        take_out_finished_leaves(&self.storage, &leaves, before).await;
442    }
443
444    async fn leaves_that_left_the_balance(&self) -> Result<Vec<TreeNode>, SparkWalletError> {
445        let statuses = [EXITING_STATUSES.as_slice(), &WATCHTOWER_EXITED_STATUSES].concat();
446        self.spark_wallet.list_leaves_with_status(&statuses).await
447    }
448
449    async fn cosign_cooperative_recoveries(
450        &self,
451        exits: Vec<WatchtowerExit>,
452        destination: &Address,
453        fee_rate: u64,
454        queries: &mut ChainQueries,
455    ) -> CooperativeRecoveries {
456        let mut recoveries = CooperativeRecoveries::default();
457        let mut unreachable: Option<String> = None;
458        for exit in exits {
459            match self
460                .cooperative_recovery(
461                    &exit,
462                    destination,
463                    fee_rate,
464                    unreachable.as_deref(),
465                    queries,
466                )
467                .await
468            {
469                Ok(Some(recovery)) => {
470                    let tx = recovery.tx;
471                    recoveries.fee_sats = recoveries
472                        .fee_sats
473                        .saturating_add(exit.exit_fee_sats())
474                        .saturating_add(recovery.fee_sats);
475                    recoveries.leaves.push(RecoverFundsLeaf {
476                        leaf_id: exit.leaf_id.clone(),
477                        value_sats: exit.value_sats,
478                        method: RecoveryMethod::Cooperative,
479                    });
480                    recoveries.transactions.push(RecoveryTransaction {
481                        kind: RecoveryTxKind::Cooperative,
482                        node_id: Some(exit.leaf_id),
483                        txid: tx.compute_txid().to_string(),
484                        tx_hex: serialize_hex(&tx),
485                        cpfp_tx_hex: None,
486                        csv_timelock_blocks: None,
487                        depends_on: Vec::new(),
488                        status: if recovery.verified {
489                            ExitTransactionStatus::Ready
490                        } else {
491                            ExitTransactionStatus::Unverified
492                        },
493                    });
494                }
495                Ok(None) => debug!(
496                    leaf_id = exit.leaf_id,
497                    "recover_funds: a recovery of the leaf is in a block"
498                ),
499                Err(error) => {
500                    info!(
501                        "Leaf {} was not recovered cooperatively: {error}",
502                        exit.leaf_id
503                    );
504                    if let CooperativeRecoveryError::OperatorsUnavailable { message } = &error {
505                        unreachable.get_or_insert_with(|| message.clone());
506                    }
507                    recoveries.failed.push(CooperativeRecoveryFailure {
508                        leaf_id: exit.leaf_id,
509                        output_txid: exit.output.outpoint.txid.to_string(),
510                        output_vout: exit.output.outpoint.vout,
511                        error,
512                    });
513                }
514            }
515        }
516        recoveries
517    }
518
519    async fn watchtower_exit_candidates(&self) -> Result<Vec<TreeNode>, SdkError> {
520        let statuses = [
521            WATCHTOWER_EXITED_STATUSES.as_slice(),
522            // Its direct tx can confirm at a fee its refunds do not spend, and a
523            // leaf renewed at a zero timelock has no refund spending it at all.
524            &[TreeNodeStatus::OnChain],
525        ]
526        .concat();
527        Ok(self.spark_wallet.list_leaves_with_status(&statuses).await?)
528    }
529
530    /// The watchtower exit of each cooperative leaf of a prepare response, and
531    /// the leaves the SDK builds no recovery for. Fails when the SDK has no
532    /// output at all for a leaf: the prepare response then does not match the
533    /// wallet's data.
534    async fn quoted_watchtower_exits(
535        &self,
536        leaves: &[&RecoverFundsLeaf],
537        stored: &HashMap<String, LeafRecovery>,
538        queries: &mut ChainQueries,
539    ) -> Result<(Vec<WatchtowerExit>, Vec<CooperativeRecoveryFailure>), SdkError> {
540        if leaves.is_empty() {
541            return Ok((Vec::new(), Vec::new()));
542        }
543        let listed: Vec<TreeNode> = self
544            .watchtower_exit_candidates()
545            .await?
546            .into_iter()
547            .filter(|leaf| {
548                let leaf_id = leaf.id.to_string();
549                leaves.iter().any(|quoted| quoted.leaf_id == leaf_id)
550            })
551            .collect();
552        // The recovery takes every stored output as it is: prepare checked it.
553        let from_storage: HashSet<String> = listed
554            .iter()
555            .map(|leaf| leaf.id.to_string())
556            .filter(|leaf_id| {
557                stored
558                    .get(leaf_id)
559                    .is_some_and(|stored| stored.watchtower_exit_output.is_some())
560            })
561            .collect();
562        let mut found = self
563            .lookup_watchtower_exits(&listed, stored, &from_storage, queries)
564            .await?;
565        let recovered: HashSet<String> = listed
566            .iter()
567            .filter(|leaf| leaf.status == TreeNodeStatus::WatchtowerExitRecovered)
568            .map(|leaf| leaf.id.to_string())
569            .collect();
570        let mut exits = Vec::with_capacity(leaves.len());
571        let mut failed = Vec::new();
572        for leaf in leaves {
573            if let Some(exit) = found.exits.remove(&leaf.leaf_id) {
574                exits.push(exit);
575                continue;
576            }
577            let unresolved = unresolved_exit(
578                leaf,
579                found.missing.get(&leaf.leaf_id),
580                stored.get(&leaf.leaf_id),
581                recovered.contains(&leaf.leaf_id),
582            )?;
583            match unresolved {
584                Unresolved::Exit(exit) => exits.push(exit),
585                Unresolved::Failed(failure) => failed.push(failure),
586            }
587        }
588        Ok((exits, failed))
589    }
590
591    async fn split_selection(
592        &self,
593        selection: ExitLeafSelection,
594        stored: &HashMap<String, LeafRecovery>,
595        queries: &mut ChainQueries,
596    ) -> Result<RecoverySelection, SdkError> {
597        let named = named_leaf_ids(&selection);
598        if named.as_ref().is_some_and(HashSet::is_empty) {
599            return Err(SdkError::InvalidInput("No leaves to recover".to_string()));
600        }
601        let candidates = self
602            .watchtower_exit_candidates()
603            .await?
604            .into_iter()
605            .filter(|leaf| {
606                named
607                    .as_ref()
608                    .is_none_or(|named| named.contains(&leaf.id.to_string()))
609            })
610            .collect();
611        let (finished, selected) = finished_and_open(candidates, stored);
612        let from_storage =
613            outputs_from_storage(&selected, stored, queries, self.storage.as_ref()).await;
614        let mut found = self
615            .lookup_watchtower_exits(&selected, stored, &from_storage, queries)
616            .await?;
617
618        let mut not_unilateral: HashSet<String> = selected
619            .iter()
620            .chain(&finished)
621            .filter(|leaf| leaf.status.is_watchtower_exited())
622            .map(|leaf| leaf.id.to_string())
623            .collect();
624        not_unilateral.extend(found.exits.keys().cloned());
625        // A finished leaf has nothing left to exit, also when the SDK cannot
626        // read its exit from the chain.
627        not_unilateral.extend(
628            stored
629                .values()
630                .filter(|leaf| is_finished(leaf))
631                .map(|leaf| leaf.leaf_id.clone()),
632        );
633        let mut skipped: Vec<SkippedLeaf> = selected
634            .iter()
635            .filter_map(|leaf| {
636                let leaf_id = leaf.id.to_string();
637                let lookup = found.missing.get(&leaf_id).map(|missing| &missing.lookup);
638                skipped_cooperative_leaf(leaf, stored.get(&leaf_id), lookup)
639            })
640            .collect();
641        if found.operators_unavailable {
642            for leaf in &mut skipped {
643                leaf.reason = SkippedLeafReason::OperatorsUnavailable;
644            }
645        }
646        let cooperative = selected
647            .iter()
648            .filter_map(|leaf| found.exits.remove(&leaf.id.to_string()))
649            .filter(|exit| !exit.recovered)
650            .collect();
651
652        let unilateral = match selection {
653            ExitLeafSelection::Specific { leaf_ids } => {
654                let leaf_ids = named_for_unilateral(leaf_ids, &not_unilateral, stored);
655                if leaf_ids.is_empty() {
656                    None
657                } else {
658                    Some(spark_wallet::ExitLeafSelection::Specific(node_ids(
659                        &leaf_ids,
660                    )?))
661                }
662            }
663            ExitLeafSelection::All => Some(spark_wallet::ExitLeafSelection::Auto),
664            ExitLeafSelection::RecoverableOnly => Some(spark_wallet::ExitLeafSelection::Exiting),
665        };
666        Ok(RecoverySelection {
667            cooperative,
668            skipped,
669            unilateral,
670            not_unilateral,
671        })
672    }
673}
674
675/// What `recover_funds` makes of a cooperative leaf without an exit from the
676/// lookup.
677enum Unresolved {
678    Exit(WatchtowerExit),
679    Failed(CooperativeRecoveryFailure),
680}
681
682/// The exit of `leaf` when the lookup gave none, or why the leaf failed. The
683/// SDK builds on the stored output of a leaf the wallet no longer lists, and
684/// on the output it assumes when the lookup has no result. A lookup that shows
685/// the leaf's funds elsewhere fails the leaf. Errors when the SDK has no output
686/// for the leaf at all.
687fn unresolved_exit(
688    leaf: &RecoverFundsLeaf,
689    missing: Option<&MissingExit>,
690    stored: Option<&LeafRecovery>,
691    recovered: bool,
692) -> Result<Unresolved, SdkError> {
693    let no_output = || {
694        SdkError::InvalidInput(format!(
695            "Leaf {} has no funds this wallet can recover cooperatively",
696            leaf.leaf_id
697        ))
698    };
699    let Some(missing) = missing else {
700        let exit = stored
701            .map(|stored| WatchtowerExit::from_stored(leaf.value_sats, stored))
702            .transpose()?
703            .flatten();
704        return exit.map(Unresolved::Exit).ok_or_else(no_output);
705    };
706    let assumed = missing.assumed.clone().ok_or_else(no_output)?;
707    let message = match &missing.lookup {
708        WatchtowerExitLookup::NotFound => "The chain shows the leaf's funds in no output",
709        WatchtowerExitLookup::Unrecoverable => {
710            "The transaction that took the leaf's funds on-chain pays none of them to the \
711             leaf's key"
712        }
713        WatchtowerExitLookup::Unilateral => "The leaf's own refunds recover its funds",
714        WatchtowerExitLookup::Pending
715        | WatchtowerExitLookup::Found { .. }
716        | WatchtowerExitLookup::Unconfirmed(_) => {
717            return Ok(Unresolved::Exit(
718                WatchtowerExit::new(
719                    leaf.leaf_id.clone(),
720                    leaf.value_sats,
721                    assumed,
722                    stored,
723                    &OutputSpend::Unknown,
724                    recovered,
725                )
726                .assumed(),
727            ));
728        }
729    };
730    Ok(Unresolved::Failed(CooperativeRecoveryFailure {
731        leaf_id: leaf.leaf_id.clone(),
732        output_txid: assumed.outpoint.txid.to_string(),
733        output_vout: assumed.outpoint.vout,
734        error: CooperativeRecoveryError::Generic {
735            message: message.to_string(),
736        },
737    }))
738}
739
740/// The leaves `selection` names. `None` for a selection by status.
741fn named_leaf_ids(selection: &ExitLeafSelection) -> Option<HashSet<String>> {
742    match selection {
743        ExitLeafSelection::Specific { leaf_ids } => Some(leaf_ids.iter().cloned().collect()),
744        ExitLeafSelection::All | ExitLeafSelection::RecoverableOnly => None,
745    }
746}
747
748/// The named leaves the unilateral prepare gets. One with a stored sweep is
749/// among them although nothing is left to exit: the unilateral prepare reports
750/// its refund as swept.
751fn named_for_unilateral(
752    leaf_ids: Vec<String>,
753    not_unilateral: &HashSet<String>,
754    stored: &HashMap<String, LeafRecovery>,
755) -> Vec<String> {
756    leaf_ids
757        .into_iter()
758        .filter(|leaf_id| !not_unilateral.contains(leaf_id) || has_stored_sweep(stored, leaf_id))
759        .collect()
760}
761
762/// The recovery and the sweep in a block of each finished leaf a call covers:
763/// the leaves in `named`, or every stored leaf for a selection by status. The
764/// SDK checks one of a named leaf however deep it is.
765fn finished_transactions(
766    stored: &HashMap<String, LeafRecovery>,
767    named: Option<&HashSet<String>>,
768) -> Vec<StoredInBlock> {
769    stored
770        .values()
771        .filter(|leaf| named.is_none_or(|named| named.contains(&leaf.leaf_id)))
772        .flat_map(|leaf| [&leaf.watchtower_exit_spend, &leaf.unilateral_exit_sweep])
773        .flatten()
774        .map(|transaction| StoredInBlock {
775            txid: transaction.txid.clone(),
776            block_height: transaction.block_height,
777            check_always: named.is_some(),
778        })
779        .collect()
780}
781
782/// `transaction` after its check: unset when the chain service no longer shows
783/// it in a block, and at its new height when it shows it in another block.
784/// Also whether the height changed.
785fn after_check(
786    transaction: Option<ChainTransaction>,
787    checks: &HashMap<String, StoredCheck>,
788) -> (Option<ChainTransaction>, bool) {
789    let Some(transaction) = transaction else {
790        return (None, false);
791    };
792    match checks.get(&transaction.txid) {
793        Some(StoredCheck::NotInBlock) => (None, false),
794        Some(StoredCheck::InBlock {
795            block_height: Some(block_height),
796        }) if *block_height != transaction.block_height => (
797            Some(ChainTransaction {
798                block_height: *block_height,
799                ..transaction
800            }),
801            true,
802        ),
803        _ => (Some(transaction), false),
804    }
805}
806
807/// `stored` after the `checks` of its recoveries and sweeps, and what to store:
808/// each transaction the chain service shows in another block than the stored
809/// one.
810fn after_finished_checks(
811    stored: HashMap<String, LeafRecovery>,
812    checks: &HashMap<String, StoredCheck>,
813) -> (HashMap<String, LeafRecovery>, Vec<UpdateLeafRecovery>) {
814    let mut moved = Vec::new();
815    let stored = stored
816        .into_iter()
817        .map(|(leaf_id, mut leaf)| {
818            let (spend, spend_moved) = after_check(leaf.watchtower_exit_spend.take(), checks);
819            let (sweep, sweep_moved) = after_check(leaf.unilateral_exit_sweep.take(), checks);
820            if spend_moved || sweep_moved {
821                moved.push(UpdateLeafRecovery {
822                    leaf_id: leaf_id.clone(),
823                    watchtower_exit_spend: spend.clone().filter(|_| spend_moved),
824                    unilateral_exit_sweep: sweep.clone().filter(|_| sweep_moved),
825                    ..Default::default()
826                });
827            }
828            leaf.watchtower_exit_spend = spend;
829            leaf.unilateral_exit_sweep = sweep;
830            (leaf_id, leaf)
831        })
832        .collect();
833    (stored, moved)
834}
835
836async fn leaf_recoveries(storage: &dyn Storage) -> Result<HashMap<String, LeafRecovery>, SdkError> {
837    Ok(storage
838        .list_leaf_recoveries()
839        .await?
840        .into_iter()
841        .map(|leaf| (leaf.leaf_id.clone(), leaf))
842        .collect())
843}
844
845/// Stores each spend in `recovered` and each sweep in `swept` that is not in
846/// `stored` yet.
847async fn store_finished(
848    storage: &dyn Storage,
849    stored: &HashMap<String, LeafRecovery>,
850    recovered: Vec<(String, ChainTransaction)>,
851    swept: Vec<(String, ChainTransaction)>,
852) {
853    let now = now_secs();
854    // The SDK stores a spend only for a leaf that has a stored recovery.
855    let recovered = recovered
856        .into_iter()
857        .filter(|(leaf_id, spend)| {
858            stored
859                .get(leaf_id)
860                .is_some_and(|leaf| leaf.watchtower_exit_spend.as_ref() != Some(spend))
861        })
862        .map(|(leaf_id, spend)| UpdateLeafRecovery {
863            leaf_id,
864            chain_checked_at: Some(now),
865            watchtower_exit_spend: Some(spend),
866            ..Default::default()
867        });
868    let swept = swept
869        .into_iter()
870        .filter(|(leaf_id, sweep)| {
871            stored
872                .get(leaf_id)
873                .is_none_or(|leaf| leaf.unilateral_exit_sweep.as_ref() != Some(sweep))
874        })
875        .map(|(leaf_id, sweep)| UpdateLeafRecovery {
876            leaf_id,
877            chain_checked_at: Some(now),
878            unilateral_exit_sweep: Some(sweep),
879            ..Default::default()
880        });
881    for update in recovered.chain(swept).collect::<Vec<_>>() {
882        store_update(storage, update).await;
883    }
884}
885
886/// Returns whether storing `update` succeeded. The SDK only logs a failure: it
887/// can get what the update holds again, from the chain service or the
888/// operators.
889pub(super) async fn store_update(storage: &dyn Storage, update: UpdateLeafRecovery) -> bool {
890    let leaf_id = update.leaf_id.clone();
891    match storage.update_leaf_recovery(update).await {
892        Ok(()) => true,
893        Err(e) => {
894            error!("Failed to store the recovery of leaf {leaf_id}: {e}");
895            false
896        }
897    }
898}
899
900/// Stores `checks` and returns the leaves among them whose check is complete.
901pub(super) async fn store_checks(
902    storage: &dyn Storage,
903    checks: Vec<UpdateLeafRecovery>,
904) -> Vec<String> {
905    let mut complete = Vec::new();
906    for check in checks {
907        let leaf_id = check.leaf_id.clone();
908        let is_complete = check.chain_checked_at.is_some();
909        if store_update(storage, check).await && is_complete {
910            complete.push(leaf_id);
911        }
912    }
913    complete
914}
915
916/// Whether storage holds the recovery or the sweep of the leaf's funds in a
917/// block.
918fn is_finished(stored: &LeafRecovery) -> bool {
919    stored.watchtower_exit_spend.is_some() || stored.unilateral_exit_sweep.is_some()
920}
921
922/// Splits `leaves` into the finished ones and the ones prepare still looks up.
923/// A lookup of a finished leaf could only find again what storage holds.
924fn finished_and_open(
925    leaves: Vec<TreeNode>,
926    stored: &HashMap<String, LeafRecovery>,
927) -> (Vec<TreeNode>, Vec<TreeNode>) {
928    leaves
929        .into_iter()
930        .partition(|leaf| stored.get(&leaf.id.to_string()).is_some_and(is_finished))
931}
932
933/// Whether every transaction of a recovery is in a block. After the chain
934/// service failed a request, the SDK may have used a recorded confirmation
935/// that it could not check again, so then it also requires the latest
936/// confirmation to be settled.
937async fn recovery_done(transactions: &[RecoveryTransaction], queries: &mut ChainQueries) -> bool {
938    let mut latest: Option<u32> = None;
939    for tx in transactions {
940        let ExitTransactionStatus::Confirmed { block_height } = tx.status else {
941            return false;
942        };
943        latest = latest.max(block_height);
944    }
945    if transactions.is_empty() {
946        return false;
947    }
948    if !queries.failed() {
949        return true;
950    }
951    match latest {
952        Some(block_height) => queries.settled(block_height).await,
953        None => false,
954    }
955}
956
957/// Whether the SDK found the leaf's output and has yet to learn whether that
958/// output is spent.
959fn check_incomplete(stored: &LeafRecovery) -> bool {
960    stored.chain_checked_at.is_none() && stored.watchtower_exit_output.is_some()
961}
962
963fn new_leaves(leaves: &[TreeNode], stored: &HashMap<String, LeafRecovery>) -> NewLeaves {
964    let mut new = NewLeaves::default();
965    for leaf in leaves {
966        let leaf_id = leaf.id.to_string();
967        if let Some(stored) = stored.get(&leaf_id) {
968            if check_incomplete(stored) {
969                new.recovered.push(leaf.clone());
970            }
971            continue;
972        }
973        match leaf.status {
974            // The SDK sends no chain request for funds too small to send out.
975            _ if !can_be_sent_out(leaf) => new.to_recover.push(UpdateLeafRecovery {
976                leaf_id,
977                ..Default::default()
978            }),
979            TreeNodeStatus::WatchtowerExitRecovered => new.recovered.push(leaf.clone()),
980            TreeNodeStatus::Exited => new.exited.push(leaf.clone()),
981            _ => new.to_recover.push(UpdateLeafRecovery {
982                leaf_id,
983                ..Default::default()
984            }),
985        }
986    }
987    new
988}
989
990/// Whether the funds of a recovered or exited `leaf` can be sent out at the
991/// lowest fee rate nodes relay. The leaf's value is the most its on-chain
992/// output holds.
993fn can_be_sent_out(leaf: &TreeNode) -> bool {
994    let value = Amount::from_sat(leaf.value);
995    let fee_rate = FeeRate::BROADCAST_MIN;
996    match leaf.status {
997        // A recovery is a transaction of its own. Of the outputs wallets
998        // receive on, P2WPKH is the smallest and has the lowest dust limit.
999        TreeNodeStatus::WatchtowerExitRecovered => {
1000            let output = ScriptBuf::new_p2wpkh(&WPubkeyHash::all_zeros());
1001            let fee = Fee::Rate {
1002                sat_per_vbyte: fee_rate.to_sat_per_vb_ceil(),
1003            };
1004            watchtower_exit_recovery_payout(value, &output, fee).is_some()
1005        }
1006        // One sweep has the refunds of several leaves as inputs, so a refund
1007        // only has to hold more than the fee of its own input.
1008        TreeNodeStatus::Exited => refund_sweep_input_fee(fee_rate).is_some_and(|fee| value > fee),
1009        _ => true,
1010    }
1011}
1012
1013/// The value of the leaves without a stored watchtower exit spend or sweep, and
1014/// how many of them are among `new_leaf_ids`. A leaf whose check is not
1015/// complete has neither, so it is counted.
1016fn recoverable_funds(
1017    leaves: &[TreeNode],
1018    stored: &HashMap<String, LeafRecovery>,
1019    new_leaf_ids: &HashSet<String>,
1020) -> (u64, usize) {
1021    let mut funds: u64 = 0;
1022    let mut found: usize = 0;
1023    for leaf in leaves {
1024        let leaf_id = leaf.id.to_string();
1025        if stored.get(&leaf_id).is_some_and(is_finished) {
1026            continue;
1027        }
1028        funds = funds.saturating_add(leaf.value);
1029        if new_leaf_ids.contains(&leaf_id) {
1030            found = found.saturating_add(1);
1031        }
1032    }
1033    (funds, found)
1034}
1035
1036/// Takes each of `leaves` whose recovery or sweep the SDK stored after it read
1037/// `before` out of the stored recoverable funds.
1038async fn take_out_finished_leaves(
1039    storage: &Arc<dyn Storage>,
1040    leaves: &[TreeNode],
1041    before: &HashMap<String, LeafRecovery>,
1042) {
1043    let stored = match leaf_recoveries(storage.as_ref()).await {
1044        Ok(stored) => stored,
1045        Err(e) => {
1046            error!("Failed to read the stored leaf recoveries: {e}");
1047            return;
1048        }
1049    };
1050    let finished = |recoveries: &HashMap<String, LeafRecovery>, leaf: &TreeNode| {
1051        recoveries
1052            .get(&leaf.id.to_string())
1053            .is_some_and(is_finished)
1054    };
1055    let taken_out = leaves
1056        .iter()
1057        .filter(|leaf| finished(&stored, leaf) && !finished(before, leaf))
1058        .map(|leaf| leaf.value)
1059        .fold(0, u64::saturating_add);
1060    if taken_out == 0 {
1061        return;
1062    }
1063    let (funds, _) = recoverable_funds(leaves, &stored, &HashSet::new());
1064    let repository = ObjectCacheRepository::new(storage.clone());
1065    let stored_funds = match repository.fetch_recoverable_funds().await {
1066        Ok(stored_funds) => stored_funds.unwrap_or_default(),
1067        Err(e) => {
1068            error!("Failed to read the recoverable funds: {e}");
1069            return;
1070        }
1071    };
1072    // The SDK adds a leaf to the total during a sync, and takes one out only
1073    // for a stored recovery or sweep. So here the total does not rise, and it
1074    // drops by no more than the leaves just taken out.
1075    let lowered = funds.clamp(stored_funds.saturating_sub(taken_out), stored_funds);
1076    if lowered != stored_funds
1077        && let Err(e) = repository.save_recoverable_funds(lowered).await
1078    {
1079        error!("Failed to store the recoverable funds: {e}");
1080    }
1081}
1082
1083/// The sweep of each leaf that has one in a block among `transactions`. A
1084/// sweep lists the refunds it depends on, and each refund has its leaf's id.
1085fn swept_leaves(transactions: &[RecoveryTransaction]) -> Vec<(String, ChainTransaction)> {
1086    let mut swept = Vec::new();
1087    for sweep in transactions {
1088        let ExitTransactionStatus::Confirmed {
1089            block_height: Some(block_height),
1090        } = sweep.status
1091        else {
1092            continue;
1093        };
1094        if sweep.kind != RecoveryTxKind::Sweep {
1095            continue;
1096        }
1097        let leaf_ids = transactions
1098            .iter()
1099            .filter(|tx| tx.kind == RecoveryTxKind::Refund && sweep.depends_on.contains(&tx.txid))
1100            .filter_map(|tx| tx.node_id.clone());
1101        for leaf_id in leaf_ids {
1102            swept.push((
1103                leaf_id,
1104                ChainTransaction {
1105                    txid: sweep.txid.clone(),
1106                    block_height,
1107                },
1108            ));
1109        }
1110    }
1111    swept
1112}
1113
1114/// The reason `prepare_recover_funds` gives for leaving out a watchtower-exited
1115/// `leaf` with no output to recover, from the `lookup` of that output. `None`
1116/// for a leaf with a recovery in a block, and for a leaf that is not
1117/// watchtower-exited.
1118fn skipped_cooperative_leaf(
1119    leaf: &TreeNode,
1120    stored: Option<&LeafRecovery>,
1121    lookup: Option<&WatchtowerExitLookup>,
1122) -> Option<SkippedLeaf> {
1123    let lookup = lookup?;
1124    if !leaf.status.is_watchtower_exited()
1125        || stored.is_some_and(|stored| stored.watchtower_exit_spend.is_some())
1126    {
1127        return None;
1128    }
1129    let reason = match lookup {
1130        WatchtowerExitLookup::Unrecoverable => SkippedLeafReason::NotRecoverable {
1131            message: "The transaction that took the leaf's funds on-chain pays none of them to \
1132                      the leaf's key"
1133                .to_string(),
1134        },
1135        WatchtowerExitLookup::Pending => SkippedLeafReason::Unverified,
1136        _ => SkippedLeafReason::FundsNotFound,
1137    };
1138    Some(SkippedLeaf {
1139        leaf_id: leaf.id.to_string(),
1140        value_sats: leaf.value,
1141        reason,
1142    })
1143}
1144
1145fn total_value(leaves: &[RecoverFundsLeaf]) -> u64 {
1146    leaves
1147        .iter()
1148        .map(|leaf| leaf.value_sats)
1149        .fold(0, u64::saturating_add)
1150}
1151
1152/// The output a cooperative recovery has as input.
1153fn recovered_output(tx: &RecoveryTransaction) -> Result<OutPoint, SdkError> {
1154    let decoded: Transaction = deserialize_hex(&tx.tx_hex)
1155        .map_err(|e| SdkError::InvalidInput(format!("Invalid transaction: {e}")))?;
1156    decoded
1157        .input
1158        .first()
1159        .map(|input| input.previous_output)
1160        .ok_or_else(|| {
1161            SdkError::InvalidInput(format!("Cooperative recovery {} spends nothing", tx.txid))
1162        })
1163}
1164
1165/// Updates the statuses of the cooperative recoveries `transactions` from the
1166/// chain. Returns the spend in a block of each recovered output, by leaf id.
1167async fn check_cooperative_recoveries(
1168    queries: &mut ChainQueries,
1169    transactions: &mut [RecoveryTransaction],
1170) -> Result<Vec<(String, ChainTransaction)>, SdkError> {
1171    let outputs = transactions
1172        .iter()
1173        .map(recovered_output)
1174        .collect::<Result<Vec<OutPoint>, SdkError>>()?;
1175    // The chain service reports an output of a transaction it does not know
1176    // as unspent, so for an unverified recovery the SDK also checks that the
1177    // output's transaction is in a block.
1178    let unverified_outputs: Vec<ChainQuery> = transactions
1179        .iter()
1180        .zip(&outputs)
1181        .filter(|(tx, _)| tx.status == ExitTransactionStatus::Unverified)
1182        .map(|(_, output)| ChainQuery::TxConfirmed(output.txid))
1183        .collect();
1184    queries
1185        .resolve(|observed| {
1186            let outspends = outputs.iter().copied().map(ChainQuery::Outspend);
1187            let wanted = outspends
1188                .chain(unverified_outputs.iter().cloned())
1189                .collect();
1190            ((), without_result(wanted, observed))
1191        })
1192        .await;
1193    let mut recovered: Vec<(String, ChainTransaction)> = Vec::new();
1194    for (tx, output) in transactions.iter_mut().zip(&outputs) {
1195        let spend = output_spend(queries.observed(), *output);
1196        let output_in_block = tx.status != ExitTransactionStatus::Unverified
1197            || matches!(
1198                result_of(queries.observed(), &ChainQuery::TxConfirmed(output.txid)),
1199                Some(ChainResult::Confirmed {
1200                    confirmed: true,
1201                    ..
1202                })
1203            );
1204        tx.status = cooperative_recovery_status(&spend, output_in_block, tx.status);
1205        if let (Some(leaf_id), Some(spend)) = (&tx.node_id, spend.in_block()) {
1206            recovered.push((leaf_id.clone(), spend));
1207        }
1208    }
1209    Ok(recovered)
1210}
1211
1212/// The status of a cooperative recovery, from the `spend` of its input:
1213/// confirmed once any recovery of that output is in a block, this one or a
1214/// replacement, and ready while the output is in a block and no recovery of it
1215/// is. Without those results from the chain service it stays `status`.
1216fn cooperative_recovery_status(
1217    spend: &OutputSpend,
1218    output_in_block: bool,
1219    status: ExitTransactionStatus,
1220) -> ExitTransactionStatus {
1221    match spend {
1222        OutputSpend::InBlock { block_height, .. } => ExitTransactionStatus::Confirmed {
1223            block_height: *block_height,
1224        },
1225        OutputSpend::Unspent | OutputSpend::InMempool(_) if output_in_block => {
1226            ExitTransactionStatus::Ready
1227        }
1228        OutputSpend::Unspent | OutputSpend::InMempool(_) | OutputSpend::Unknown => status,
1229    }
1230}
1231
1232fn parse_destination(destination: &str, network: Network) -> Result<Address, SdkError> {
1233    destination
1234        .parse::<Address<NetworkUnchecked>>()
1235        .map_err(|e| {
1236            if destination.parse::<SilentPaymentAddress>().is_ok() {
1237                SdkError::InvalidInput(
1238                    "Silent payment addresses are not supported for fund recovery".to_string(),
1239                )
1240            } else {
1241                SdkError::InvalidInput(format!("Invalid destination address: {e}"))
1242            }
1243        })?
1244        .require_network(network.into())
1245        .map_err(|e| SdkError::InvalidInput(format!("Address network mismatch: {e}")))
1246}
1247
1248#[cfg(test)]
1249mod tests {
1250    use bitcoin::{Txid, hashes::Hash};
1251    use spark_wallet::tree_store_tests::create_test_node_with_parent;
1252
1253    use crate::{
1254        StoredWatchtowerExitOutput,
1255        chain::stub::{ChainStub, tx_paying},
1256    };
1257
1258    use super::*;
1259
1260    #[test]
1261    fn a_silent_payment_address_is_no_recovery_destination() {
1262        let result = parse_destination(
1263            "sp1qqgste7k9hx0qftg6qmwlkqtwuy6cycyavzmzj85c6qdfhjdpdjtdgqjuexzk6murw56suy3e0rd2cgqvycxttddwsvgxe2usfpxumr70xc9pkqwv",
1264            Network::Mainnet,
1265        );
1266        assert!(matches!(
1267            result,
1268            Err(SdkError::InvalidInput(message))
1269                if message == "Silent payment addresses are not supported for fund recovery"
1270        ));
1271    }
1272
1273    const LEAF_ID: &str = "00000000-0000-0000-0000-00000000000a";
1274    const OTHER_LEAF_ID: &str = "00000000-0000-0000-0000-00000000000b";
1275
1276    fn stored_leaf(leaf_id: &str) -> LeafRecovery {
1277        LeafRecovery {
1278            leaf_id: leaf_id.to_string(),
1279            chain_checked_at: None,
1280            watchtower_exit_output: None,
1281            watchtower_exit_recoveries: Vec::new(),
1282            watchtower_exit_spend: None,
1283            unilateral_exit_sweep: None,
1284        }
1285    }
1286
1287    fn in_block(txid: &str) -> ChainTransaction {
1288        ChainTransaction {
1289            txid: txid.to_string(),
1290            block_height: 100,
1291        }
1292    }
1293
1294    fn by_leaf_id(exits: Vec<LeafRecovery>) -> HashMap<String, LeafRecovery> {
1295        exits
1296            .into_iter()
1297            .map(|leaf| (leaf.leaf_id.clone(), leaf))
1298            .collect()
1299    }
1300
1301    #[test]
1302    fn a_watchtower_exited_leaf_without_an_output_is_skipped() {
1303        let leaf = create_test_node_with_parent(LEAF_ID, None, TreeNodeStatus::WatchtowerExited);
1304        let skipped = |stored: Option<&LeafRecovery>, lookup: Option<&WatchtowerExitLookup>| {
1305            skipped_cooperative_leaf(&leaf, stored, lookup).map(|skipped| skipped.reason)
1306        };
1307
1308        assert_eq!(
1309            skipped(None, Some(&WatchtowerExitLookup::NotFound)),
1310            Some(SkippedLeafReason::FundsNotFound)
1311        );
1312        assert_eq!(
1313            skipped(
1314                Some(&stored_leaf(LEAF_ID)),
1315                Some(&WatchtowerExitLookup::NotFound)
1316            ),
1317            Some(SkippedLeafReason::FundsNotFound)
1318        );
1319        assert_eq!(
1320            skipped(None, Some(&WatchtowerExitLookup::Pending)),
1321            Some(SkippedLeafReason::Unverified)
1322        );
1323        assert!(matches!(
1324            skipped(None, Some(&WatchtowerExitLookup::Unrecoverable)),
1325            Some(SkippedLeafReason::NotRecoverable { .. })
1326        ));
1327        assert_eq!(skipped(None, None), None, "an output was found");
1328        let recovered = LeafRecovery {
1329            watchtower_exit_spend: Some(in_block("recovery")),
1330            ..stored_leaf(LEAF_ID)
1331        };
1332        assert_eq!(
1333            skipped(Some(&recovered), Some(&WatchtowerExitLookup::NotFound)),
1334            None,
1335            "a finished recovery is not listed"
1336        );
1337
1338        let on_chain = create_test_node_with_parent(LEAF_ID, None, TreeNodeStatus::OnChain);
1339        assert_eq!(
1340            skipped_cooperative_leaf(&on_chain, None, Some(&WatchtowerExitLookup::NotFound)),
1341            None,
1342            "its unilateral exit is quoted"
1343        );
1344    }
1345
1346    #[test]
1347    fn a_new_leaf_is_stored_unless_its_status_leaves_its_funds_open() {
1348        let id = |n: u8| format!("00000000-0000-0000-0000-0000000000{n:02}");
1349        let leaves: Vec<TreeNode> = [
1350            TreeNodeStatus::WatchtowerExited,
1351            TreeNodeStatus::OnChain,
1352            TreeNodeStatus::ParentExited,
1353            TreeNodeStatus::WatchtowerExitRecovered,
1354            TreeNodeStatus::Exited,
1355            TreeNodeStatus::WatchtowerExitRecovered,
1356        ]
1357        .into_iter()
1358        .zip(1u8..)
1359        .map(|(status, n)| create_test_node_with_parent(&id(n), None, status))
1360        .collect();
1361        // The sixth leaf has a stored recovery.
1362        let stored = by_leaf_id(vec![stored_leaf(&id(6))]);
1363
1364        let new = new_leaves(&leaves, &stored);
1365
1366        let ids = |leaves: &[TreeNode]| -> Vec<String> {
1367            leaves.iter().map(|leaf| leaf.id.to_string()).collect()
1368        };
1369        assert_eq!(
1370            new.to_recover
1371                .iter()
1372                .map(|update| update.leaf_id.clone())
1373                .collect::<Vec<_>>(),
1374            vec![id(1), id(2), id(3)]
1375        );
1376        assert!(
1377            new.to_recover
1378                .iter()
1379                .all(|update| update.chain_checked_at.is_none())
1380        );
1381        assert_eq!(ids(&new.recovered), vec![id(4)]);
1382        assert_eq!(ids(&new.exited), vec![id(5)]);
1383    }
1384
1385    #[test]
1386    fn a_leaf_too_small_to_send_out_is_stored_without_a_chain_check() {
1387        let leaf = |id: &str, status, value| {
1388            let mut leaf = create_test_node_with_parent(id, None, status);
1389            leaf.value = value;
1390            leaf
1391        };
1392        let recovered = |value| leaf(LEAF_ID, TreeNodeStatus::WatchtowerExitRecovered, value);
1393        let exited = |value| leaf(OTHER_LEAF_ID, TreeNodeStatus::Exited, value);
1394
1395        // A recovery to a P2WPKH output is 99 vbytes, and the dust limit of
1396        // that output is 294 sats.
1397        assert!(can_be_sent_out(&recovered(393)));
1398        assert!(!can_be_sent_out(&recovered(392)));
1399        // A taproot key-path input is 57.5 vbytes.
1400        assert!(can_be_sent_out(&exited(59)));
1401        assert!(!can_be_sent_out(&exited(58)));
1402        // A leaf in another status gets no chain check to begin with.
1403        assert!(can_be_sent_out(&leaf(
1404            LEAF_ID,
1405            TreeNodeStatus::WatchtowerExited,
1406            1
1407        )));
1408
1409        let new = new_leaves(&[recovered(392), exited(58)], &HashMap::new());
1410        assert!(new.recovered.is_empty() && new.exited.is_empty());
1411        assert_eq!(
1412            new.to_recover
1413                .iter()
1414                .map(|update| update.leaf_id.as_str())
1415                .collect::<Vec<_>>(),
1416            vec![LEAF_ID, OTHER_LEAF_ID]
1417        );
1418        let new = new_leaves(&[recovered(393), exited(59)], &HashMap::new());
1419        assert!(new.to_recover.is_empty());
1420        assert_eq!((new.recovered.len(), new.exited.len()), (1, 1));
1421    }
1422
1423    #[test]
1424    fn the_funds_to_recover_are_those_of_leaves_not_taken_out() {
1425        let leaf = |leaf_id: &str| {
1426            create_test_node_with_parent(leaf_id, None, TreeNodeStatus::WatchtowerExited)
1427        };
1428        let leaves = [leaf(LEAF_ID), leaf(OTHER_LEAF_ID)];
1429        let value = leaves[0].value;
1430        let new_leaf_ids = HashSet::from([LEAF_ID.to_string(), OTHER_LEAF_ID.to_string()]);
1431        let funds = |other: Option<LeafRecovery>, new_leaf_ids: &HashSet<String>| {
1432            let stored = by_leaf_id(std::iter::once(stored_leaf(LEAF_ID)).chain(other).collect());
1433            recoverable_funds(&leaves, &stored, new_leaf_ids)
1434        };
1435
1436        assert_eq!(
1437            funds(Some(stored_leaf(OTHER_LEAF_ID)), &new_leaf_ids),
1438            (value.saturating_mul(2), 2)
1439        );
1440        assert_eq!(
1441            funds(Some(stored_leaf(OTHER_LEAF_ID)), &HashSet::new()),
1442            (value.saturating_mul(2), 0),
1443            "a leaf stored before is not found again"
1444        );
1445        assert_eq!(
1446            funds(None, &HashSet::from([LEAF_ID.to_string()])),
1447            (value.saturating_mul(2), 1),
1448            "a leaf without a stored recovery is counted"
1449        );
1450        let recovered = LeafRecovery {
1451            watchtower_exit_spend: Some(in_block("recovery")),
1452            ..stored_leaf(OTHER_LEAF_ID)
1453        };
1454        assert_eq!(funds(Some(recovered), &new_leaf_ids), (value, 1));
1455        let swept = LeafRecovery {
1456            unilateral_exit_sweep: Some(in_block("sweep")),
1457            ..stored_leaf(OTHER_LEAF_ID)
1458        };
1459        assert_eq!(funds(Some(swept), &new_leaf_ids), (value, 1));
1460    }
1461
1462    fn stored_output() -> StoredWatchtowerExitOutput {
1463        StoredWatchtowerExitOutput {
1464            txid: Txid::from_byte_array([3u8; 32]).to_string(),
1465            vout: 0,
1466            amount_sats: 9_500,
1467            script_pubkey: "5120".to_string(),
1468            block_height: 100,
1469        }
1470    }
1471
1472    #[test]
1473    fn a_leaf_with_a_stored_output_and_no_check_time_is_counted_and_checked_again() {
1474        let leaf =
1475            create_test_node_with_parent(LEAF_ID, None, TreeNodeStatus::WatchtowerExitRecovered);
1476        let leaves = std::slice::from_ref(&leaf);
1477        let incomplete = LeafRecovery {
1478            watchtower_exit_output: Some(stored_output()),
1479            ..stored_leaf(LEAF_ID)
1480        };
1481        let complete = LeafRecovery {
1482            chain_checked_at: Some(1_000),
1483            ..incomplete.clone()
1484        };
1485
1486        let stored = by_leaf_id(vec![incomplete]);
1487        let new = new_leaves(leaves, &stored);
1488        assert_eq!(new.recovered.len(), 1);
1489        assert!(new.to_recover.is_empty() && new.exited.is_empty());
1490        assert_eq!(
1491            recoverable_funds(leaves, &stored, &HashSet::new()).0,
1492            leaf.value
1493        );
1494
1495        let stored = by_leaf_id(vec![complete]);
1496        let new = new_leaves(leaves, &stored);
1497        assert!(new.recovered.is_empty());
1498        assert_eq!(
1499            recoverable_funds(leaves, &stored, &HashSet::new()).0,
1500            leaf.value
1501        );
1502    }
1503
1504    #[test]
1505    fn a_leaf_without_a_looked_up_exit_is_built_on_an_assumed_output_or_fails() {
1506        let leaf = RecoverFundsLeaf {
1507            leaf_id: LEAF_ID.to_string(),
1508            value_sats: 10_000,
1509            method: RecoveryMethod::Cooperative,
1510        };
1511        let assumed = spark_wallet::WatchtowerExitOutput {
1512            leaf_id: create_test_node_with_parent(LEAF_ID, None, TreeNodeStatus::WatchtowerExited)
1513                .id,
1514            outpoint: OutPoint {
1515                txid: Txid::from_byte_array([7u8; 32]),
1516                vout: 1,
1517            },
1518            tx_out: bitcoin::TxOut {
1519                value: Amount::from_sat(9_500),
1520                script_pubkey: ScriptBuf::new(),
1521            },
1522        };
1523        let missing = |lookup: WatchtowerExitLookup, has_assumed: bool| MissingExit {
1524            lookup,
1525            assumed: has_assumed.then(|| assumed.clone()),
1526        };
1527
1528        // The lookup has no result: the SDK builds on the output it assumes.
1529        let pending = missing(WatchtowerExitLookup::Pending, true);
1530        let Unresolved::Exit(exit) = unresolved_exit(&leaf, Some(&pending), None, false).unwrap()
1531        else {
1532            panic!("expected an exit");
1533        };
1534        assert_eq!(exit.output, assumed);
1535
1536        // The lookup shows the leaf's funds elsewhere: the leaf fails, and the
1537        // entry names the output the SDK assumed.
1538        for lookup in [
1539            WatchtowerExitLookup::NotFound,
1540            WatchtowerExitLookup::Unrecoverable,
1541            WatchtowerExitLookup::Unilateral,
1542        ] {
1543            let elsewhere = missing(lookup, true);
1544            let Unresolved::Failed(failure) =
1545                unresolved_exit(&leaf, Some(&elsewhere), None, false).unwrap()
1546            else {
1547                panic!("expected a failure");
1548            };
1549            assert_eq!(failure.output_txid, assumed.outpoint.txid.to_string());
1550            assert_eq!(failure.output_vout, 1);
1551            assert!(matches!(
1552                failure.error,
1553                CooperativeRecoveryError::Generic { .. }
1554            ));
1555        }
1556
1557        // Without any output the prepare response does not match the wallet.
1558        let no_output = missing(WatchtowerExitLookup::Pending, false);
1559        assert!(unresolved_exit(&leaf, Some(&no_output), None, false).is_err());
1560        assert!(unresolved_exit(&leaf, None, None, false).is_err());
1561
1562        // A leaf the wallet no longer lists still has its stored output.
1563        let stored = LeafRecovery {
1564            watchtower_exit_output: Some(stored_output()),
1565            ..stored_leaf(LEAF_ID)
1566        };
1567        assert!(matches!(
1568            unresolved_exit(&leaf, None, Some(&stored), false).unwrap(),
1569            Unresolved::Exit(_)
1570        ));
1571    }
1572
1573    #[test]
1574    fn a_finished_leaf_is_checked_always_when_named_and_else_while_not_settled() {
1575        let stored = by_leaf_id(vec![
1576            LeafRecovery {
1577                watchtower_exit_spend: Some(in_block("recovery")),
1578                ..stored_leaf(LEAF_ID)
1579            },
1580            LeafRecovery {
1581                unilateral_exit_sweep: Some(in_block("sweep")),
1582                ..stored_leaf(OTHER_LEAF_ID)
1583            },
1584        ]);
1585        let txids = |transactions: &[StoredInBlock]| -> HashSet<(String, bool)> {
1586            transactions
1587                .iter()
1588                .map(|tx| (tx.txid.clone(), tx.check_always))
1589                .collect()
1590        };
1591
1592        assert_eq!(
1593            txids(&finished_transactions(&stored, None)),
1594            HashSet::from([
1595                ("recovery".to_string(), false),
1596                ("sweep".to_string(), false)
1597            ])
1598        );
1599        let named = HashSet::from([OTHER_LEAF_ID.to_string()]);
1600        assert_eq!(
1601            txids(&finished_transactions(&stored, Some(&named))),
1602            HashSet::from([("sweep".to_string(), true)])
1603        );
1604    }
1605
1606    #[test]
1607    fn a_named_leaf_with_a_stored_sweep_reaches_the_unilateral_prepare() {
1608        const THIRD_LEAF_ID: &str = "00000000-0000-0000-0000-00000000000c";
1609        let stored = by_leaf_id(vec![
1610            LeafRecovery {
1611                watchtower_exit_spend: Some(in_block("recovery")),
1612                ..stored_leaf(LEAF_ID)
1613            },
1614            LeafRecovery {
1615                unilateral_exit_sweep: Some(in_block("sweep")),
1616                ..stored_leaf(OTHER_LEAF_ID)
1617            },
1618        ]);
1619        let not_unilateral = HashSet::from([LEAF_ID.to_string(), OTHER_LEAF_ID.to_string()]);
1620        let named = vec![
1621            LEAF_ID.to_string(),
1622            OTHER_LEAF_ID.to_string(),
1623            THIRD_LEAF_ID.to_string(),
1624        ];
1625
1626        assert_eq!(
1627            named_for_unilateral(named, &not_unilateral, &stored),
1628            vec![OTHER_LEAF_ID.to_string(), THIRD_LEAF_ID.to_string()]
1629        );
1630    }
1631
1632    #[test]
1633    fn a_leaf_is_not_finished_while_the_chain_shows_its_recovery_in_no_block() {
1634        let stored = || {
1635            by_leaf_id(vec![
1636                LeafRecovery {
1637                    watchtower_exit_spend: Some(in_block("recovery")),
1638                    ..stored_leaf(LEAF_ID)
1639                },
1640                LeafRecovery {
1641                    unilateral_exit_sweep: Some(in_block("sweep")),
1642                    ..stored_leaf(OTHER_LEAF_ID)
1643                },
1644            ])
1645        };
1646
1647        // Without a result the SDK goes by storage.
1648        let (unchanged, moved) = after_finished_checks(stored(), &HashMap::new());
1649        assert_eq!(unchanged, stored());
1650        assert!(moved.is_empty());
1651
1652        let checks = HashMap::from([
1653            ("recovery".to_string(), StoredCheck::NotInBlock),
1654            (
1655                "sweep".to_string(),
1656                StoredCheck::InBlock {
1657                    block_height: Some(104),
1658                },
1659            ),
1660        ]);
1661        let (checked, moved) = after_finished_checks(stored(), &checks);
1662        assert!(!is_finished(&checked[LEAF_ID]));
1663        let sweep = ChainTransaction {
1664            txid: "sweep".to_string(),
1665            block_height: 104,
1666        };
1667        assert_eq!(
1668            checked[OTHER_LEAF_ID].unilateral_exit_sweep,
1669            Some(sweep.clone())
1670        );
1671        assert_eq!(
1672            moved,
1673            vec![UpdateLeafRecovery {
1674                leaf_id: OTHER_LEAF_ID.to_string(),
1675                unilateral_exit_sweep: Some(sweep),
1676                ..Default::default()
1677            }]
1678        );
1679    }
1680
1681    #[test]
1682    fn a_quote_looks_up_no_leaf_whose_recovery_or_sweep_is_stored() {
1683        let id = |n: u8| format!("00000000-0000-0000-0000-0000000000{n:02}");
1684        let leaves: Vec<TreeNode> = (1u8..=4)
1685            .map(|n| {
1686                create_test_node_with_parent(&id(n), None, TreeNodeStatus::WatchtowerExitRecovered)
1687            })
1688            .collect();
1689        let stored = by_leaf_id(vec![
1690            LeafRecovery {
1691                watchtower_exit_spend: Some(in_block("recovery")),
1692                ..stored_leaf(&id(1))
1693            },
1694            LeafRecovery {
1695                unilateral_exit_sweep: Some(in_block("sweep")),
1696                ..stored_leaf(&id(2))
1697            },
1698            LeafRecovery {
1699                watchtower_exit_output: Some(stored_output()),
1700                ..stored_leaf(&id(3))
1701            },
1702        ]);
1703        let ids = |leaves: &[TreeNode]| -> Vec<String> {
1704            leaves.iter().map(|leaf| leaf.id.to_string()).collect()
1705        };
1706
1707        let (finished, open) = finished_and_open(leaves, &stored);
1708
1709        assert_eq!(ids(&finished), vec![id(1), id(2)]);
1710        assert_eq!(ids(&open), vec![id(3), id(4)]);
1711    }
1712
1713    fn unilateral(
1714        kind: RecoveryTxKind,
1715        txid: &str,
1716        node_id: Option<&str>,
1717        depends_on: &[&str],
1718        status: ExitTransactionStatus,
1719    ) -> RecoveryTransaction {
1720        RecoveryTransaction {
1721            kind,
1722            node_id: node_id.map(ToString::to_string),
1723            txid: txid.to_string(),
1724            tx_hex: String::new(),
1725            cpfp_tx_hex: None,
1726            csv_timelock_blocks: None,
1727            depends_on: depends_on.iter().map(ToString::to_string).collect(),
1728            status,
1729        }
1730    }
1731
1732    #[test]
1733    fn a_sweep_in_a_block_swept_the_leaves_of_the_refunds_it_spends() {
1734        let confirmed = ExitTransactionStatus::Confirmed {
1735            block_height: Some(100),
1736        };
1737        let refunds = [
1738            unilateral(
1739                RecoveryTxKind::Refund,
1740                "refund_a",
1741                Some(LEAF_ID),
1742                &[],
1743                confirmed,
1744            ),
1745            unilateral(
1746                RecoveryTxKind::Refund,
1747                "refund_b",
1748                Some(OTHER_LEAF_ID),
1749                &[],
1750                confirmed,
1751            ),
1752        ];
1753        let with_sweep = |sweep: RecoveryTransaction| -> Vec<RecoveryTransaction> {
1754            refunds.iter().cloned().chain([sweep]).collect()
1755        };
1756        let sweep =
1757            |status| unilateral(RecoveryTxKind::Sweep, "sweep", None, &["refund_a"], status);
1758
1759        assert_eq!(
1760            swept_leaves(&with_sweep(sweep(confirmed))),
1761            vec![(LEAF_ID.to_string(), in_block("sweep"))]
1762        );
1763        // Not in a block, or in one the chain service did not name.
1764        for status in [
1765            ExitTransactionStatus::Ready,
1766            ExitTransactionStatus::Confirmed { block_height: None },
1767        ] {
1768            assert!(swept_leaves(&with_sweep(sweep(status))).is_empty());
1769        }
1770        assert!(swept_leaves(&refunds).is_empty());
1771    }
1772
1773    fn watchtower_output() -> OutPoint {
1774        OutPoint {
1775            txid: Txid::from_byte_array([7; 32]),
1776            vout: 1,
1777        }
1778    }
1779
1780    #[test]
1781    fn a_cooperative_recovery_spends_the_output_of_its_first_input() {
1782        let tx = tx_paying(watchtower_output(), 9_500);
1783        let recovery = |tx_hex: String| RecoveryTransaction {
1784            kind: RecoveryTxKind::Cooperative,
1785            node_id: Some(LEAF_ID.to_string()),
1786            txid: tx.compute_txid().to_string(),
1787            tx_hex,
1788            cpfp_tx_hex: None,
1789            csv_timelock_blocks: None,
1790            depends_on: Vec::new(),
1791            status: ExitTransactionStatus::Ready,
1792        };
1793
1794        assert_eq!(
1795            recovered_output(&recovery(serialize_hex(&tx))).unwrap(),
1796            watchtower_output()
1797        );
1798        assert!(recovered_output(&recovery("00".to_string())).is_err());
1799    }
1800
1801    #[test]
1802    fn a_cooperative_recovery_is_confirmed_once_any_recovery_of_its_output_is() {
1803        let confirmed = ExitTransactionStatus::Confirmed {
1804            block_height: Some(120),
1805        };
1806        let in_block = OutputSpend::InBlock {
1807            txid: Txid::from_byte_array([8; 32]),
1808            block_height: Some(120),
1809        };
1810
1811        assert_eq!(
1812            cooperative_recovery_status(&in_block, true, ExitTransactionStatus::Ready),
1813            confirmed
1814        );
1815        // Not in a block, whatever the status was before.
1816        let not_in_block = [
1817            OutputSpend::Unspent,
1818            OutputSpend::InMempool(Txid::from_byte_array([8; 32])),
1819        ];
1820        for spend in &not_in_block {
1821            assert_eq!(
1822                cooperative_recovery_status(spend, true, confirmed),
1823                ExitTransactionStatus::Ready
1824            );
1825        }
1826        // Without a result the status stays as it was.
1827        assert_eq!(
1828            cooperative_recovery_status(&OutputSpend::Unknown, true, confirmed),
1829            confirmed
1830        );
1831        // An unverified recovery is ready only once its output is in a block.
1832        let unverified = ExitTransactionStatus::Unverified;
1833        for spend in &not_in_block {
1834            assert_eq!(
1835                cooperative_recovery_status(spend, false, unverified),
1836                unverified
1837            );
1838        }
1839        assert_eq!(
1840            cooperative_recovery_status(&in_block, false, unverified),
1841            confirmed
1842        );
1843    }
1844
1845    fn confirmed_at(block_height: u32) -> RecoveryTransaction {
1846        RecoveryTransaction {
1847            kind: RecoveryTxKind::Sweep,
1848            node_id: None,
1849            txid: Txid::from_byte_array([8; 32]).to_string(),
1850            tx_hex: String::new(),
1851            cpfp_tx_hex: None,
1852            csv_timelock_blocks: None,
1853            depends_on: Vec::new(),
1854            status: ExitTransactionStatus::Confirmed {
1855                block_height: Some(block_height),
1856            },
1857        }
1858    }
1859
1860    /// The queries of a call in which the chain service failed a request.
1861    async fn queries_after_a_failure(tip: u32) -> ChainQueries {
1862        let chain = ChainStub {
1863            tip: Some(tip),
1864            ..Default::default()
1865        };
1866        let mut queries = ChainQueries::new(Arc::new(chain));
1867        let unknown = ChainQuery::TxConfirmed(Txid::from_byte_array([9; 32]));
1868        queries
1869            .resolve(|observed| {
1870                let pending = if observed.is_empty() {
1871                    vec![unknown.clone()]
1872                } else {
1873                    Vec::new()
1874                };
1875                ((), pending)
1876            })
1877            .await;
1878        assert!(queries.failed());
1879        queries
1880    }
1881
1882    #[macros::async_test_all]
1883    async fn after_a_failed_request_a_recovery_is_done_once_settled() {
1884        let mut queries = queries_after_a_failure(110).await;
1885
1886        assert!(
1887            recovery_done(&[confirmed_at(100)], &mut queries).await,
1888            "11 blocks deep"
1889        );
1890        assert!(
1891            !recovery_done(&[confirmed_at(100), confirmed_at(108)], &mut queries).await,
1892            "the latest is 3 blocks deep"
1893        );
1894    }
1895
1896    #[cfg(not(target_family = "wasm"))]
1897    mod stored_funds {
1898        use std::sync::atomic::Ordering;
1899
1900        use crate::{
1901            persist::sqlite::SqliteStorage, sdk::watchtower_exit::store_watchtower_exit_lookups,
1902        };
1903
1904        use super::*;
1905
1906        fn temp_storage() -> Arc<dyn Storage> {
1907            let mut dir = std::env::temp_dir();
1908            dir.push(format!("breez-recoverable-funds-{}", uuid::Uuid::new_v4()));
1909            Arc::new(SqliteStorage::new(&dir).expect("create sqlite storage"))
1910        }
1911
1912        fn leaf(leaf_id: &str, status: TreeNodeStatus) -> TreeNode {
1913            create_test_node_with_parent(leaf_id, None, status)
1914        }
1915
1916        /// Stores a recovery for each of `leaves` and their value as the funds
1917        /// to recover, as the SDK does in a sync.
1918        async fn store_leaves_to_recover(storage: &Arc<dyn Storage>, leaves: &[TreeNode]) {
1919            for leaf in leaves {
1920                let stored = UpdateLeafRecovery {
1921                    leaf_id: leaf.id.to_string(),
1922                    ..Default::default()
1923                };
1924                storage.update_leaf_recovery(stored).await.unwrap();
1925            }
1926            let (funds, _) = recoverable_funds(leaves, &HashMap::new(), &HashSet::new());
1927            ObjectCacheRepository::new(storage.clone())
1928                .save_recoverable_funds(funds)
1929                .await
1930                .unwrap();
1931        }
1932
1933        async fn stored(storage: &Arc<dyn Storage>) -> HashMap<String, LeafRecovery> {
1934            leaf_recoveries(storage.as_ref()).await.unwrap()
1935        }
1936
1937        async fn stored_funds(storage: &Arc<dyn Storage>) -> u64 {
1938            ObjectCacheRepository::new(storage.clone())
1939                .fetch_recoverable_funds()
1940                .await
1941                .unwrap()
1942                .unwrap_or_default()
1943        }
1944
1945        /// Stores a sweep in a block for `leaf` and takes the leaf out of the
1946        /// stored funds of a wallet that lists `leaves`.
1947        async fn sweep_and_take_out(
1948            storage: &Arc<dyn Storage>,
1949            leaf: &TreeNode,
1950            leaves: &[TreeNode],
1951        ) {
1952            let before = stored(storage).await;
1953            let swept = vec![(leaf.id.to_string(), in_block("sweep"))];
1954            store_finished(storage.as_ref(), &before, Vec::new(), swept).await;
1955            take_out_finished_leaves(storage, leaves, &before).await;
1956        }
1957
1958        fn kept(
1959            kind: RecoveryTxKind,
1960            tx: &Transaction,
1961            node_id: Option<&str>,
1962            depends_on: &[&Transaction],
1963        ) -> RecoveryTransaction {
1964            RecoveryTransaction {
1965                kind,
1966                node_id: node_id.map(ToString::to_string),
1967                txid: tx.compute_txid().to_string(),
1968                tx_hex: serialize_hex(tx),
1969                cpfp_tx_hex: None,
1970                csv_timelock_blocks: None,
1971                depends_on: depends_on
1972                    .iter()
1973                    .map(|tx| tx.compute_txid().to_string())
1974                    .collect(),
1975                status: ExitTransactionStatus::Ready,
1976            }
1977        }
1978
1979        /// A chain service that shows each of `spends` in a block: the
1980        /// outpoint, its spender, and the height of the spender's block.
1981        fn chain_with(spends: &[(OutPoint, &Transaction, u32)]) -> Arc<ChainStub> {
1982            let outspends = spends
1983                .iter()
1984                .map(|(outpoint, spender, block_height)| {
1985                    let spender = spender.compute_txid().to_string();
1986                    (
1987                        (outpoint.txid.to_string(), outpoint.vout),
1988                        ChainStub::spent(&spender, true, Some(*block_height)),
1989                    )
1990                })
1991                .collect();
1992            Arc::new(ChainStub {
1993                outspends,
1994                ..Default::default()
1995            })
1996        }
1997
1998        #[tokio::test]
1999        async fn check_takes_a_recovered_leaf_out_of_the_funds_to_recover() {
2000            let recovered = leaf(LEAF_ID, TreeNodeStatus::WatchtowerExitRecovered);
2001            let open = leaf(OTHER_LEAF_ID, TreeNodeStatus::WatchtowerExited);
2002            let leaves = [recovered, open.clone()];
2003            let storage = temp_storage();
2004            store_leaves_to_recover(&storage, &leaves).await;
2005            let before = stored(&storage).await;
2006            let recovery = tx_paying(watchtower_output(), 9_500);
2007            let mut transactions = vec![kept(
2008                RecoveryTxKind::Cooperative,
2009                &recovery,
2010                Some(LEAF_ID),
2011                &[],
2012            )];
2013            let chain = chain_with(&[(watchtower_output(), &recovery, 120)]);
2014            let mut queries = ChainQueries::new(chain.clone());
2015
2016            let spends = check_cooperative_recoveries(&mut queries, &mut transactions)
2017                .await
2018                .unwrap();
2019            store_finished(storage.as_ref(), &before, spends, Vec::new()).await;
2020            take_out_finished_leaves(&storage, &leaves, &before).await;
2021
2022            assert_eq!(stored_funds(&storage).await, open.value);
2023            assert_eq!(
2024                transactions[0].status,
2025                ExitTransactionStatus::Confirmed {
2026                    block_height: Some(120)
2027                }
2028            );
2029            assert_eq!(chain.requests.load(Ordering::SeqCst), 1);
2030        }
2031
2032        #[tokio::test]
2033        async fn check_takes_a_swept_leaf_out_of_the_funds_to_recover() {
2034            let exited = leaf(LEAF_ID, TreeNodeStatus::Exited);
2035            let open = leaf(OTHER_LEAF_ID, TreeNodeStatus::OnChain);
2036            let leaves = [exited, open.clone()];
2037            let storage = temp_storage();
2038            store_leaves_to_recover(&storage, &leaves).await;
2039            let before = stored(&storage).await;
2040            let node_output = OutPoint {
2041                txid: Txid::from_byte_array([5; 32]),
2042                vout: 0,
2043            };
2044            let refund = tx_paying(node_output, 900);
2045            let refund_output = OutPoint {
2046                txid: refund.compute_txid(),
2047                vout: 0,
2048            };
2049            let sweep = tx_paying(refund_output, 800);
2050            let mut transactions = vec![
2051                kept(RecoveryTxKind::Refund, &refund, Some(LEAF_ID), &[]),
2052                kept(RecoveryTxKind::Sweep, &sweep, None, &[&refund]),
2053            ];
2054            let chain = chain_with(&[(node_output, &refund, 100), (refund_output, &sweep, 101)]);
2055            let mut queries = ChainQueries::new(chain.clone());
2056
2057            let diverged = check_recovery_transactions(&mut queries, &mut transactions)
2058                .await
2059                .unwrap();
2060            let swept = swept_leaves(&transactions);
2061            store_finished(storage.as_ref(), &before, Vec::new(), swept).await;
2062            take_out_finished_leaves(&storage, &leaves, &before).await;
2063
2064            assert!(!diverged);
2065            assert_eq!(stored_funds(&storage).await, open.value);
2066            assert_eq!(chain.requests.load(Ordering::SeqCst), 2);
2067        }
2068
2069        #[tokio::test]
2070        async fn prepare_takes_a_recovered_leaf_out_of_the_funds_to_recover() {
2071            let recovered = leaf(LEAF_ID, TreeNodeStatus::WatchtowerExitRecovered);
2072            let open = leaf(OTHER_LEAF_ID, TreeNodeStatus::WatchtowerExited);
2073            let leaves = [recovered.clone(), open.clone()];
2074            let storage = temp_storage();
2075            store_leaves_to_recover(&storage, &leaves).await;
2076            let output = stored_output();
2077            let outpoint = OutPoint {
2078                txid: output.txid.parse().unwrap(),
2079                vout: output.vout,
2080            };
2081            let found_output = UpdateLeafRecovery {
2082                leaf_id: LEAF_ID.to_string(),
2083                chain_checked_at: Some(900),
2084                watchtower_exit_output: Some(output),
2085                ..Default::default()
2086            };
2087            storage.update_leaf_recovery(found_output).await.unwrap();
2088            let before = stored(&storage).await;
2089            let recovery = tx_paying(outpoint, 9_000);
2090            let chain = chain_with(&[(outpoint, &recovery, 101)]);
2091            let mut queries = ChainQueries::new(chain.clone());
2092
2093            let found = store_watchtower_exit_lookups(
2094                std::slice::from_ref(&recovered),
2095                &HashMap::new(),
2096                true,
2097                &before,
2098                &HashSet::from([LEAF_ID.to_string()]),
2099                &mut queries,
2100                storage.as_ref(),
2101            )
2102            .await
2103            .unwrap();
2104            take_out_finished_leaves(&storage, &leaves, &before).await;
2105
2106            assert!(found.exits[LEAF_ID].recovered);
2107            assert_eq!(stored_funds(&storage).await, open.value);
2108            assert_eq!(chain.requests.load(Ordering::SeqCst), 1);
2109        }
2110
2111        #[tokio::test]
2112        async fn the_sdk_adds_no_leaf_to_the_funds_to_recover_outside_a_sync() {
2113            let exited = leaf(LEAF_ID, TreeNodeStatus::Exited);
2114            let mut new = leaf(OTHER_LEAF_ID, TreeNodeStatus::OnChain);
2115            new.value = exited.value.saturating_mul(3);
2116            let storage = temp_storage();
2117            store_leaves_to_recover(&storage, std::slice::from_ref(&exited)).await;
2118
2119            sweep_and_take_out(&storage, &exited, &[exited.clone(), new]).await;
2120
2121            assert_eq!(stored_funds(&storage).await, exited.value);
2122        }
2123
2124        #[tokio::test]
2125        async fn a_leaf_the_wallet_no_longer_lists_stays_in_the_funds_to_recover() {
2126            let exited = leaf(LEAF_ID, TreeNodeStatus::Exited);
2127            let unlisted = leaf(OTHER_LEAF_ID, TreeNodeStatus::OnChain);
2128            let storage = temp_storage();
2129            store_leaves_to_recover(&storage, &[exited.clone(), unlisted.clone()]).await;
2130
2131            sweep_and_take_out(&storage, &exited, std::slice::from_ref(&exited)).await;
2132
2133            assert_eq!(stored_funds(&storage).await, unlisted.value);
2134        }
2135
2136        #[tokio::test]
2137        async fn the_funds_to_recover_stay_when_a_swept_leaf_was_not_among_them() {
2138            let exited = leaf(LEAF_ID, TreeNodeStatus::Exited);
2139            let open = leaf(OTHER_LEAF_ID, TreeNodeStatus::OnChain);
2140            let storage = temp_storage();
2141            store_leaves_to_recover(&storage, std::slice::from_ref(&open)).await;
2142
2143            sweep_and_take_out(&storage, &exited, &[exited.clone(), open.clone()]).await;
2144
2145            assert_eq!(stored_funds(&storage).await, open.value);
2146        }
2147
2148        #[tokio::test]
2149        async fn the_funds_to_recover_stay_for_a_leaf_swept_before_the_call() {
2150            let exited = leaf(LEAF_ID, TreeNodeStatus::Exited);
2151            let unlisted = leaf(OTHER_LEAF_ID, TreeNodeStatus::OnChain);
2152            let storage = temp_storage();
2153            store_leaves_to_recover(&storage, std::slice::from_ref(&unlisted)).await;
2154            let swept = vec![(LEAF_ID.to_string(), in_block("sweep"))];
2155            store_finished(storage.as_ref(), &HashMap::new(), Vec::new(), swept).await;
2156            let before = stored(&storage).await;
2157
2158            take_out_finished_leaves(&storage, std::slice::from_ref(&exited), &before).await;
2159
2160            assert_eq!(stored_funds(&storage).await, unlisted.value);
2161        }
2162
2163        #[tokio::test]
2164        async fn the_funds_to_recover_stay_while_the_wallet_lists_no_leaf() {
2165            let exited = leaf(LEAF_ID, TreeNodeStatus::Exited);
2166            let storage = temp_storage();
2167            store_leaves_to_recover(&storage, std::slice::from_ref(&exited)).await;
2168
2169            sweep_and_take_out(&storage, &exited, &[]).await;
2170
2171            assert_eq!(stored_funds(&storage).await, exited.value);
2172        }
2173    }
2174}