Skip to main content

breez_sdk_spark/sdk/
unilateral_exit.rs

1use std::collections::{HashMap, HashSet};
2use std::str::FromStr;
3
4use bitcoin::{
5    Address, Amount, CompressedPublicKey, OutPoint, ScriptBuf, Transaction, TxOut, Txid,
6    XOnlyPublicKey,
7    consensus::encode::{deserialize_hex, serialize_hex},
8    secp256k1::PublicKey,
9};
10
11use spark_wallet::{
12    ConfirmedExitNode as WalletConfirmedExitNode, CpfpInput,
13    ExitChainState as WalletExitChainState, ExitCheck, ExitCheckInput,
14    ExitNodeConfirmation as WalletExitNodeConfirmation, ExitRefund as WalletExitRefund,
15    ExitRefundState as WalletExitRefundState, ExitTxKind, ExitTxStatus, Observation, RefundSweep,
16    RefundSweepLookup, TreeNode, TreeNodeId, UnilateralExitBuild, UnilateralExitSkipReason,
17    UnilateralExitSkippedLeaf, check_exit_chain, is_ephemeral_anchor_output, leaf_refund_addresses,
18    scan_exit_chain, scan_funding, scan_refund_sweeps,
19};
20
21use tracing::{debug, trace};
22
23use crate::{
24    ChainTransaction, LeafRecovery, Storage, UpdateLeafRecovery,
25    chain::BitcoinChainService,
26    error::SdkError,
27    models::{
28        ConfirmedExitNode, CpfpFundingKind, CpfpFundingStrategy, CpfpInput as ModelCpfpInput,
29        ExitChainState as ModelExitChainState, ExitNodeConfirmation, ExitRefund, ExitRefundState,
30        ExitTransactionStatus, PerBranchFunding, RecoverFundsLeaf, RecoveryFunding, RecoveryMethod,
31        RecoveryTransaction, RecoveryTxKind, SkippedLeaf, SkippedLeafReason,
32    },
33    signer::CpfpSigner,
34    utils::time::now_secs,
35};
36
37use super::{
38    BreezSdk,
39    chain_queries::{ChainQueries, batches},
40    recover_funds::store_checks,
41};
42
43#[derive(Default)]
44pub(super) struct UnilateralQuote {
45    pub(super) leaves: Vec<RecoverFundsLeaf>,
46    pub(super) skipped: Vec<SkippedLeaf>,
47    pub(super) recoverable_value_sats: u64,
48    pub(super) total_fee_sats: u64,
49    pub(super) cpfp_fee_sats: u64,
50    pub(super) fanout_fee_sats: u64,
51    pub(super) refund_fee_sats: u64,
52    pub(super) sweep_fee_sats: u64,
53    pub(super) funding: Option<RecoveryFunding>,
54    pub(super) exit_chain_state: ModelExitChainState,
55}
56
57#[derive(Default)]
58pub(super) struct UnilateralBuild {
59    pub(super) leaves: Vec<RecoverFundsLeaf>,
60    pub(super) recoverable_value_sats: u64,
61    pub(super) total_fee_sats: u64,
62    pub(super) cpfp_fee_sats: u64,
63    pub(super) fanout_fee_sats: u64,
64    pub(super) refund_fee_sats: u64,
65    pub(super) sweep_fee_sats: u64,
66    pub(super) transactions: Vec<RecoveryTransaction>,
67}
68
69impl BreezSdk {
70    /// Quotes a unilateral exit of the selected leaves: which would exit, the
71    /// exact fee for the funding kind, and how much to fund. A leaf whose exit
72    /// already finished is left out, and recorded as finished.
73    #[allow(clippy::too_many_arguments)]
74    pub(super) async fn quote_unilateral_exit(
75        &self,
76        destination: &Address,
77        fee_rate_sat_per_vbyte: u64,
78        funding_kind: Option<&CpfpFundingKind>,
79        funding_strategy: CpfpFundingStrategy,
80        selection: spark_wallet::ExitLeafSelection,
81        not_unilateral: &HashSet<String>,
82        stored: &HashMap<String, LeafRecovery>,
83        queries: &mut ChainQueries,
84    ) -> Result<UnilateralQuote, SdkError> {
85        let dest_script_len = destination.script_pubkey().len();
86        // Without a funding kind no CPFP child is quoted, so these are not used.
87        let (input_weight, output_script) = match funding_kind {
88            Some(kind) => funding_kind_params(kind)?,
89            None => (0, ScriptBuf::new()),
90        };
91        let mut context = self
92            .spark_wallet
93            .load_selected_exit_context(selection)
94            .await?;
95        let swept = leaves_with_stored_sweep(&context.leaf_ids, stored);
96        // The chain walk below drops them as well, but only while the chain can
97        // be read.
98        context
99            .leaf_ids
100            .retain(|leaf_id| !not_unilateral.contains(&leaf_id.to_string()));
101
102        // Ask the chain what these leaves have already done before pricing them,
103        // so a leaf part-way out is quoted on the work it has left rather than on
104        // a fresh exit, and is not dropped as unprofitable over work already
105        // paid for. Every lookup the tree needs happens here.
106        let refund_addresses = leaf_refund_addresses(
107            &context.tree_nodes,
108            &context.leaf_ids,
109            self.config.network.into(),
110        );
111        let (exit_chain_state, sweeps) = resolve_exit_chain_state(
112            queries,
113            &context.tree_nodes,
114            &context.leaf_ids,
115            &refund_addresses,
116        )
117        .await;
118        self.store_sweeps(&sweeps, stored).await;
119        // A leaf whose exit already finished is not exited again, whether named or
120        // not; `exit_chain_state` still reports it as swept or stopped.
121        let before = context.leaf_ids.clone();
122        context.drop_finished_leaves(&exit_chain_state);
123        let mut skipped = skipped_dropped_leaves(&before, &context, &exit_chain_state, stored);
124
125        let quote = self.spark_wallet.quote_unilateral_exit(
126            &context,
127            sat_per_kw_from_vbyte(fee_rate_sat_per_vbyte),
128            input_weight,
129            output_script.len(),
130            output_script.minimal_non_dust().to_sat(),
131            funding_strategy.into(),
132            dest_script_len,
133            &exit_chain_state,
134        )?;
135        skipped.extend(quote.skipped_leaves.iter().map(skipped_by_planner));
136        // No selected leaves is not an error: return an empty quote.
137        let recoverable_value_sats = quote
138            .selected_leaves
139            .iter()
140            .map(|l| l.value)
141            .fold(0u64, u64::saturating_add);
142        let leaves = quote
143            .selected_leaves
144            .iter()
145            .map(|l| RecoverFundsLeaf {
146                leaf_id: l.id.to_string(),
147                value_sats: l.value,
148                method: RecoveryMethod::Unilateral,
149            })
150            .collect();
151        let per_branch: Vec<PerBranchFunding> = quote
152            .per_branch_funding
153            .into_iter()
154            .map(|(id, funding_sats)| PerBranchFunding {
155                leaf_id: id.to_string(),
156                funding_sats,
157            })
158            .collect();
159        if funding_kind.is_none() && !per_branch.is_empty() {
160            return Err(SdkError::InvalidInput(
161                "A funding kind is needed: a transaction of a unilateral exit in the selection \
162                 has a CPFP child"
163                    .to_string(),
164            ));
165        }
166
167        debug!(
168            selected_leaves = quote.selected_leaves.len(),
169            recoverable_value_sats,
170            total_fee_sat = quote.total_fee_sat,
171            cpfp_fee_sat = quote.cpfp_fee_sat,
172            fanout_fee_sat = quote.fanout_fee_sat,
173            refund_fee_sat = quote.refund_fee_sat,
174            sweep_fee_sat = quote.sweep_fee_sat,
175            single_utxo_funding_sat = quote.single_utxo_funding_sat,
176            branches = per_branch.len(),
177            ?funding_strategy,
178            "quote_unilateral_exit: quote ready"
179        );
180
181        Ok(UnilateralQuote {
182            leaves,
183            skipped,
184            recoverable_value_sats,
185            total_fee_sats: quote.total_fee_sat,
186            cpfp_fee_sats: quote.cpfp_fee_sat,
187            fanout_fee_sats: quote.fanout_fee_sat,
188            refund_fee_sats: quote.refund_fee_sat,
189            sweep_fee_sats: quote.sweep_fee_sat,
190            funding: (!per_branch.is_empty()).then_some(RecoveryFunding {
191                single_utxo_sats: quote.single_utxo_funding_sat,
192                per_branch,
193                strategy: funding_strategy,
194            }),
195            exit_chain_state: exit_chain_state_model(with_swept_refunds(exit_chain_state, swept)),
196        })
197    }
198
199    /// Builds and signs a unilateral exit of exactly `leaf_ids` from the actual
200    /// funding UTXOs, in topological broadcast order, without broadcasting.
201    ///
202    /// It reads on-chain state first: an already-confirmed fan-out or CPFP node
203    /// is not rebuilt, and a leaf refund already on-chain (recognized by the
204    /// leaf's refund address, so any refund variant counts) is swept directly.
205    /// Re-running after partial progress therefore resumes rather than restarts.
206    #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
207    pub(super) async fn build_unilateral_exit(
208        &self,
209        destination: &Address,
210        leaf_ids: Vec<TreeNodeId>,
211        fee_rate_sat_per_vbyte: u64,
212        funding_inputs: Vec<ModelCpfpInput>,
213        single_utxo_funding_sats: u64,
214        funding_strategy: CpfpFundingStrategy,
215        exit_chain_state: &ModelExitChainState,
216        signer: Option<&dyn CpfpSigner>,
217        queries: &mut ChainQueries,
218    ) -> Result<UnilateralBuild, SdkError> {
219        let btc_network: bitcoin::Network = self.config.network.into();
220        let dest_script_len = destination.script_pubkey().len();
221
222        let supplied = funding_inputs
223            .into_iter()
224            .map(|i| i.into_funding_input(btc_network))
225            .collect::<Result<Vec<_>, SdkError>>()?;
226        let supplied_any = !supplied.is_empty();
227
228        // A prior run spends the funding it was given, so what the caller hands
229        // back may name outputs that are gone. Follow them to what they became
230        // before planning, so the plan is made over what can actually be spent.
231        let funding_inputs = resolve_funding(queries, supplied).await;
232        // Followed to nothing: a previous run spent all of it. That is a
233        // shortfall, not a malformed request.
234        if supplied_any && funding_inputs.is_empty() {
235            return Err(SdkError::insufficient_cpfp_funds(single_utxo_funding_sats));
236        }
237        let fee_rate_sat_per_kw = sat_per_kw_from_vbyte(fee_rate_sat_per_vbyte);
238        let chain_state = exit_chain_state_from_model(exit_chain_state)?;
239        let context = self
240            .spark_wallet
241            .load_exit_context(spark_wallet::ExitLeafSelection::Specific(leaf_ids))
242            .await?;
243        let prepared_exit = self.spark_wallet.prepare_unilateral_exit_plan(
244            &context,
245            fee_rate_sat_per_kw,
246            funding_inputs,
247            funding_strategy.into(),
248            dest_script_len,
249            &chain_state,
250        )?;
251        if prepared_exit.selected_leaves.is_empty() {
252            debug!("build_unilateral_exit: plan selected no leaves, returning empty result");
253            return Ok(UnilateralBuild::default());
254        }
255        trace!(
256            selected_leaves = prepared_exit.selected_leaves.len(),
257            tree_nodes = prepared_exit.tree_nodes.len(),
258            has_fan_out = prepared_exit.fan_out_psbt.is_some(),
259            "build_unilateral_exit: plan prepared"
260        );
261
262        let leaves: Vec<RecoverFundsLeaf> = prepared_exit
263            .selected_leaves
264            .iter()
265            .map(|l| RecoverFundsLeaf {
266                leaf_id: l.id.to_string(),
267                value_sats: l.value,
268                method: RecoveryMethod::Unilateral,
269            })
270            .collect();
271
272        let build = self
273            .spark_wallet
274            .build_unilateral_exit(&prepared_exit, &chain_state, fee_rate_sat_per_kw)
275            .await?;
276        let recoverable_value_sats = build.recoverable_value_sat;
277        let cpfp_fee_sats = build.cpfp_fee_sat;
278        let fanout_fee_sats = build.fanout_fee_sat;
279        let refund_fee_sats = build.refund_fee_sat;
280        let build_fee_sats = cpfp_fee_sats
281            .saturating_add(fanout_fee_sats)
282            .saturating_add(refund_fee_sats);
283        // Captured before the loop below consumes `build.branches`.
284        let sweep_status = sweep_initial_status(&build);
285        // The child of a refund without an anchor goes out with its refund, so
286        // the sweep of the child's output waits on the refund.
287        let refund_of_child: HashMap<Txid, Txid> = build
288            .branches
289            .iter()
290            .flat_map(|branch| &branch.txs)
291            .filter_map(|tx| Some((tx.cpfp_tx.as_ref()?.compute_txid(), tx.txid)))
292            .collect();
293        debug!(
294            has_fan_out = build.fan_out.is_some(),
295            branches = build.branches.len(),
296            refund_outputs = build.refund_outputs.len(),
297            cpfp_change_inputs = build.cpfp_change_inputs.len(),
298            recoverable_value_sats,
299            cpfp_fee_sats,
300            fanout_fee_sats,
301            refund_fee_sats,
302            "build_unilateral_exit: build assembled, signing"
303        );
304
305        let mut transactions: Vec<RecoveryTransaction> = Vec::new();
306
307        if let Some(fan_out) = build.fan_out {
308            trace!(
309                txid = %fan_out.txid,
310                status = ?fan_out.status,
311                needs_signing = fan_out.to_sign.is_some(),
312                "build_unilateral_exit: fan-out"
313            );
314            let tx_hex = match fan_out.to_sign {
315                Some(psbt) => sign_psbt_via(psbt, signer).await?,
316                None => serialize_hex(&fan_out.base_tx),
317            };
318            transactions.push(RecoveryTransaction {
319                kind: RecoveryTxKind::FanOut,
320                node_id: None,
321                txid: fan_out.txid.to_string(),
322                tx_hex,
323                cpfp_tx_hex: None,
324                csv_timelock_blocks: fan_out.csv_timelock_blocks,
325                depends_on: fan_out.depends_on.iter().map(ToString::to_string).collect(),
326                status: initial_status(fan_out.status),
327            });
328        }
329
330        for branch in build.branches {
331            trace!(leaf_id = %branch.leaf_id, txs = branch.txs.len(), "build_unilateral_exit: branch");
332            for tx in branch.txs {
333                let kind = match tx.kind {
334                    ExitTxKind::Node => RecoveryTxKind::Node,
335                    ExitTxKind::Refund => RecoveryTxKind::Refund,
336                    // The fan-out is emitted above, never inside a branch.
337                    ExitTxKind::FanOut => continue,
338                };
339                trace!(
340                    ?kind,
341                    node_id = ?tx.node_id.as_ref().map(ToString::to_string),
342                    txid = %tx.txid,
343                    status = ?tx.status,
344                    needs_cpfp_child = tx.to_sign.is_some(),
345                    csv_timelock_blocks = ?tx.csv_timelock_blocks,
346                    depends_on = tx.depends_on.len(),
347                    "build_unilateral_exit: exit tx"
348                );
349                let cpfp_tx_hex = match (tx.to_sign, tx.cpfp_tx) {
350                    (Some(child), _) => Some(sign_psbt_via(child, signer).await?),
351                    (None, Some(cpfp_tx)) => Some(serialize_hex(&cpfp_tx)),
352                    (None, None) => None,
353                };
354                transactions.push(RecoveryTransaction {
355                    kind,
356                    node_id: tx.node_id.map(|id| id.to_string()),
357                    txid: tx.txid.to_string(),
358                    tx_hex: serialize_hex(&tx.base_tx),
359                    cpfp_tx_hex,
360                    csv_timelock_blocks: tx.csv_timelock_blocks,
361                    depends_on: tx.depends_on.iter().map(ToString::to_string).collect(),
362                    status: initial_status(tx.status),
363                });
364            }
365        }
366
367        // A sweep over zero inputs would error: return without one when no refund
368        // is on-chain yet. A later run sweeps any refund that surfaces.
369        if build.refund_outputs.is_empty() {
370            resolve_statuses(queries, &mut transactions).await?;
371            debug!("build_unilateral_exit: no refund outputs to sweep, omitting the sweep");
372            return Ok(UnilateralBuild {
373                leaves,
374                recoverable_value_sats,
375                total_fee_sats: build_fee_sats,
376                cpfp_fee_sats,
377                fanout_fee_sats,
378                refund_fee_sats,
379                sweep_fee_sats: 0,
380                transactions,
381            });
382        }
383
384        let refund_txids: Vec<String> = build
385            .refund_outputs
386            .iter()
387            .map(|r| {
388                refund_of_child
389                    .get(&r.outpoint.txid)
390                    .unwrap_or(&r.outpoint.txid)
391                    .to_string()
392            })
393            .collect();
394        let sweep_psbt = self
395            .spark_wallet
396            .create_refund_sweep_transaction(
397                build.refund_outputs,
398                build.cpfp_change_inputs,
399                destination.clone(),
400                fee_rate_sat_per_kw,
401            )
402            .await?;
403        let sweep_fee_sats = sweep_fee(&sweep_psbt);
404        let total_fee_sats = build_fee_sats.saturating_add(sweep_fee_sats);
405        let sweep_txid = sweep_psbt.unsigned_tx.compute_txid();
406        trace!(
407            txid = %sweep_txid,
408            status = ?sweep_status,
409            refund_inputs = refund_txids.len(),
410            "build_unilateral_exit: sweep"
411        );
412        let sweep_tx_hex = finalize_sweep(sweep_psbt, signer).await?;
413        transactions.push(RecoveryTransaction {
414            kind: RecoveryTxKind::Sweep,
415            node_id: None,
416            txid: sweep_txid.to_string(),
417            tx_hex: sweep_tx_hex,
418            cpfp_tx_hex: None,
419            csv_timelock_blocks: None,
420            depends_on: refund_txids,
421            status: sweep_status,
422        });
423
424        resolve_statuses(queries, &mut transactions).await?;
425        debug!(
426            transactions = transactions.len(),
427            recoverable_value_sats,
428            total_fee_sats,
429            sweep_fee_sats,
430            "build_unilateral_exit: complete"
431        );
432        Ok(UnilateralBuild {
433            leaves,
434            recoverable_value_sats,
435            total_fee_sats,
436            cpfp_fee_sats,
437            fanout_fee_sats,
438            refund_fee_sats,
439            sweep_fee_sats,
440            transactions,
441        })
442    }
443
444    /// Stores the `sweeps` that `stored` does not hold.
445    async fn store_sweeps(&self, sweeps: &[RefundSweep], stored: &HashMap<String, LeafRecovery>) {
446        let now = now_secs();
447        for sweep in sweeps {
448            let Some(transaction) = sweep_in_block(sweep) else {
449                continue;
450            };
451            let leaf_id = sweep.leaf_id.to_string();
452            let held = stored
453                .get(&leaf_id)
454                .is_some_and(|leaf| leaf.unilateral_exit_sweep.as_ref() == Some(&transaction));
455            if held {
456                continue;
457            }
458            self.store_leaf_recovery(UpdateLeafRecovery {
459                leaf_id,
460                chain_checked_at: Some(now),
461                unilateral_exit_sweep: Some(transaction),
462                ..Default::default()
463            })
464            .await;
465        }
466    }
467}
468
469/// Checks with the chain service whether the refund of each exited leaf was
470/// swept, from the leaf's refund address. The operators report an exited leaf
471/// the same either way. It stores the checks of a batch before it starts the
472/// next one, and starts none after a failed request. Returns the leaves whose
473/// check is complete.
474pub(super) async fn store_exited_leaf_checks(
475    leaves: &[TreeNode],
476    network: bitcoin::Network,
477    queries: &mut ChainQueries,
478    storage: &dyn Storage,
479) -> Vec<String> {
480    let mut complete = Vec::new();
481    for batch in batches(leaves) {
482        if queries.failed() {
483            break;
484        }
485        let refund_addresses = refund_addresses_of(batch, network);
486        queries
487            .resolve(|observed| ((), scan_refund_sweeps(&refund_addresses, observed).pending))
488            .await;
489        let checks = exited_leaf_checks(batch, &refund_addresses, &queries.fetched(), now_secs());
490        complete.extend(store_checks(storage, checks).await);
491    }
492    complete
493}
494
495fn refund_addresses_of(
496    leaves: &[TreeNode],
497    network: bitcoin::Network,
498) -> HashMap<TreeNodeId, Address> {
499    let tree_nodes: HashMap<TreeNodeId, TreeNode> = leaves
500        .iter()
501        .map(|leaf| (leaf.id.clone(), leaf.clone()))
502        .collect();
503    let leaf_ids: Vec<TreeNodeId> = leaves.iter().map(|leaf| leaf.id.clone()).collect();
504    leaf_refund_addresses(&tree_nodes, &leaf_ids, network)
505}
506
507/// What to store for each exited leaf, from the queries with a result: nothing
508/// for a leaf with a query still pending, and a check without a sweep for a
509/// leaf the results show no sweep for. The funds of such a leaf stay in the
510/// total until the chain service shows a sweep of them in a block.
511fn exited_leaf_checks(
512    leaves: &[TreeNode],
513    refund_addresses: &HashMap<TreeNodeId, Address>,
514    fetched: &[Observation],
515    now: u64,
516) -> Vec<UpdateLeafRecovery> {
517    let scan = scan_refund_sweeps(refund_addresses, fetched);
518    let mut checks = Vec::new();
519    for leaf in leaves {
520        let sweep = match scan.lookups.get(&leaf.id) {
521            Some(RefundSweepLookup::Pending) => continue,
522            Some(RefundSweepLookup::Swept(sweep)) => {
523                // The SDK stores a sweep only with the height of its block.
524                let Some(sweep) = sweep_in_block(sweep) else {
525                    continue;
526                };
527                Some(sweep)
528            }
529            // A leaf without a refund has no address to look at.
530            Some(RefundSweepLookup::NotSwept) | None => None,
531        };
532        checks.push(UpdateLeafRecovery {
533            leaf_id: leaf.id.to_string(),
534            chain_checked_at: Some(now),
535            unilateral_exit_sweep: sweep,
536            ..Default::default()
537        });
538    }
539    checks
540}
541
542/// `None` when the chain service did not report the sweep's block.
543fn sweep_in_block(sweep: &RefundSweep) -> Option<ChainTransaction> {
544    sweep.block_height.map(|block_height| ChainTransaction {
545        txid: sweep.txid.to_string(),
546        block_height,
547    })
548}
549
550pub(super) fn has_stored_sweep(stored: &HashMap<String, LeafRecovery>, leaf_id: &str) -> bool {
551    stored
552        .get(leaf_id)
553        .is_some_and(|leaf| leaf.unilateral_exit_sweep.is_some())
554}
555
556/// The leaves among `leaf_ids` whose sweep storage holds.
557fn leaves_with_stored_sweep(
558    leaf_ids: &[TreeNodeId],
559    stored: &HashMap<String, LeafRecovery>,
560) -> Vec<TreeNodeId> {
561    leaf_ids
562        .iter()
563        .filter(|leaf_id| has_stored_sweep(stored, &leaf_id.to_string()))
564        .cloned()
565        .collect()
566}
567
568/// `state` with the refund of each leaf in `swept` reported as swept. The SDK
569/// does not read the exit of such a leaf from the chain: storage holds its
570/// sweep.
571fn with_swept_refunds(
572    mut state: WalletExitChainState,
573    swept: Vec<TreeNodeId>,
574) -> WalletExitChainState {
575    state
576        .refunds
577        .retain(|refund| !swept.contains(&refund.leaf_id));
578    state
579        .refunds
580        .extend(swept.into_iter().map(|leaf_id| WalletExitRefund {
581            leaf_id,
582            state: WalletExitRefundState::Swept,
583        }));
584    state.refunds.sort_by(|a, b| a.leaf_id.cmp(&b.leaf_id));
585    state
586}
587
588/// The leaves of `before` that `context` dropped although their exit did not
589/// finish in a sweep.
590fn skipped_dropped_leaves(
591    before: &[TreeNodeId],
592    context: &spark_wallet::ExitContext,
593    state: &WalletExitChainState,
594    stored: &HashMap<String, LeafRecovery>,
595) -> Vec<SkippedLeaf> {
596    let mut skipped = Vec::new();
597    for leaf_id in before {
598        if context.leaf_ids.contains(leaf_id) {
599            continue;
600        }
601        let Some(leaf) = context.tree_nodes.get(leaf_id) else {
602            continue;
603        };
604        let stored_sweep = stored
605            .get(&leaf_id.to_string())
606            .is_some_and(|leaf| leaf.unilateral_exit_sweep.is_some());
607        if let Some(reason) = dropped_leaf_reason(leaf_id, state, stored_sweep) {
608            skipped.push(SkippedLeaf {
609                leaf_id: leaf_id.to_string(),
610                value_sats: leaf.value,
611                reason,
612            });
613        }
614    }
615    skipped
616}
617
618/// Updates the statuses of `transactions` from the chain. Returns whether a
619/// transaction outside them spent an outpoint they still need.
620pub(super) async fn check_recovery_transactions(
621    queries: &mut ChainQueries,
622    transactions: &mut [RecoveryTransaction],
623) -> Result<bool, SdkError> {
624    let inputs = transactions
625        .iter()
626        .map(exit_check_input)
627        .collect::<Result<Vec<_>, SdkError>>()?;
628    let check = resolve_exit_check(queries, &inputs).await;
629
630    for tx in transactions.iter_mut() {
631        let txid = Txid::from_str(&tx.txid)
632            .map_err(|e| SdkError::InvalidInput(format!("Invalid txid {}: {e}", tx.txid)))?;
633        tx.status = status_after_check(tx.status, &check, &txid);
634    }
635
636    resolve_statuses(queries, transactions).await?;
637    Ok(check.diverged)
638}
639
640/// Why a quote leaves out a leaf its context dropped. `None` when the leaf's
641/// exit finished in a sweep, which the chain read or a stored sweep shows.
642fn dropped_leaf_reason(
643    leaf_id: &TreeNodeId,
644    state: &WalletExitChainState,
645    stored_sweep: bool,
646) -> Option<SkippedLeafReason> {
647    if stored_sweep || is_swept(state, leaf_id) {
648        return None;
649    }
650    Some(if state.stopped_leaves.contains(leaf_id) {
651        SkippedLeafReason::NotRecoverable {
652            message: "A transaction the wallet cannot continue from took the leaf's exit \
653                      on-chain"
654                .to_string(),
655        }
656    } else {
657        // The wallet drops such a leaf from the context only when its own
658        // lookup had no result.
659        SkippedLeafReason::Unverified
660    })
661}
662
663fn skipped_by_planner(leaf: &UnilateralExitSkippedLeaf) -> SkippedLeaf {
664    SkippedLeaf {
665        leaf_id: leaf.id.to_string(),
666        value_sats: leaf.value,
667        reason: match &leaf.reason {
668            UnilateralExitSkipReason::Unprofitable => SkippedLeafReason::FeeExceedsValue,
669            UnilateralExitSkipReason::Unexitable(reason) => SkippedLeafReason::NotRecoverable {
670                message: format!("The leaf cannot be exited: {reason}"),
671            },
672        },
673    }
674}
675
676fn is_swept(state: &WalletExitChainState, leaf_id: &TreeNodeId) -> bool {
677    state.refunds.iter().any(|refund| {
678        refund.leaf_id == *leaf_id && matches!(refund.state, WalletExitRefundState::Swept)
679    })
680}
681
682/// The sweep's fee: total input value minus output value.
683fn sweep_fee(sweep_psbt: &bitcoin::Psbt) -> u64 {
684    let in_value: u64 = sweep_psbt
685        .inputs
686        .iter()
687        .filter_map(|i| i.witness_utxo.as_ref())
688        .map(|o| o.value.to_sat())
689        .fold(0u64, u64::saturating_add);
690    let out_value: u64 = sweep_psbt
691        .unsigned_tx
692        .output
693        .iter()
694        .map(|o| o.value.to_sat())
695        .fold(0u64, u64::saturating_add);
696    in_value.saturating_sub(out_value)
697}
698
699/// Converts a sat/vByte fee rate (the public API unit) to sat/kW (the exit
700/// engine's unit): one vByte is 4 weight units, so 1 sat/vByte is 250 sat/kW.
701fn sat_per_kw_from_vbyte(sat_per_vbyte: u64) -> u64 {
702    sat_per_vbyte.saturating_mul(250)
703}
704
705/// The signed input weight and a representative output scriptPubKey for a
706/// funding kind.
707fn funding_kind_params(kind: &CpfpFundingKind) -> Result<(u64, ScriptBuf), SdkError> {
708    // Only the scriptPubKey length matters here (it fixes output weight and
709    // dust), so any valid program of the right size works.
710    let witness_script = |version, program: &[u8]| -> Result<ScriptBuf, SdkError> {
711        let program = bitcoin::WitnessProgram::new(version, program).map_err(|e| {
712            SdkError::Generic(format!("invalid representative witness program: {e}"))
713        })?;
714        Ok(ScriptBuf::new_witness_program(&program))
715    };
716    let (weight, script) = match kind {
717        CpfpFundingKind::P2wpkh => (
718            spark_wallet::p2wpkh_input_weight().to_wu(),
719            witness_script(bitcoin::WitnessVersion::V0, &[0u8; 20])?,
720        ),
721        CpfpFundingKind::P2tr => (
722            spark_wallet::p2tr_key_path_input_weight().to_wu(),
723            witness_script(bitcoin::WitnessVersion::V1, &[0u8; 32])?,
724        ),
725        CpfpFundingKind::Custom {
726            script_pubkey_hex,
727            signed_input_weight,
728        } => {
729            let script = ScriptBuf::from_hex(script_pubkey_hex).map_err(|e| {
730                SdkError::InvalidInput(format!("Invalid funding script_pubkey_hex: {e}"))
731            })?;
732            // Only native SegWit funding is supported: the exit threads txids from
733            // unsigned txs, stable only when the input's scriptSig stays empty.
734            // Reject here so the quote fails before funding is gathered.
735            if !script.is_witness_program() {
736                return Err(SdkError::InvalidInput(
737                    "Custom funding must pay to a native SegWit (witness-program) script"
738                        .to_string(),
739                ));
740            }
741            (*signed_input_weight, script)
742        }
743    };
744    Ok((weight, script))
745}
746
747impl ModelCpfpInput {
748    /// Converts into the spark-wallet funding type. Takes `network` to derive
749    /// the P2WPKH/P2TR script from a pubkey.
750    fn into_funding_input(self, network: bitcoin::Network) -> Result<CpfpInput, SdkError> {
751        let parse_txid = |s: &str| {
752            Txid::from_str(s)
753                .map_err(|e| SdkError::InvalidInput(format!("Invalid funding txid: {e}")))
754        };
755        match self {
756            ModelCpfpInput::P2wpkh {
757                txid,
758                vout,
759                value_sats: value,
760                pubkey,
761            } => {
762                let pk = PublicKey::from_str(&pubkey)
763                    .map_err(|e| SdkError::InvalidInput(format!("Invalid funding pubkey: {e}")))?;
764                let script_pubkey =
765                    Address::p2wpkh(&CompressedPublicKey(pk), network).script_pubkey();
766                Ok(CpfpInput {
767                    outpoint: OutPoint {
768                        txid: parse_txid(&txid)?,
769                        vout,
770                    },
771                    witness_utxo: TxOut {
772                        value: Amount::from_sat(value),
773                        script_pubkey,
774                    },
775                    signed_input_weight: spark_wallet::p2wpkh_input_weight().to_wu(),
776                })
777            }
778            ModelCpfpInput::P2tr {
779                txid,
780                vout,
781                value_sats: value,
782                pubkey,
783            } => {
784                let xonly = parse_xonly(&pubkey)?;
785                let secp = bitcoin::secp256k1::Secp256k1::verification_only();
786                let script_pubkey = Address::p2tr(&secp, xonly, None, network).script_pubkey();
787                Ok(CpfpInput {
788                    outpoint: OutPoint {
789                        txid: parse_txid(&txid)?,
790                        vout,
791                    },
792                    witness_utxo: TxOut {
793                        value: Amount::from_sat(value),
794                        script_pubkey,
795                    },
796                    signed_input_weight: spark_wallet::p2tr_key_path_input_weight().to_wu(),
797                })
798            }
799            ModelCpfpInput::Custom {
800                txid,
801                vout,
802                value_sats: value,
803                script_pubkey_hex,
804                signed_input_weight,
805            } => {
806                let script_pubkey = ScriptBuf::from_hex(&script_pubkey_hex).map_err(|e| {
807                    SdkError::InvalidInput(format!("Invalid funding scriptPubKey hex: {e}"))
808                })?;
809                // The exit signs/weighs funding inputs as SegWit and spends them in
810                // a v3/TRUC anchor package; a legacy input breaks both. Reject it.
811                if !script_pubkey.is_witness_program() {
812                    return Err(SdkError::InvalidInput(
813                        "Custom funding input must pay to a SegWit (witness-program) script"
814                            .to_string(),
815                    ));
816                }
817                Ok(CpfpInput {
818                    outpoint: OutPoint {
819                        txid: parse_txid(&txid)?,
820                        vout,
821                    },
822                    witness_utxo: TxOut {
823                        value: Amount::from_sat(value),
824                        script_pubkey,
825                    },
826                    signed_input_weight,
827                })
828            }
829        }
830    }
831}
832
833/// Parses an x-only pubkey from hex, accepting both x-only (32-byte) and
834/// compressed (33-byte) encodings.
835fn parse_xonly(pubkey: &str) -> Result<XOnlyPublicKey, SdkError> {
836    if let Ok(xonly) = XOnlyPublicKey::from_str(pubkey) {
837        return Ok(xonly);
838    }
839    let pk = PublicKey::from_str(pubkey)
840        .map_err(|e| SdkError::InvalidInput(format!("Invalid funding pubkey: {e}")))?;
841    Ok(pk.x_only_public_key().0)
842}
843
844/// Reads what the chain has already done to `leaf_ids`, before any funding is
845/// considered. Also returns the sweeps the results show.
846async fn resolve_exit_chain_state(
847    queries: &mut ChainQueries,
848    tree_nodes: &HashMap<TreeNodeId, TreeNode>,
849    leaf_ids: &[TreeNodeId],
850    refund_addresses: &HashMap<TreeNodeId, Address>,
851) -> (WalletExitChainState, Vec<RefundSweep>) {
852    let (state, sweeps) = queries
853        .resolve(|observed| {
854            let scan = scan_exit_chain(tree_nodes, leaf_ids, refund_addresses, observed);
855            ((scan.state, scan.sweeps), scan.pending)
856        })
857        .await;
858    debug!(
859        nodes = state.nodes.len(),
860        refunds = state.refunds.len(),
861        "resolve_exit_chain_state: what the chain has already done"
862    );
863    (state, sweeps)
864}
865
866/// Reads back the state a caller carried over from `prepare_recover_funds`.
867fn exit_chain_state_from_model(
868    state: &ModelExitChainState,
869) -> Result<WalletExitChainState, SdkError> {
870    Ok(WalletExitChainState {
871        nodes: state
872            .confirmed_nodes
873            .iter()
874            .map(|node| {
875                Ok(WalletConfirmedExitNode {
876                    block_height: node.block_height,
877                    node_id: node_id(&node.node_id)?,
878                    confirmed_by: match node.confirmed_by {
879                        ExitNodeConfirmation::Cpfp => WalletExitNodeConfirmation::Cpfp,
880                        ExitNodeConfirmation::Direct => WalletExitNodeConfirmation::Direct,
881                    },
882                })
883            })
884            .collect::<Result<_, SdkError>>()?,
885        refunds: state
886            .refunds
887            .iter()
888            .map(|refund| {
889                let restored = match &refund.state {
890                    ExitRefundState::OnChain {
891                        tx_hex,
892                        vout,
893                        value_sats,
894                        block_height,
895                    } => WalletExitRefundState::OnChain {
896                        block_height: *block_height,
897                        tx: deserialize_hex(tx_hex).map_err(|e| {
898                            SdkError::InvalidInput(format!("Invalid refund transaction: {e}"))
899                        })?,
900                        vout: *vout,
901                        value: *value_sats,
902                    },
903                    ExitRefundState::Swept => WalletExitRefundState::Swept,
904                };
905                Ok(WalletExitRefund {
906                    leaf_id: node_id(&refund.leaf_id)?,
907                    state: restored,
908                })
909            })
910            .collect::<Result<_, SdkError>>()?,
911        stopped_leaves: node_ids(&state.stopped_leaf_ids)?,
912        unverified_nodes: node_ids(&state.unverified_node_ids)?,
913        unverifiable_confirmed_nodes: node_ids(&state.unverifiable_confirmed_node_ids)?,
914    })
915}
916
917fn node_id(id: &str) -> Result<TreeNodeId, SdkError> {
918    TreeNodeId::from_str(id).map_err(|e| SdkError::InvalidInput(format!("Invalid id {id}: {e}")))
919}
920
921pub(super) fn node_ids(ids: &[String]) -> Result<Vec<TreeNodeId>, SdkError> {
922    ids.iter().map(|id| node_id(id)).collect()
923}
924
925/// Restates the wallet's on-chain reading in the API's own types: ids as strings
926/// and transactions as hex, so a caller can read what an exit has already done
927/// rather than hand an opaque token back.
928fn exit_chain_state_model(state: WalletExitChainState) -> ModelExitChainState {
929    ModelExitChainState {
930        confirmed_nodes: state
931            .nodes
932            .into_iter()
933            .map(|node| ConfirmedExitNode {
934                node_id: node.node_id.to_string(),
935                confirmed_by: match node.confirmed_by {
936                    WalletExitNodeConfirmation::Cpfp => ExitNodeConfirmation::Cpfp,
937                    WalletExitNodeConfirmation::Direct => ExitNodeConfirmation::Direct,
938                },
939                block_height: node.block_height,
940            })
941            .collect(),
942        refunds: state
943            .refunds
944            .into_iter()
945            .map(|refund| ExitRefund {
946                leaf_id: refund.leaf_id.to_string(),
947                state: match refund.state {
948                    WalletExitRefundState::OnChain {
949                        tx,
950                        vout,
951                        value,
952                        block_height,
953                    } => ExitRefundState::OnChain {
954                        tx_hex: serialize_hex(&tx),
955                        vout,
956                        value_sats: value,
957                        block_height,
958                    },
959                    WalletExitRefundState::Swept => ExitRefundState::Swept,
960                },
961            })
962            .collect(),
963        stopped_leaf_ids: ids(state.stopped_leaves),
964        unverified_node_ids: ids(state.unverified_nodes),
965        unverifiable_confirmed_node_ids: ids(state.unverifiable_confirmed_nodes),
966    }
967}
968
969fn ids(ids: Vec<TreeNodeId>) -> Vec<String> {
970    ids.into_iter().map(|id| id.to_string()).collect()
971}
972
973/// Fills in the status of every transaction that is neither on-chain nor
974/// unreadable: whether it can go out now, or what it is waiting on. Derived from
975/// the whole list, so it is resolved once the list is complete rather than as
976/// each entry is built.
977///
978/// A relative timelock counts from the height of the input being spent, so
979/// maturity needs that height and the chain tip. Both are read here rather than
980/// fetched again per transaction. A height that cannot be read leaves the
981/// transaction waiting rather than ready, the direction that never sends a
982/// transaction the mempool would reject.
983pub(super) async fn resolve_statuses(
984    queries: &mut ChainQueries,
985    transactions: &mut [RecoveryTransaction],
986) -> Result<(), SdkError> {
987    let confirmed: HashSet<&str> = transactions
988        .iter()
989        .filter(|tx| matches!(tx.status, ExitTransactionStatus::Confirmed { .. }))
990        .map(|tx| tx.txid.as_str())
991        .collect();
992    let met: Vec<bool> = transactions
993        .iter()
994        .map(|tx| {
995            tx.depends_on
996                .iter()
997                .all(|dep| confirmed.contains(dep.as_str()))
998        })
999        .collect();
1000
1001    // Seeded from the list, which already carries the height of everything the
1002    // exit walk confirmed, so the chain is only asked about inputs from outside
1003    // it: the ancestor a resumed exit starts from.
1004    let mut heights: HashMap<Txid, Option<u32>> = transactions
1005        .iter()
1006        .filter_map(|tx| match tx.status {
1007            ExitTransactionStatus::Confirmed {
1008                block_height: Some(height),
1009            } => Some((Txid::from_str(&tx.txid).ok()?, Some(height))),
1010            _ => None,
1011        })
1012        .collect();
1013
1014    let mut resolved = Vec::with_capacity(transactions.len());
1015    for (tx, met) in transactions.iter().zip(&met) {
1016        // On-chain, or its own on-chain state unknown: neither leaves anything
1017        // to wait for.
1018        if matches!(
1019            tx.status,
1020            ExitTransactionStatus::Confirmed { .. } | ExitTransactionStatus::Unverified
1021        ) {
1022            resolved.push(tx.status);
1023            continue;
1024        }
1025        if !met {
1026            resolved.push(ExitTransactionStatus::WaitingForDependencies);
1027            continue;
1028        }
1029        if tx.csv_timelock_blocks.is_none() {
1030            resolved.push(ExitTransactionStatus::Ready);
1031            continue;
1032        }
1033        let decoded = deserialize_hex::<Transaction>(&tx.tx_hex)
1034            .map_err(|e| SdkError::InvalidInput(format!("Invalid transaction: {e}")))?;
1035        let Some(spendable_at) =
1036            spendable_at_height(queries.chain_service(), &decoded, &mut heights).await
1037        else {
1038            resolved.push(ExitTransactionStatus::WaitingForTimelock {
1039                spendable_at_height: None,
1040            });
1041            continue;
1042        };
1043        // A transaction is accepted while it would be valid in the next block.
1044        let matured = queries
1045            .tip_height()
1046            .await
1047            .is_some_and(|tip| tip.saturating_add(1) >= spendable_at);
1048        resolved.push(if matured {
1049            ExitTransactionStatus::Ready
1050        } else {
1051            ExitTransactionStatus::WaitingForTimelock {
1052                spendable_at_height: Some(spendable_at),
1053            }
1054        });
1055    }
1056
1057    for (tx, status) in transactions.iter_mut().zip(resolved) {
1058        tx.status = status;
1059    }
1060    Ok(())
1061}
1062
1063/// The status of one kept transaction after a chain read.
1064///
1065/// - The chain has it in a block: `Confirmed`, at the height the read reported,
1066///   or at the height already held when the read settled it along the spend
1067///   chain instead of asking about it.
1068/// - The chain service failed a query the read needed for it: `Unverified`.
1069/// - The chain was asked and reported it is not in a block: reset to a
1070///   placeholder `resolve_statuses` replaces, discarding a confirmation a reorg
1071///   has undone.
1072/// - `Unverified` otherwise: reset to that placeholder as well, because the read
1073///   had every result it needed for the transaction.
1074/// - Anything else: left as it is. `resolve_statuses` recomputes every status
1075///   except `Confirmed` and `Unverified`, and a `Confirmed` may not be dropped
1076///   on a read that did not contradict it.
1077fn status_after_check(
1078    current: ExitTransactionStatus,
1079    check: &ExitCheck,
1080    txid: &Txid,
1081) -> ExitTransactionStatus {
1082    let held_height = match current {
1083        ExitTransactionStatus::Confirmed { block_height } => block_height,
1084        _ => None,
1085    };
1086    match (check.confirmed.get(txid), current) {
1087        (Some(block_height), _) => ExitTransactionStatus::Confirmed {
1088            block_height: block_height.or(held_height),
1089        },
1090        (None, _) if check.unverified.contains(txid) => ExitTransactionStatus::Unverified,
1091        (None, ExitTransactionStatus::Confirmed { .. }) if check.not_confirmed.contains(txid) => {
1092            ExitTransactionStatus::WaitingForDependencies
1093        }
1094        (None, ExitTransactionStatus::Unverified) => ExitTransactionStatus::WaitingForDependencies,
1095        (None, _) => current,
1096    }
1097}
1098
1099/// The first block height that can include `tx`, given the relative timelocks on
1100/// its inputs. `None` when an input's confirmation height cannot be established,
1101/// which leaves maturity unknown.
1102async fn spendable_at_height(
1103    chain: &dyn BitcoinChainService,
1104    tx: &Transaction,
1105    heights: &mut HashMap<Txid, Option<u32>>,
1106) -> Option<u32> {
1107    let mut spendable_at = None;
1108    for input in &tx.input {
1109        let blocks = match input.sequence.to_relative_lock_time() {
1110            Some(bitcoin::relative::LockTime::Blocks(blocks)) => u32::from(blocks.value()),
1111            _ => continue,
1112        };
1113        if blocks == 0 {
1114            continue;
1115        }
1116        let funded_by = input.previous_output.txid;
1117        if heights.get(&funded_by).is_none() {
1118            let height = match chain.get_transaction_status(funded_by.to_string()).await {
1119                Ok(status) if status.confirmed => status.block_height,
1120                _ => None,
1121            };
1122            heights.insert(funded_by, height);
1123        }
1124        let known = heights.get(&funded_by).copied().flatten();
1125        // One unreadable input is enough to leave the whole transaction unknown:
1126        // it may be the one that matures last.
1127        let height = known?;
1128        spendable_at = Some(spendable_at.unwrap_or(0).max(height.saturating_add(blocks)));
1129    }
1130    spendable_at
1131}
1132
1133/// Decodes one kept transaction into what the check reads.
1134fn exit_check_input(tx: &RecoveryTransaction) -> Result<ExitCheckInput, SdkError> {
1135    let decode = |hex: &str| {
1136        deserialize_hex::<Transaction>(hex)
1137            .map_err(|e| SdkError::InvalidInput(format!("Invalid transaction: {e}")))
1138    };
1139    Ok(ExitCheckInput {
1140        tx: decode(&tx.tx_hex)?,
1141        cpfp: tx.cpfp_tx_hex.as_deref().map(decode).transpose()?,
1142        confirmed: matches!(tx.status, ExitTransactionStatus::Confirmed { .. }),
1143    })
1144}
1145
1146/// Which kept transactions are in a block, and whether the on-chain state
1147/// diverged from them, as the chain service reports it.
1148async fn resolve_exit_check(queries: &mut ChainQueries, inputs: &[ExitCheckInput]) -> ExitCheck {
1149    let check = queries
1150        .resolve(|observed| {
1151            let mut check = check_exit_chain(inputs, observed);
1152            let pending = std::mem::take(&mut check.pending);
1153            (check, pending)
1154        })
1155        .await;
1156    debug!(
1157        confirmed = check.confirmed.len(),
1158        diverged = check.diverged,
1159        "resolve_exit_check: read back"
1160    );
1161    check
1162}
1163
1164/// Follows the supplied funding to what it is worth now. The only chain reading
1165/// a build does: the tree was read while preparing.
1166async fn resolve_funding(queries: &mut ChainQueries, supplied: Vec<CpfpInput>) -> Vec<CpfpInput> {
1167    let resolved = queries
1168        .resolve(|observed| {
1169            let scan = scan_funding(&supplied, observed);
1170            (scan.inputs, scan.pending)
1171        })
1172        .await;
1173    debug!(
1174        supplied = supplied.len(),
1175        resolved = resolved.len(),
1176        "resolve_funding: what the supplied funding is worth now"
1177    );
1178    resolved
1179}
1180
1181/// The status a built transaction starts at. What an unconfirmed one is waiting
1182/// for takes the whole list to work out, so [`resolve_statuses`] replaces this.
1183fn initial_status(status: ExitTxStatus) -> ExitTransactionStatus {
1184    match status {
1185        ExitTxStatus::Confirmed { block_height } => {
1186            ExitTransactionStatus::Confirmed { block_height }
1187        }
1188        ExitTxStatus::Unconfirmed => ExitTransactionStatus::WaitingForDependencies,
1189        ExitTxStatus::Unverified => ExitTransactionStatus::Unverified,
1190    }
1191}
1192
1193/// The sweep's starting status, derived from the refunds it spends. A verified
1194/// refund is spent-and-dropped once its sweep confirms (the exit then returns
1195/// with no sweep), so a freshly-returned sweep over verified refunds is never
1196/// yet on-chain. An unverified refund (its chain lookup failed) could already be
1197/// on-chain and swept without us knowing, so the sweep is `Unverified`.
1198fn sweep_initial_status(build: &UnilateralExitBuild) -> ExitTransactionStatus {
1199    let any_refund_unverified = build
1200        .branches
1201        .iter()
1202        .flat_map(|b| b.txs.iter())
1203        .any(|t| t.kind == ExitTxKind::Refund && t.status == ExitTxStatus::Unverified);
1204    if any_refund_unverified {
1205        ExitTransactionStatus::Unverified
1206    } else {
1207        ExitTransactionStatus::WaitingForDependencies
1208    }
1209}
1210
1211/// Signs a PSBT via the external `CpfpSigner`, returning the tx as hex.
1212/// Ephemeral anchor inputs are finalized here (`OP_TRUE`, no signature).
1213async fn sign_psbt_via(
1214    mut psbt: bitcoin::Psbt,
1215    signer: Option<&dyn CpfpSigner>,
1216) -> Result<String, SdkError> {
1217    let signer = signer.ok_or_else(no_signer)?;
1218    for input in &mut psbt.inputs {
1219        if let Some(txo) = &input.witness_utxo
1220            && is_ephemeral_anchor_output(txo)
1221        {
1222            input.final_script_witness = Some(bitcoin::Witness::new());
1223        }
1224    }
1225    let out_bytes = signer
1226        .sign_psbt(psbt.serialize())
1227        .await
1228        .map_err(|e| SdkError::Signer(format!("CPFP signer error: {e}")))?;
1229    let out_psbt = bitcoin::Psbt::deserialize(&out_bytes)
1230        .map_err(|e| SdkError::Generic(format!("Failed to deserialize signed PSBT: {e}")))?;
1231    ensure_all_inputs_finalized(&out_psbt)?;
1232    Ok(serialize_hex(&out_psbt.extract_tx_unchecked_fee_rate()))
1233}
1234
1235/// Finalizes the sweep. Refund inputs are already signed by spark-wallet, so the
1236/// external signer is only invoked when CPFP-change inputs still need it.
1237async fn finalize_sweep(
1238    psbt: bitcoin::Psbt,
1239    signer: Option<&dyn CpfpSigner>,
1240) -> Result<String, SdkError> {
1241    let needs_signer = psbt
1242        .inputs
1243        .iter()
1244        .any(|input| input.final_script_witness.is_none());
1245    let psbt = if needs_signer {
1246        let out_bytes = signer
1247            .ok_or_else(no_signer)?
1248            .sign_psbt(psbt.serialize())
1249            .await
1250            .map_err(|e| SdkError::Signer(format!("Sweep signer error: {e}")))?;
1251        bitcoin::Psbt::deserialize(&out_bytes).map_err(|e| {
1252            SdkError::Generic(format!("Failed to deserialize signed sweep PSBT: {e}"))
1253        })?
1254    } else {
1255        psbt
1256    };
1257    ensure_all_inputs_finalized(&psbt)?;
1258    Ok(serialize_hex(&psbt.extract_tx_unchecked_fee_rate()))
1259}
1260
1261fn no_signer() -> SdkError {
1262    SdkError::InvalidInput("A signer is needed to sign the funding inputs".to_string())
1263}
1264
1265/// Rejects a PSBT with any input the signer left unfinalized (neither a witness
1266/// nor a scriptSig), so a missing signature fails here instead of at broadcast.
1267fn ensure_all_inputs_finalized(psbt: &bitcoin::Psbt) -> Result<(), SdkError> {
1268    if let Some(index) = psbt
1269        .inputs
1270        .iter()
1271        .position(|input| input.final_script_witness.is_none() && input.final_script_sig.is_none())
1272    {
1273        return Err(SdkError::Signer(format!(
1274            "PSBT input {index} was not signed"
1275        )));
1276    }
1277    Ok(())
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282    use super::*;
1283    use crate::{
1284        chain::{
1285            Outspend, TxStatus, Utxo,
1286            stub::{ChainStub, tx_paying},
1287        },
1288        error::SignerError,
1289    };
1290    use std::sync::Arc;
1291
1292    use bitcoin::hashes::Hash;
1293    use spark_wallet::{ChainQuery, ChainResult, ExitBranch, ExitTx};
1294
1295    #[cfg(feature = "browser-tests")]
1296    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
1297
1298    fn refund_tx(status: ExitTxStatus) -> ExitTx {
1299        ExitTx {
1300            kind: ExitTxKind::Refund,
1301            node_id: None,
1302            txid: Txid::from_byte_array([3; 32]),
1303            base_tx: Transaction {
1304                version: bitcoin::transaction::Version::TWO,
1305                lock_time: bitcoin::absolute::LockTime::ZERO,
1306                input: vec![],
1307                output: vec![],
1308            },
1309            to_sign: None,
1310            cpfp_tx: None,
1311            csv_timelock_blocks: None,
1312            depends_on: vec![],
1313            status,
1314        }
1315    }
1316
1317    fn build_with_refund(status: ExitTxStatus) -> UnilateralExitBuild {
1318        UnilateralExitBuild {
1319            fan_out: None,
1320            branches: vec![ExitBranch {
1321                leaf_id: TreeNodeId::from_str("leaf").unwrap(),
1322                txs: vec![refund_tx(status)],
1323            }],
1324            refund_outputs: vec![],
1325            cpfp_change_inputs: vec![],
1326            recoverable_value_sat: 0,
1327            cpfp_fee_sat: 0,
1328            fanout_fee_sat: 0,
1329            refund_fee_sat: 0,
1330        }
1331    }
1332
1333    #[test]
1334    fn a_leaf_with_a_stored_sweep_is_reported_as_swept() {
1335        let id = |n: u8| {
1336            TreeNodeId::from_str(&format!("00000000-0000-0000-0000-0000000000{n:02}")).unwrap()
1337        };
1338        let stored = HashMap::from([(
1339            id(1).to_string(),
1340            LeafRecovery {
1341                leaf_id: id(1).to_string(),
1342                chain_checked_at: Some(900),
1343                watchtower_exit_output: None,
1344                watchtower_exit_recoveries: Vec::new(),
1345                watchtower_exit_spend: None,
1346                unilateral_exit_sweep: Some(ChainTransaction {
1347                    txid: "sweep".to_string(),
1348                    block_height: 100,
1349                }),
1350            },
1351        )]);
1352
1353        let swept = leaves_with_stored_sweep(&[id(1), id(2)], &stored);
1354        assert_eq!(swept, vec![id(1)]);
1355
1356        let state = with_swept_refunds(WalletExitChainState::default(), swept);
1357        assert_eq!(state.refunds.len(), 1);
1358        assert_eq!(state.refunds[0].leaf_id, id(1));
1359        assert!(matches!(
1360            state.refunds[0].state,
1361            WalletExitRefundState::Swept
1362        ));
1363    }
1364
1365    #[test]
1366    fn a_sweep_over_verified_refunds_starts_out_waiting_on_them() {
1367        assert_eq!(
1368            sweep_initial_status(&build_with_refund(ExitTxStatus::Unconfirmed)),
1369            ExitTransactionStatus::WaitingForDependencies
1370        );
1371    }
1372
1373    #[test]
1374    fn a_sweep_over_an_unverified_refund_is_unverified() {
1375        assert_eq!(
1376            sweep_initial_status(&build_with_refund(ExitTxStatus::Unverified)),
1377            ExitTransactionStatus::Unverified
1378        );
1379    }
1380
1381    fn unsigned_two_input_psbt() -> bitcoin::Psbt {
1382        let tx = Transaction {
1383            version: bitcoin::transaction::Version::TWO,
1384            lock_time: bitcoin::absolute::LockTime::ZERO,
1385            input: vec![
1386                bitcoin::TxIn {
1387                    previous_output: OutPoint {
1388                        txid: Txid::from_byte_array([1; 32]),
1389                        vout: 0,
1390                    },
1391                    ..Default::default()
1392                },
1393                bitcoin::TxIn {
1394                    previous_output: OutPoint {
1395                        txid: Txid::from_byte_array([2; 32]),
1396                        vout: 0,
1397                    },
1398                    ..Default::default()
1399                },
1400            ],
1401            output: vec![TxOut {
1402                value: Amount::from_sat(1_000),
1403                script_pubkey: ScriptBuf::new(),
1404            }],
1405        };
1406        let mut psbt = bitcoin::Psbt::from_unsigned_tx(tx).unwrap();
1407        for input in &mut psbt.inputs {
1408            input.witness_utxo = Some(TxOut {
1409                value: Amount::from_sat(2_000),
1410                script_pubkey: ScriptBuf::new(),
1411            });
1412        }
1413        psbt
1414    }
1415
1416    fn finalize_input(input: &mut bitcoin::psbt::Input) {
1417        let mut witness = bitcoin::Witness::new();
1418        witness.push([0x01u8]);
1419        input.final_script_witness = Some(witness);
1420    }
1421
1422    /// A `CpfpSigner` that finalizes only the first `finalize` inputs.
1423    struct PartialSigner {
1424        finalize: usize,
1425    }
1426
1427    #[macros::async_trait]
1428    impl CpfpSigner for PartialSigner {
1429        async fn sign_psbt(&self, psbt_bytes: Vec<u8>) -> Result<Vec<u8>, SignerError> {
1430            let mut psbt = bitcoin::Psbt::deserialize(&psbt_bytes).unwrap();
1431            for input in psbt.inputs.iter_mut().take(self.finalize) {
1432                finalize_input(input);
1433            }
1434            Ok(psbt.serialize())
1435        }
1436    }
1437
1438    #[test]
1439    fn ensure_all_inputs_finalized_rejects_unsigned() {
1440        assert!(ensure_all_inputs_finalized(&unsigned_two_input_psbt()).is_err());
1441    }
1442
1443    #[test]
1444    fn ensure_all_inputs_finalized_accepts_finalized() {
1445        let mut psbt = unsigned_two_input_psbt();
1446        psbt.inputs.iter_mut().for_each(finalize_input);
1447        assert!(ensure_all_inputs_finalized(&psbt).is_ok());
1448    }
1449
1450    #[macros::async_test_all]
1451    async fn sign_psbt_via_errors_when_an_input_is_left_unsigned() {
1452        let result = sign_psbt_via(
1453            unsigned_two_input_psbt(),
1454            Some(&PartialSigner { finalize: 1 }),
1455        )
1456        .await;
1457        assert!(matches!(result, Err(SdkError::Signer(_))));
1458    }
1459
1460    #[macros::async_test_all]
1461    async fn signing_without_a_signer_asks_for_one() {
1462        let result = sign_psbt_via(unsigned_two_input_psbt(), None).await;
1463        assert!(matches!(result, Err(SdkError::InvalidInput(_))));
1464    }
1465
1466    #[macros::async_test_all]
1467    async fn sign_psbt_via_succeeds_when_every_input_is_signed() {
1468        let result = sign_psbt_via(
1469            unsigned_two_input_psbt(),
1470            Some(&PartialSigner { finalize: 2 }),
1471        )
1472        .await;
1473        assert!(result.is_ok());
1474    }
1475
1476    /// A transaction spending `parent` under a relative timelock of `csv` blocks.
1477    fn timelocked_tx(parent: Txid, csv: u32) -> Transaction {
1478        Transaction {
1479            version: bitcoin::transaction::Version::TWO,
1480            lock_time: bitcoin::absolute::LockTime::ZERO,
1481            input: vec![bitcoin::TxIn {
1482                previous_output: OutPoint {
1483                    txid: parent,
1484                    vout: 0,
1485                },
1486                sequence: bitcoin::Sequence::from_height(u16::try_from(csv).unwrap()),
1487                ..Default::default()
1488            }],
1489            output: vec![TxOut {
1490                value: Amount::from_sat(1_000),
1491                script_pubkey: ScriptBuf::new(),
1492            }],
1493        }
1494    }
1495
1496    fn model_tx(
1497        tx: &Transaction,
1498        csv: Option<u32>,
1499        depends_on: Vec<String>,
1500        status: ExitTransactionStatus,
1501    ) -> RecoveryTransaction {
1502        RecoveryTransaction {
1503            kind: RecoveryTxKind::Node,
1504            node_id: None,
1505            txid: tx.compute_txid().to_string(),
1506            tx_hex: serialize_hex(tx),
1507            cpfp_tx_hex: None,
1508            csv_timelock_blocks: csv,
1509            depends_on,
1510            status,
1511        }
1512    }
1513
1514    #[test]
1515    fn only_a_swept_refund_ends_an_exit() {
1516        let id = |id: &str| TreeNodeId::from_str(id).unwrap();
1517        let refund = |leaf_id: &str, state| WalletExitRefund {
1518            leaf_id: id(leaf_id),
1519            state,
1520        };
1521        let state = WalletExitChainState {
1522            nodes: Vec::new(),
1523            refunds: vec![
1524                refund("swept", WalletExitRefundState::Swept),
1525                refund(
1526                    "on-chain",
1527                    WalletExitRefundState::OnChain {
1528                        tx: timelocked_tx(Txid::from_byte_array([1; 32]), 0),
1529                        vout: 0,
1530                        value: 1_000,
1531                        block_height: None,
1532                    },
1533                ),
1534            ],
1535            stopped_leaves: vec![id("stopped"), id("on-chain")],
1536            unverified_nodes: Vec::new(),
1537            unverifiable_confirmed_nodes: Vec::new(),
1538        };
1539        let swept: Vec<&str> = ["swept", "on-chain", "stopped", "open"]
1540            .into_iter()
1541            .filter(|leaf_id| is_swept(&state, &id(leaf_id)))
1542            .collect();
1543        assert_eq!(swept, vec!["swept"], "a stopped leaf stays recoverable");
1544
1545        assert_eq!(dropped_leaf_reason(&id("swept"), &state, false), None);
1546        assert!(matches!(
1547            dropped_leaf_reason(&id("stopped"), &state, false),
1548            Some(SkippedLeafReason::NotRecoverable { .. })
1549        ));
1550        assert_eq!(
1551            dropped_leaf_reason(&id("open"), &state, false),
1552            Some(SkippedLeafReason::Unverified),
1553            "a leaf the chain read says nothing about"
1554        );
1555        assert_eq!(
1556            dropped_leaf_reason(&id("open"), &state, true),
1557            None,
1558            "a sweep an earlier read stored"
1559        );
1560    }
1561
1562    /// An exited leaf with its refund in a block, and the chain stub that shows it.
1563    struct ExitedLeaf {
1564        tree_nodes: HashMap<TreeNodeId, TreeNode>,
1565        leaf_id: TreeNodeId,
1566        refund_addresses: HashMap<TreeNodeId, Address>,
1567        refund_outpoint: OutPoint,
1568        chain: ChainStub,
1569    }
1570
1571    fn exited_leaf(leaf_id: &str, refund_byte: u8) -> ExitedLeaf {
1572        let mut leaf = spark_wallet::tree_store_tests::create_test_node_with_parent(
1573            leaf_id,
1574            None,
1575            spark_wallet::TreeNodeStatus::Exited,
1576        );
1577        let deposit = OutPoint {
1578            txid: Txid::from_byte_array([refund_byte.wrapping_add(100); 32]),
1579            vout: 0,
1580        };
1581        leaf.node_tx = tx_paying(deposit, 1_000);
1582        let address = Address::p2tr(
1583            &bitcoin::secp256k1::Secp256k1::verification_only(),
1584            leaf.verifying_public_key.x_only_public_key().0,
1585            None,
1586            bitcoin::Network::Regtest,
1587        );
1588        let refund = tx_paying(
1589            OutPoint {
1590                txid: leaf.node_tx.compute_txid(),
1591                vout: 0,
1592            },
1593            900,
1594        );
1595        let refund_outpoint = OutPoint {
1596            txid: Txid::from_byte_array([refund_byte; 32]),
1597            vout: 0,
1598        };
1599        let mut chain = ChainStub::default();
1600        // The leaf's node tx is in a block.
1601        chain.outspends.insert(
1602            (deposit.txid.to_string(), deposit.vout),
1603            ChainStub::spent(&leaf.node_tx.compute_txid().to_string(), true, Some(90)),
1604        );
1605        chain.address_txos.insert(
1606            address.to_string(),
1607            vec![Utxo {
1608                txid: refund_outpoint.txid.to_string(),
1609                vout: 0,
1610                value: 900,
1611                status: TxStatus {
1612                    confirmed: true,
1613                    block_height: Some(95),
1614                    block_time: None,
1615                },
1616            }],
1617        );
1618        chain
1619            .transactions
1620            .insert(refund_outpoint.txid.to_string(), serialize_hex(&refund));
1621        ExitedLeaf {
1622            leaf_id: leaf.id.clone(),
1623            refund_addresses: HashMap::from([(leaf.id.clone(), address)]),
1624            tree_nodes: HashMap::from([(leaf.id.clone(), leaf)]),
1625            refund_outpoint,
1626            chain,
1627        }
1628    }
1629
1630    impl ExitedLeaf {
1631        fn refund_spent(mut self, outspend: Outspend) -> Self {
1632            let outpoint = self.refund_outpoint;
1633            self.chain
1634                .outspends
1635                .insert((outpoint.txid.to_string(), outpoint.vout), outspend);
1636            self
1637        }
1638
1639        async fn checks(self) -> Vec<UpdateLeafRecovery> {
1640            self.checks_and_requests().await.0
1641        }
1642
1643        /// The checks, and how many requests the chain stub received for them.
1644        async fn checks_and_requests(self) -> (Vec<UpdateLeafRecovery>, usize) {
1645            let leaves: Vec<TreeNode> = self.tree_nodes.values().cloned().collect();
1646            let chain = std::sync::Arc::new(self.chain);
1647            let mut queries = ChainQueries::for_sync(chain.clone());
1648            queries
1649                .resolve(|observed| {
1650                    let scan = scan_refund_sweeps(&self.refund_addresses, observed);
1651                    ((), scan.pending)
1652                })
1653                .await;
1654            let checks =
1655                exited_leaf_checks(&leaves, &self.refund_addresses, &queries.fetched(), 1_000);
1656            let requests = chain.requests.load(std::sync::atomic::Ordering::SeqCst);
1657            (checks, requests)
1658        }
1659    }
1660
1661    fn checked_leaf(leaf_id: &str, sweep: Option<ChainTransaction>) -> UpdateLeafRecovery {
1662        UpdateLeafRecovery {
1663            leaf_id: leaf_id.to_string(),
1664            chain_checked_at: Some(1_000),
1665            unilateral_exit_sweep: sweep,
1666            ..Default::default()
1667        }
1668    }
1669
1670    #[macros::async_test_all]
1671    async fn an_exited_leaf_is_stored_with_the_sweep_of_its_refund() {
1672        let swept = exited_leaf("leaf", 5)
1673            .refund_spent(ChainStub::spent("sweep", true, Some(100)))
1674            .checks()
1675            .await;
1676        // The stub's spender txid does not parse, so the outspend query has no result.
1677        assert!(swept.is_empty());
1678
1679        let sweep = Txid::from_byte_array([9; 32]).to_string();
1680        let swept = exited_leaf("leaf", 5)
1681            .refund_spent(ChainStub::spent(&sweep, true, Some(100)))
1682            .checks()
1683            .await;
1684        assert_eq!(
1685            swept,
1686            vec![checked_leaf(
1687                "leaf",
1688                Some(ChainTransaction {
1689                    txid: sweep.clone(),
1690                    block_height: 100,
1691                })
1692            )]
1693        );
1694
1695        // A refund with no sweep, or with one only in the mempool, gets a check
1696        // without a sweep.
1697        for outspend in [Outspend::Unspent, ChainStub::spent(&sweep, false, None)] {
1698            let open = exited_leaf("leaf", 5).refund_spent(outspend).checks().await;
1699            assert_eq!(open, vec![checked_leaf("leaf", None)]);
1700        }
1701    }
1702
1703    #[macros::async_test_all]
1704    async fn the_check_of_an_exited_leaf_takes_two_requests() {
1705        let sweep = Txid::from_byte_array([9; 32]).to_string();
1706        for outspend in [ChainStub::spent(&sweep, true, Some(100)), Outspend::Unspent] {
1707            let (checks, requests) = exited_leaf("leaf", 5)
1708                .refund_spent(outspend)
1709                .checks_and_requests()
1710                .await;
1711            assert_eq!(checks.len(), 1);
1712            // The listing of the refund address, and the spend of the refund.
1713            assert_eq!(requests, 2);
1714        }
1715    }
1716
1717    #[macros::async_test_all]
1718    async fn an_exited_leaf_without_every_result_is_left_for_the_next_sync() {
1719        // The query for the refund's spend has no result.
1720        let missing = exited_leaf("leaf", 5).checks().await;
1721        assert!(missing.is_empty());
1722
1723        // The SDK stores a sweep only with the height of its block.
1724        let sweep = Txid::from_byte_array([9; 32]).to_string();
1725        let unnamed = exited_leaf("leaf", 5)
1726            .refund_spent(ChainStub::spent(&sweep, true, None))
1727            .checks()
1728            .await;
1729        assert!(unnamed.is_empty());
1730    }
1731
1732    #[macros::async_test_all]
1733    async fn an_exited_leaf_with_no_refund_at_its_address_stays_to_recover() {
1734        let mut exited = exited_leaf("leaf", 5);
1735        for txos in exited.chain.address_txos.values_mut() {
1736            txos.clear();
1737        }
1738
1739        assert_eq!(exited.checks().await, vec![checked_leaf("leaf", None)]);
1740    }
1741
1742    #[test]
1743    fn an_exited_leaf_is_checked_on_its_own_results() {
1744        let fetched = exited_leaf("fetched", 5);
1745        let waiting = exited_leaf("waiting", 6);
1746        let leaves: Vec<TreeNode> = fetched
1747            .tree_nodes
1748            .values()
1749            .chain(waiting.tree_nodes.values())
1750            .cloned()
1751            .collect();
1752        let refund_addresses: HashMap<TreeNodeId, Address> = fetched
1753            .refund_addresses
1754            .clone()
1755            .into_iter()
1756            .chain(waiting.refund_addresses.clone())
1757            .collect();
1758        // Every result for the first leaf, none for the second.
1759        let observed = vec![Observation {
1760            query: ChainQuery::RefundAddress {
1761                leaf_id: fetched.leaf_id.clone(),
1762                address: refund_addresses[&fetched.leaf_id].clone(),
1763            },
1764            result: ChainResult::AddressUtxos(Vec::new()),
1765        }];
1766
1767        let checks = exited_leaf_checks(&leaves, &refund_addresses, &observed, 1_000);
1768
1769        assert_eq!(checks, vec![checked_leaf("fetched", None)]);
1770    }
1771
1772    fn check_of(
1773        confirmed: &[(Txid, Option<u32>)],
1774        not_confirmed: &[Txid],
1775    ) -> spark_wallet::ExitCheck {
1776        spark_wallet::ExitCheck {
1777            confirmed: confirmed.iter().copied().collect(),
1778            diverged: false,
1779            not_confirmed: not_confirmed.iter().copied().collect(),
1780            unverified: HashSet::new(),
1781            pending: Vec::new(),
1782        }
1783    }
1784
1785    /// The check settles an ancestor along the spend chain without asking, so it
1786    /// reports no height for it. Overwriting with that loses the height the
1787    /// caller is holding, which is what a child's timelock counts from.
1788    #[macros::async_test_all]
1789    async fn a_settled_ancestor_keeps_the_height_the_caller_already_had() {
1790        let txid = Txid::from_byte_array([4; 32]);
1791        let held = ExitTransactionStatus::Confirmed {
1792            block_height: Some(880_000),
1793        };
1794
1795        assert_eq!(
1796            status_after_check(held, &check_of(&[(txid, None)], &[]), &txid),
1797            held,
1798            "a height-less confirmation does not erase the one held"
1799        );
1800        assert_eq!(
1801            status_after_check(held, &check_of(&[(txid, Some(880_004))], &[]), &txid),
1802            ExitTransactionStatus::Confirmed {
1803                block_height: Some(880_004)
1804            },
1805            "a height the chain did report wins"
1806        );
1807    }
1808
1809    /// A transaction the chain reports as not in a block loses its stored
1810    /// `Confirmed`, so a reorg cannot leave the exit reporting `Done` over a
1811    /// transaction that is no longer there. A failed lookup leaves it alone.
1812    #[macros::async_test_all]
1813    async fn a_confirmation_the_chain_contradicts_is_dropped() {
1814        let txid = Txid::from_byte_array([5; 32]);
1815        let held = ExitTransactionStatus::Confirmed {
1816            block_height: Some(880_000),
1817        };
1818
1819        assert_eq!(
1820            status_after_check(held, &check_of(&[], &[txid]), &txid),
1821            ExitTransactionStatus::WaitingForDependencies,
1822            "re-derived, so resolve_statuses works out where it really stands"
1823        );
1824        assert_eq!(
1825            status_after_check(held, &check_of(&[], &[]), &txid),
1826            held,
1827            "no answer either way leaves the caller's record alone"
1828        );
1829    }
1830
1831    /// `Unverified` means that the chain service failed a query the SDK needed
1832    /// for the transaction. `status_after_check` replaces it with what the check
1833    /// read: the transaction in a block, a query failed again, or every result
1834    /// the check needed, after which `resolve_statuses` recomputes the status.
1835    #[macros::async_test_all]
1836    async fn a_check_replaces_an_unverified_status_with_what_it_read() {
1837        let txid = Txid::from_byte_array([6; 32]);
1838        let unreadable = spark_wallet::ExitCheck {
1839            unverified: HashSet::from([txid]),
1840            ..check_of(&[], &[])
1841        };
1842
1843        assert_eq!(
1844            status_after_check(
1845                ExitTransactionStatus::Unverified,
1846                &check_of(&[(txid, Some(880_000))], &[]),
1847                &txid,
1848            ),
1849            ExitTransactionStatus::Confirmed {
1850                block_height: Some(880_000)
1851            }
1852        );
1853        assert_eq!(
1854            status_after_check(ExitTransactionStatus::Ready, &unreadable, &txid),
1855            ExitTransactionStatus::Unverified
1856        );
1857        assert_eq!(
1858            status_after_check(
1859                ExitTransactionStatus::Unverified,
1860                &check_of(&[], &[]),
1861                &txid
1862            ),
1863            ExitTransactionStatus::WaitingForDependencies
1864        );
1865    }
1866
1867    /// `resolve_statuses` recomputes everything except `Confirmed` and
1868    /// `Unverified`, so a check that learned nothing about a transaction can leave
1869    /// its status alone and still have it come out up to date.
1870    #[macros::async_test_all]
1871    async fn a_check_that_learned_nothing_leaves_a_recomputable_status_alone() {
1872        let txid = Txid::from_byte_array([7; 32]);
1873        for status in [
1874            ExitTransactionStatus::Ready,
1875            ExitTransactionStatus::WaitingForDependencies,
1876            ExitTransactionStatus::WaitingForTimelock {
1877                spendable_at_height: Some(880_010),
1878            },
1879        ] {
1880            assert_eq!(
1881                status_after_check(status, &check_of(&[], &[]), &txid),
1882                status
1883            );
1884        }
1885    }
1886
1887    /// A parent at height 100 with a 6 block timelock is spendable from block
1888    /// 106, so a tip of 105 is enough: the child would be valid in block 106.
1889    #[macros::async_test_all]
1890    async fn a_matured_timelock_is_ready_one_block_early() {
1891        let parent = model_tx(
1892            &timelocked_tx(Txid::from_byte_array([9; 32]), 0),
1893            None,
1894            vec![],
1895            ExitTransactionStatus::Confirmed {
1896                block_height: Some(100),
1897            },
1898        );
1899        let parent_txid = Txid::from_str(&parent.txid).unwrap();
1900        let child = model_tx(
1901            &timelocked_tx(parent_txid, 6),
1902            Some(6),
1903            vec![parent.txid.clone()],
1904            ExitTransactionStatus::WaitingForDependencies,
1905        );
1906        let chain = ChainStub {
1907            tip: Some(105),
1908            heights: HashMap::new(),
1909            ..Default::default()
1910        };
1911
1912        let mut txs = vec![parent, child];
1913        resolve_statuses(&mut ChainQueries::new(Arc::new(chain)), &mut txs)
1914            .await
1915            .unwrap();
1916
1917        assert_eq!(txs[1].status, ExitTransactionStatus::Ready);
1918    }
1919
1920    #[macros::async_test_all]
1921    async fn an_unmatured_timelock_reports_the_block_it_waits_for() {
1922        let parent = model_tx(
1923            &timelocked_tx(Txid::from_byte_array([9; 32]), 0),
1924            None,
1925            vec![],
1926            ExitTransactionStatus::Confirmed {
1927                block_height: Some(100),
1928            },
1929        );
1930        let parent_txid = Txid::from_str(&parent.txid).unwrap();
1931        let child = model_tx(
1932            &timelocked_tx(parent_txid, 6),
1933            Some(6),
1934            vec![parent.txid.clone()],
1935            ExitTransactionStatus::WaitingForDependencies,
1936        );
1937        let chain = ChainStub {
1938            tip: Some(104),
1939            heights: HashMap::new(),
1940            ..Default::default()
1941        };
1942
1943        let mut txs = vec![parent, child];
1944        resolve_statuses(&mut ChainQueries::new(Arc::new(chain)), &mut txs)
1945            .await
1946            .unwrap();
1947
1948        assert_eq!(
1949            txs[1].status,
1950            ExitTransactionStatus::WaitingForTimelock {
1951                spendable_at_height: Some(106)
1952            }
1953        );
1954    }
1955
1956    /// The chain service fails the tip height. The SDK requests it once for all
1957    /// the transactions waiting on a timelock.
1958    #[macros::async_test_all]
1959    async fn a_failed_tip_height_is_requested_once() {
1960        let parent = model_tx(
1961            &timelocked_tx(Txid::from_byte_array([9; 32]), 0),
1962            None,
1963            vec![],
1964            ExitTransactionStatus::Confirmed {
1965                block_height: Some(100),
1966            },
1967        );
1968        let parent_txid = Txid::from_str(&parent.txid).unwrap();
1969        let children: Vec<RecoveryTransaction> = [6, 7, 8]
1970            .into_iter()
1971            .map(|csv| {
1972                model_tx(
1973                    &timelocked_tx(parent_txid, csv),
1974                    Some(csv),
1975                    vec![parent.txid.clone()],
1976                    ExitTransactionStatus::WaitingForDependencies,
1977                )
1978            })
1979            .collect();
1980        let chain = Arc::new(ChainStub {
1981            tip: None,
1982            ..Default::default()
1983        });
1984
1985        let mut txs = vec![parent];
1986        txs.extend(children);
1987        resolve_statuses(&mut ChainQueries::new(chain.clone()), &mut txs)
1988            .await
1989            .unwrap();
1990
1991        assert_eq!(chain.requests.load(std::sync::atomic::Ordering::SeqCst), 1);
1992        assert_eq!(
1993            txs[1].status,
1994            ExitTransactionStatus::WaitingForTimelock {
1995                spendable_at_height: Some(106)
1996            }
1997        );
1998    }
1999
2000    /// An unconfirmed parent holds the child at its dependencies: the timelock
2001    /// has no height to count from yet.
2002    #[macros::async_test_all]
2003    async fn an_unconfirmed_dependency_outranks_the_timelock() {
2004        let parent = model_tx(
2005            &timelocked_tx(Txid::from_byte_array([9; 32]), 0),
2006            None,
2007            vec![],
2008            ExitTransactionStatus::WaitingForDependencies,
2009        );
2010        let parent_txid = Txid::from_str(&parent.txid).unwrap();
2011        let child = model_tx(
2012            &timelocked_tx(parent_txid, 6),
2013            Some(6),
2014            vec![parent.txid.clone()],
2015            ExitTransactionStatus::WaitingForDependencies,
2016        );
2017        let chain = ChainStub {
2018            tip: Some(999),
2019            heights: HashMap::new(),
2020            ..Default::default()
2021        };
2022
2023        let mut txs = vec![parent, child];
2024        resolve_statuses(&mut ChainQueries::new(Arc::new(chain)), &mut txs)
2025            .await
2026            .unwrap();
2027
2028        assert_eq!(txs[1].status, ExitTransactionStatus::WaitingForDependencies);
2029    }
2030
2031    /// The exit a resume builds starts below the node it resumes from, so the
2032    /// height its first timelock counts from is not in the list. It comes from
2033    /// the chain instead.
2034    #[macros::async_test_all]
2035    async fn a_height_outside_the_list_is_read_from_the_chain() {
2036        let ancestor = Txid::from_byte_array([7; 32]);
2037        let tx = timelocked_tx(ancestor, 10);
2038        let chain = ChainStub {
2039            tip: Some(1_000),
2040            heights: HashMap::from([(ancestor.to_string(), 500)]),
2041            ..Default::default()
2042        };
2043
2044        let mut txs = vec![model_tx(
2045            &tx,
2046            Some(10),
2047            vec![],
2048            ExitTransactionStatus::WaitingForDependencies,
2049        )];
2050        resolve_statuses(&mut ChainQueries::new(Arc::new(chain)), &mut txs)
2051            .await
2052            .unwrap();
2053
2054        assert_eq!(txs[0].status, ExitTransactionStatus::Ready);
2055    }
2056
2057    /// An unreadable chain leaves the transaction waiting rather than ready:
2058    /// the direction that never sends what the mempool would reject.
2059    #[macros::async_test_all]
2060    async fn an_unreadable_height_leaves_the_timelock_unknown() {
2061        let tx = timelocked_tx(Txid::from_byte_array([7; 32]), 10);
2062        let chain = ChainStub {
2063            tip: Some(1_000),
2064            heights: HashMap::new(),
2065            ..Default::default()
2066        };
2067
2068        let mut txs = vec![model_tx(
2069            &tx,
2070            Some(10),
2071            vec![],
2072            ExitTransactionStatus::WaitingForDependencies,
2073        )];
2074        resolve_statuses(&mut ChainQueries::new(Arc::new(chain)), &mut txs)
2075            .await
2076            .unwrap();
2077
2078        assert_eq!(
2079            txs[0].status,
2080            ExitTransactionStatus::WaitingForTimelock {
2081                spendable_at_height: None
2082            }
2083        );
2084    }
2085
2086    /// A transaction in a block and the next one, whose CPFP child has `funding`
2087    /// as an input.
2088    struct NextToConfirm {
2089        transactions: Vec<RecoveryTransaction>,
2090        funding: OutPoint,
2091        chain: ChainStub,
2092    }
2093
2094    fn next_to_confirm() -> NextToConfirm {
2095        let confirmed = tx_paying(
2096            OutPoint {
2097                txid: Txid::from_byte_array([1; 32]),
2098                vout: 0,
2099            },
2100            1_000,
2101        );
2102        let confirmed_txid = confirmed.compute_txid();
2103        let next_input = OutPoint {
2104            txid: confirmed_txid,
2105            vout: 0,
2106        };
2107        let next = tx_paying(next_input, 900);
2108        let funding = OutPoint {
2109            txid: Txid::from_byte_array([3; 32]),
2110            vout: 0,
2111        };
2112        let mut cpfp = tx_paying(funding, 500);
2113        cpfp.input.push(bitcoin::TxIn {
2114            previous_output: OutPoint {
2115                txid: next.compute_txid(),
2116                vout: 1,
2117            },
2118            ..Default::default()
2119        });
2120        let chain = ChainStub {
2121            heights: HashMap::from([(confirmed_txid.to_string(), 100)]),
2122            outspends: HashMap::from([(
2123                (next_input.txid.to_string(), next_input.vout),
2124                Outspend::Unspent,
2125            )]),
2126            ..Default::default()
2127        };
2128        NextToConfirm {
2129            transactions: vec![
2130                model_tx(
2131                    &confirmed,
2132                    None,
2133                    vec![],
2134                    ExitTransactionStatus::Confirmed {
2135                        block_height: Some(100),
2136                    },
2137                ),
2138                RecoveryTransaction {
2139                    cpfp_tx_hex: Some(serialize_hex(&cpfp)),
2140                    ..model_tx(
2141                        &next,
2142                        None,
2143                        vec![confirmed_txid.to_string()],
2144                        ExitTransactionStatus::WaitingForDependencies,
2145                    )
2146                },
2147            ],
2148            funding,
2149            chain,
2150        }
2151    }
2152
2153    impl NextToConfirm {
2154        /// Runs `check_recovery_transactions`. Returns whether it found an
2155        /// outpoint spent by another transaction, the status it gave the next
2156        /// transaction, and how many requests the chain stub received.
2157        async fn check(mut self) -> (bool, ExitTransactionStatus, usize) {
2158            let chain = std::sync::Arc::new(self.chain);
2159            let mut queries = ChainQueries::new(chain.clone());
2160            let diverged = check_recovery_transactions(&mut queries, &mut self.transactions)
2161                .await
2162                .unwrap();
2163            let requests = chain.requests.load(std::sync::atomic::Ordering::SeqCst);
2164            (diverged, self.transactions[1].status, requests)
2165        }
2166    }
2167
2168    #[macros::async_test_all]
2169    async fn check_finds_the_spent_funding_of_a_cpfp_child() {
2170        let mut next = next_to_confirm();
2171        let spender_txid = Txid::from_byte_array([2; 32]).to_string();
2172        next.chain.outspends.insert(
2173            (next.funding.txid.to_string(), next.funding.vout),
2174            ChainStub::spent(&spender_txid, true, Some(101)),
2175        );
2176
2177        let (diverged, _, requests) = next.check().await;
2178
2179        assert!(diverged);
2180        assert_eq!(
2181            requests, 3,
2182            "the transaction in a block, the outpoint of the next one's input, and the funding"
2183        );
2184    }
2185
2186    /// The SDK could not read the chain for the next transaction while it built
2187    /// the recovery. `check_recovery_transactions` reads every input it needs,
2188    /// the funding of its CPFP child included, and finds it ready.
2189    #[macros::async_test_all]
2190    async fn check_clears_unverified_once_it_reads_what_the_transaction_needs() {
2191        let mut next = next_to_confirm();
2192        next.transactions[1].status = ExitTransactionStatus::Unverified;
2193        next.chain.outspends.insert(
2194            (next.funding.txid.to_string(), next.funding.vout),
2195            Outspend::Unspent,
2196        );
2197
2198        let (diverged, status, _) = next.check().await;
2199
2200        assert!(!diverged);
2201        assert_eq!(status, ExitTransactionStatus::Ready);
2202    }
2203
2204    /// The chain stub fails the query for the funding of the next transaction's
2205    /// CPFP child.
2206    #[macros::async_test_all]
2207    async fn check_reports_a_transaction_it_could_not_read_as_unverified() {
2208        let (diverged, status, requests) = next_to_confirm().check().await;
2209
2210        assert!(!diverged);
2211        assert_eq!(status, ExitTransactionStatus::Unverified);
2212        assert_eq!(requests, 3);
2213    }
2214}