anyswap-sdk 1.8.0

Rust client SDK for AnySwap: swaps between Lightning and on-chain Bitcoin or Liquid, with a driver that runs them to completion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! Typed client-side view of a swap-in.
//!
//! [`SwapIn`] is the parsed form of the wire [`SwapState`]: hex fields become
//! keys and outpoints, and per-status fields move into [`SwapInStatus`] variants
//! so the consumer sees exactly what is available in each state. Created via
//! `TryFrom<SwapState>` on the polling response.

pub use anyswap_core::types::{ErrorType, SwapInStatus as Status};
use anyswap_core::{
    api::SwapState,
    invoice::{self, InvoiceError},
    transaction::TxError,
    types::{Chain, Outpoint, SwapType},
    utils::sha256_payment_hash,
};
use bitcoin::secp256k1::{PublicKey, SecretKey};
use thiserror::Error;
use uuid::Uuid;

use crate::{
    codec::{self, CodecError},
    context::SwapContext,
    swap_script::{ScriptError, Side, SwapScript, Terms, Tx},
    utxo::{SwapUtxo, UtxoError},
    wallet::SwapWallet,
};

#[derive(Debug, Error)]
pub enum SwapInError {
    #[error("expected swap type SwapIn, got {0}")]
    UnexpectedSwapType(SwapType),

    #[error("unknown status: {0}")]
    UnknownStatus(String),

    #[error("unknown error type: {0}")]
    UnknownErrorType(String),

    #[error("missing field: {0}")]
    MissingField(&'static str),

    #[error("a keypath refund needs the claim key the server reveals when it cancels")]
    KeypathRefundUnavailable,

    #[error("this client is not set up for Liquid; add the Liquid parameters to the context")]
    LiquidNotConfigured,

    #[error("the swap trades asset {found}, but this client is set up for {expected}")]
    UnexpectedAsset { expected: String, found: String },

    #[error("wallet: {0}")]
    Wallet(String),

    #[error("invalid swap script: {0}")]
    Script(String),

    #[error("the output does not belong to this swap")]
    UnknownOutput,

    #[error("the server has not reported a preimage in this status")]
    NoPreimage,

    #[error(transparent)]
    Invoice(#[from] InvoiceError),

    #[error("the preimage hashes to {found}, but the claim invoice's payment hash is {expected}")]
    UnexpectedPaymentHash { expected: String, found: String },

    #[error(transparent)]
    Utxo(#[from] UtxoError),

    #[error(transparent)]
    Tx(#[from] TxError),

    #[error(transparent)]
    Codec(#[from] CodecError),
}

impl From<ScriptError> for SwapInError {
    fn from(e: ScriptError) -> Self {
        match e {
            ScriptError::LiquidNotConfigured => Self::LiquidNotConfigured,
            ScriptError::UnexpectedAsset { expected, found } => {
                Self::UnexpectedAsset { expected, found }
            }
            ScriptError::MissingField(field) => Self::MissingField(field),
            ScriptError::Wallet(e) => Self::Wallet(e),
            ScriptError::Script(e) => Self::Script(e),
        }
    }
}

/// A swap-in: the user locks on-chain funds into the swap script and the server
/// pays the user's `claim_invoice` once the opening transaction confirms. The
/// user holds the refund key, the server holds the claim key.
#[derive(Debug, Clone)]
pub struct SwapIn {
    pub swap_id: Uuid,
    pub protocol_version: String,
    pub chain: Chain,
    pub asset: String,
    pub receive_amount: u64,
    pub send_amount: u64,
    pub base_fee: u64,
    pub service_fee: u64,
    pub payment_hash: [u8; 32],
    pub csv: u32,
    /// User's pubkey in the swap script (refund side).
    pub refund_pubkey: PublicKey,
    /// Server's pubkey in the swap script (claim side).
    pub claim_pubkey: PublicKey,
    /// User's ECDH blinding pubkey for the Liquid opening output.
    pub user_blinding_pubkey: Option<PublicKey>,
    /// Server's ECDH blinding pubkey for the Liquid opening output.
    pub service_blinding_pubkey: Option<PublicKey>,
    pub claim_invoice: String,
    pub refund_address: Option<String>,
    pub created_at: u64,
    pub transitioned_at: u64,
    pub status: SwapInStatus,
}

/// Server-reported swap-in lifecycle state with the fields available in it.
///
/// Normal flow: [`AwaitOpeningTxConfirmation`](Self::AwaitOpeningTxConfirmation) ->
/// [`PayInvoice`](Self::PayInvoice) ->
/// [`AwaitClaimKeyRevealMessage`](Self::AwaitClaimKeyRevealMessage) ->
/// [`AwaitClaimTxConfirmation`](Self::AwaitClaimTxConfirmation) ->
/// [`Claimed`](Self::Claimed).
///
/// Cancellation at any point before a successful claim results in
/// [`Canceled`](Self::Canceled), where the server reveals its claim privkey so
/// the user can refund a deposit without waiting out the CSV.
#[derive(Debug, Clone, PartialEq, Eq, strum::Display, strum::IntoStaticStr)]
pub enum SwapInStatus {
    /// Server is watching the swap address for the opening tx and its
    /// confirmations. No server-provided outpoint yet: the client tracks its own
    /// deposit by scanning the swap address until the swap advances.
    AwaitOpeningTxConfirmation,
    /// Opening tx confirmed; server is paying the claim invoice.
    PayInvoice { outpoint: Outpoint },
    /// Invoice paid. `preimage` is the server's evidence of that; check it with
    /// [`SwapIn::verify_payment`] before revealing the refund key. Server awaits
    /// that key (sent via
    /// [`HttpClient::reveal_claim`](crate::client::HttpClient::reveal_claim))
    /// for a cooperative keypath claim; otherwise it claims via the preimage
    /// script path.
    AwaitClaimKeyRevealMessage {
        outpoint: Outpoint,
        preimage: [u8; 32],
    },
    /// Claim tx broadcast; awaiting on-chain confirmation.
    AwaitClaimTxConfirmation {
        outpoint: Outpoint,
        preimage: [u8; 32],
    },
    /// Terminal: claim tx confirmed. Swap finished successfully.
    Claimed {
        outpoint: Outpoint,
        preimage: [u8; 32],
    },
    /// Terminal: canceled before a successful claim. `error_code` is the
    /// machine-readable reason. The server reveals its claim privkey; the user
    /// recovers any deposit by re-deriving the swap address, finding the UTXOs on
    /// chain, and refunding them (keypath, or CSV).
    Canceled {
        error_code: ErrorType,
        claim_privkey: SecretKey,
        cancel_message: String,
    },
}

impl SwapInStatus {
    /// Opening outpoint, once the server has recorded the confirmed deposit.
    /// `Canceled` never carries it; the user re-derives the address to find their
    /// deposit on chain.
    pub fn outpoint(&self) -> Option<&Outpoint> {
        match self {
            Self::AwaitOpeningTxConfirmation | Self::Canceled { .. } => None,
            Self::PayInvoice { outpoint }
            | Self::AwaitClaimKeyRevealMessage { outpoint, .. }
            | Self::AwaitClaimTxConfirmation { outpoint, .. }
            | Self::Claimed { outpoint, .. } => Some(outpoint),
        }
    }

    /// Payment preimage, present from the moment the server paid the claim
    /// invoice.
    pub fn preimage(&self) -> Option<&[u8; 32]> {
        match self {
            Self::AwaitClaimKeyRevealMessage { preimage, .. }
            | Self::AwaitClaimTxConfirmation { preimage, .. }
            | Self::Claimed { preimage, .. } => Some(preimage),
            _ => None,
        }
    }

    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Claimed { .. } | Self::Canceled { .. })
    }
}

/// The user is the refund side of a swap-in, so these build refunds only: a
/// cooperative one once the server reveals its claim key, and the unilateral CSV
/// one otherwise. The per-swap keys come from the context's wallet, so a caller
/// never handles a private key.
impl SwapIn {
    /// Checks the reported preimage against the payment hash in
    /// [`Self::claim_invoice`], which only paying it yields. Call before
    /// [`HttpClient::reveal_claim`](crate::client::HttpClient::reveal_claim).
    /// The invoice is the server's echo of the one sent in `create_swap`;
    /// confirm they match separately.
    pub fn verify_payment(&self) -> Result<(), SwapInError> {
        let expected = invoice::payment_hash(&self.claim_invoice)?;
        let preimage = self.status.preimage().ok_or(SwapInError::NoPreimage)?;
        let found = sha256_payment_hash(preimage);
        if found != expected {
            return Err(SwapInError::UnexpectedPaymentHash {
                expected: hex::encode(expected),
                found: hex::encode(found),
            });
        }
        Ok(())
    }

    /// The deposit address. The user sends `send_amount` here to open the swap.
    pub fn address<W: SwapWallet>(&self, ctx: &SwapContext<W>) -> Result<String, SwapInError> {
        Ok(self.script(ctx)?.address())
    }

    /// Every output of `tx_hex` paying the deposit address: the deposit itself,
    /// and any strays sent to the same address.
    ///
    /// On Liquid an output that does not unblind with this swap's key, or that
    /// holds another asset, belongs to someone else and is skipped.
    pub fn outputs<W: SwapWallet>(
        &self,
        ctx: &SwapContext<W>,
        tx_hex: &str,
    ) -> Result<Vec<SwapUtxo>, SwapInError> {
        let tx = Tx::decode(self.chain, tx_hex)?;
        Ok(self.script(ctx)?.outputs(&tx))
    }

    /// Splits `prevouts` into the ones worth refunding at `fee_rate` and the
    /// ones that would cost more to spend than they return. Run strays through
    /// this before refunding, and show the second set to the user. Needs the
    /// context because Liquid values only exist blinded inside the outputs.
    pub fn partition_economical<W: SwapWallet>(
        &self,
        ctx: &SwapContext<W>,
        utxos: &[SwapUtxo],
        fee_rate: f64,
    ) -> Result<(Vec<SwapUtxo>, Vec<SwapUtxo>), SwapInError> {
        Ok(self.script(ctx)?.economical(utxos, fee_rate)?)
    }

    /// The value of `utxo` in sats. Bitcoin states it on chain; a Liquid value
    /// is blinded, and this unblinds it with the swap's own key.
    pub fn value<W: SwapWallet>(
        &self,
        ctx: &SwapContext<W>,
        utxo: &SwapUtxo,
    ) -> Result<u64, SwapInError> {
        self.script(ctx)?
            .value(utxo)
            .ok_or(SwapInError::UnknownOutput)
    }

    /// Refunds `utxos` cooperatively, spendable right away. Needs the claim key
    /// the server reveals when it cancels the swap. Returns the signed
    /// transaction as hex.
    pub fn refund_by_keypath<W: SwapWallet>(
        &self,
        ctx: &SwapContext<W>,
        utxos: &[SwapUtxo],
        destination: &str,
        fee_rate: f64,
    ) -> Result<String, SwapInError> {
        let SwapInStatus::Canceled { claim_privkey, .. } = &self.status else {
            return Err(SwapInError::KeypathRefundUnavailable);
        };
        let refund_privkey = self.refund_privkey(ctx)?;
        Ok(self.script(ctx)?.keypath(
            utxos,
            *claim_privkey,
            refund_privkey,
            destination,
            fee_rate,
        )?)
    }

    /// Refunds `utxos` unilaterally, valid once every input has aged past the
    /// swap's CSV timeout. Needs only the user's own key, so it works even when
    /// the server does not answer. Returns the signed transaction as hex.
    pub fn refund_by_csv<W: SwapWallet>(
        &self,
        ctx: &SwapContext<W>,
        utxos: &[SwapUtxo],
        destination: &str,
        fee_rate: f64,
    ) -> Result<String, SwapInError> {
        let refund_privkey = self.refund_privkey(ctx)?;
        Ok(self
            .script(ctx)?
            .refund_by_csv(utxos, refund_privkey, destination, fee_rate)?)
    }

    /// The terms the deposit script is built from.
    pub fn terms(&self) -> Terms {
        Terms {
            swap_id: self.swap_id,
            side: Side::Source,
            chain: self.chain,
            asset: self.asset.clone(),
            csv: self.csv,
            payment_hash: self.payment_hash,
            server_pubkey: self.claim_pubkey,
            server_blinding_pubkey: self.service_blinding_pubkey,
        }
    }

    fn script<W: SwapWallet>(&self, ctx: &SwapContext<W>) -> Result<SwapScript, SwapInError> {
        Ok(ctx.script(&self.terms())?)
    }

    /// The user's key in the swap script.
    fn refund_privkey<W: SwapWallet>(
        &self,
        ctx: &SwapContext<W>,
    ) -> Result<SecretKey, SwapInError> {
        ctx.wallet()
            .source_refund_privkey(&self.swap_id)
            .map_err(|error| SwapInError::Wallet(error.to_string()))
    }
}

impl TryFrom<SwapState> for SwapIn {
    type Error = SwapInError;

    fn try_from(s: SwapState) -> Result<Self, SwapInError> {
        if s.swap_type != SwapType::SwapIn {
            return Err(SwapInError::UnexpectedSwapType(s.swap_type));
        }

        let status: Status = s
            .status
            .parse()
            .map_err(|_| SwapInError::UnknownStatus(s.status.clone()))?;

        let status = match status {
            Status::AwaitOpeningTxConfirmation => SwapInStatus::AwaitOpeningTxConfirmation,
            Status::PayInvoice => SwapInStatus::PayInvoice {
                outpoint: source_outpoint(&s)?,
            },
            Status::AwaitClaimKeyRevealMessage => SwapInStatus::AwaitClaimKeyRevealMessage {
                outpoint: source_outpoint(&s)?,
                preimage: preimage(&s)?,
            },
            Status::AwaitClaimTxConfirmation => SwapInStatus::AwaitClaimTxConfirmation {
                outpoint: source_outpoint(&s)?,
                preimage: preimage(&s)?,
            },
            Status::Claimed => SwapInStatus::Claimed {
                outpoint: source_outpoint(&s)?,
                preimage: preimage(&s)?,
            },
            Status::Canceled => {
                let raw = require(s.error_type.clone(), "error_type")?;
                SwapInStatus::Canceled {
                    error_code: raw
                        .parse()
                        .map_err(|_| SwapInError::UnknownErrorType(raw.clone()))?,
                    claim_privkey: codec::parse_privkey(&require(
                        s.source_claim_privkey.clone(),
                        "source_claim_privkey",
                    )?)?,
                    cancel_message: require(s.cancel_message.clone(), "cancel_message")?,
                }
            }
        };
        let user_blinding_pubkey = s
            .source_user_blinding_pubkey
            .as_deref()
            .map(codec::parse_pubkey)
            .transpose()?;
        let service_blinding_pubkey = s
            .source_service_blinding_pubkey
            .as_deref()
            .map(codec::parse_pubkey)
            .transpose()?;

        Ok(SwapIn {
            swap_id: s.swap_id,
            protocol_version: s.protocol_version,
            chain: require(s.source_chain, "source_chain")?,
            asset: require(s.source_asset, "source_asset")?,
            receive_amount: s.receive_amount,
            send_amount: s.send_amount,
            base_fee: s.base_fee,
            service_fee: s.service_fee,
            payment_hash: codec::parse_hash32(&s.payment_hash)?,
            csv: require(s.source_csv, "source_csv")?,
            refund_pubkey: codec::parse_pubkey(&require(
                s.source_refund_pubkey,
                "source_refund_pubkey",
            )?)?,
            claim_pubkey: codec::parse_pubkey(&require(
                s.source_claim_pubkey,
                "source_claim_pubkey",
            )?)?,
            user_blinding_pubkey,
            service_blinding_pubkey,
            claim_invoice: require(s.claim_invoice, "claim_invoice")?,
            refund_address: s.user_refund_address,
            created_at: s.created_at,
            transitioned_at: s.transitioned_at,
            status,
        })
    }
}

fn require<T>(opt: Option<T>, field: &'static str) -> Result<T, SwapInError> {
    opt.ok_or(SwapInError::MissingField(field))
}

fn source_outpoint(s: &SwapState) -> Result<Outpoint, SwapInError> {
    Ok(codec::parse_outpoint(
        require(s.source_txid.as_deref(), "source_txid")?,
        require(s.source_vout, "source_vout")?,
    )?)
}

fn preimage(s: &SwapState) -> Result<[u8; 32], SwapInError> {
    Ok(codec::parse_hash32(require(
        s.preimage.as_deref(),
        "preimage",
    )?)?)
}

#[cfg(test)]
mod tests {
    use anyswap_core::{
        script::{BitcoinSwapScript, LiquidSwapScript},
        secp,
        types::{ErrorType, NATIVE_ASSET, SwapNetwork},
    };
    use bitcoin::hashes::{Hash as _, sha256};

    use super::*;
    use crate::{
        swap_script::SpendPath,
        utxo::fixtures::{confidential_tx, genesis_hash, liquid_asset, liquid_destination},
        wallet::Wallet,
    };

    const SERVICE_SIGNING_KEY: [u8; 32] = [21; 32];
    const SERVICE_BLINDING_KEY: [u8; 32] = [22; 32];
    const BITCOIN_DESTINATION: &str = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080";

    fn context() -> SwapContext<Wallet> {
        let (wallet, _) = Wallet::generate(SwapNetwork::Regtest).unwrap();
        SwapContext::new(wallet)
            .with_liquid(&genesis_hash(), &liquid_asset())
            .unwrap()
    }

    fn swap_in(ctx: &SwapContext<Wallet>, chain: Chain, status: SwapInStatus) -> SwapIn {
        let swap_id = Uuid::from_u128(11);
        let service_signing = SecretKey::from_slice(&SERVICE_SIGNING_KEY).unwrap();
        let service_blinding = SecretKey::from_slice(&SERVICE_BLINDING_KEY).unwrap();
        let preimage = ctx.wallet().preimage(&swap_id).unwrap();
        SwapIn {
            swap_id,
            protocol_version: "2.0.0".into(),
            chain,
            asset: match chain {
                Chain::Bitcoin => NATIVE_ASSET.to_string(),
                Chain::Liquid => liquid_asset(),
            },
            receive_amount: 100_000,
            send_amount: 101_000,
            base_fee: 1_000,
            service_fee: 0,
            payment_hash: sha256::Hash::hash(&preimage).to_byte_array(),
            csv: 144,
            refund_pubkey: ctx.wallet().source_refund_pubkey(&swap_id).unwrap(),
            claim_pubkey: service_signing.public_key(secp()),
            user_blinding_pubkey: Some(ctx.wallet().source_blinding_pubkey(&swap_id).unwrap()),
            service_blinding_pubkey: Some(service_blinding.public_key(secp())),
            claim_invoice: "lnbcrt1".into(),
            refund_address: None,
            created_at: 1,
            transitioned_at: 1,
            status,
        }
    }

    fn canceled() -> SwapInStatus {
        SwapInStatus::Canceled {
            error_code: ErrorType::UserCanceled,
            claim_privkey: SecretKey::from_slice(&SERVICE_SIGNING_KEY).unwrap(),
            cancel_message: "canceled".into(),
        }
    }

    #[test]
    fn liquid_refunds_the_deposit_and_a_stray_together() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Liquid, canceled());
        let opening_tx = confidential_tx(&liquid_script(&swap, &ctx), &[101_000, 40_000]);

        let utxos = swap.outputs(&ctx, &opening_tx).unwrap();

        assert_eq!(utxos.len(), 2);
        assert_eq!(swap.value(&ctx, &utxos[0]).unwrap(), 101_000);
        assert_eq!(swap.value(&ctx, &utxos[1]).unwrap(), 40_000);
        let destination = liquid_destination();
        for tx_hex in [
            swap.refund_by_csv(&ctx, &utxos, &destination, 1.0).unwrap(),
            swap.refund_by_keypath(&ctx, &utxos, &destination, 1.0)
                .unwrap(),
        ] {
            let tx = anyswap_core::transaction::liquid::decode_tx_hex(&tx_hex).unwrap();
            assert_eq!(tx.input.len(), 2);
        }
    }

    #[test]
    fn liquid_skips_outputs_of_another_swap() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Liquid, canceled());
        let other = SwapIn {
            csv: 288,
            ..swap_in(&ctx, Chain::Liquid, canceled())
        };
        let other_tx = confidential_tx(&liquid_script(&other, &ctx), &[101_000]);

        assert!(swap.outputs(&ctx, &other_tx).unwrap().is_empty());
    }

    #[test]
    fn another_swaps_output_has_no_value_here() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Liquid, canceled());
        // A different swap id derives a different blinding key, so its outputs
        // do not unblind with this swap's.
        let other = SwapIn {
            swap_id: Uuid::from_u128(99),
            ..swap_in(&ctx, Chain::Liquid, canceled())
        };
        let other_tx = confidential_tx(&liquid_script(&other, &ctx), &[101_000]);
        let theirs = other.outputs(&ctx, &other_tx).unwrap().remove(0);

        assert!(matches!(
            swap.value(&ctx, &theirs),
            Err(SwapInError::UnknownOutput)
        ));
    }

    #[test]
    fn refunds_a_utxo_the_caller_supplied() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Bitcoin, canceled());
        let opening_tx = bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000]);
        let txid = anyswap_core::transaction::bitcoin::decode_tx_hex(&opening_tx)
            .unwrap()
            .compute_txid()
            .to_string();
        // Not from outputs(): the values an indexer reported, as a caller with
        // their own chain source would pass them.
        let utxos = vec![SwapUtxo::bitcoin(txid, 0, 100_000)];

        let tx_hex = swap
            .refund_by_csv(
                &ctx,
                &utxos,
                "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080",
                1.0,
            )
            .unwrap();

        let tx = anyswap_core::transaction::bitcoin::decode_tx_hex(&tx_hex).unwrap();
        assert_eq!(tx.input.len(), 1);
        assert_eq!(swap.value(&ctx, &utxos[0]).unwrap(), 100_000);
    }

    #[test]
    fn a_keypath_refund_needs_the_revealed_claim_key() {
        let ctx = context();
        let swap = swap_in(
            &ctx,
            Chain::Liquid,
            SwapInStatus::AwaitOpeningTxConfirmation,
        );

        assert!(matches!(
            swap.refund_by_keypath(&ctx, &[], &liquid_destination(), 1.0),
            Err(SwapInError::KeypathRefundUnavailable)
        ));
    }

    #[test]
    fn a_liquid_swap_needs_a_context_set_up_for_liquid() {
        let (wallet, _) = Wallet::generate(SwapNetwork::Regtest).unwrap();
        let bitcoin_only = SwapContext::new(wallet);
        let swap = swap_in(&context(), Chain::Liquid, canceled());

        assert!(matches!(
            swap.address(&bitcoin_only),
            Err(SwapInError::LiquidNotConfigured)
        ));
    }

    #[test]
    fn a_swap_trading_another_asset_is_refused() {
        let (wallet, _) = Wallet::generate(SwapNetwork::Regtest).unwrap();
        let ctx = SwapContext::new(wallet)
            .with_liquid(&genesis_hash(), &"11".repeat(32))
            .unwrap();
        let swap = swap_in(&ctx, Chain::Liquid, canceled());

        assert!(matches!(
            swap.address(&ctx),
            Err(SwapInError::UnexpectedAsset { .. })
        ));
    }

    #[test]
    fn partition_drops_utxos_that_cannot_pay_their_own_fee() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Bitcoin, canceled());
        let opening_tx = bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000, 1_480]);

        let utxos = swap.outputs(&ctx, &opening_tx).unwrap();
        // A Bitcoin CSV refund is 138 vB, so at 10 sat/vB an input must be
        // worth more than its 1_380 sat fee and a 546 sat output.
        let (economical, dust) = swap.partition_economical(&ctx, &utxos, 10.0).unwrap();

        assert_eq!(economical.len(), 1);
        assert_eq!(swap.value(&ctx, &economical[0]).unwrap(), 100_000);
        assert_eq!(dust.len(), 1);
        assert_eq!(swap.value(&ctx, &dust[0]).unwrap(), 1_480);
    }

    #[test]
    fn partition_reports_a_bad_fee_rate_instead_of_calling_everything_dust() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Bitcoin, canceled());
        let opening_tx = bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000]);
        let utxos = swap.outputs(&ctx, &opening_tx).unwrap();

        for rate in [f64::NAN, -1.0] {
            assert!(swap.partition_economical(&ctx, &utxos, rate).is_err());
        }
    }

    #[test]
    fn bitcoin_refunds_by_csv() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Bitcoin, canceled());
        let opening_tx = bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000]);
        let utxos = swap.outputs(&ctx, &opening_tx).unwrap();

        let tx_hex = swap
            .refund_by_csv(
                &ctx,
                &utxos,
                "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080",
                1.0,
            )
            .unwrap();

        let tx = anyswap_core::transaction::bitcoin::decode_tx_hex(&tx_hex).unwrap();
        assert_eq!(tx.input.len(), 1);
        assert_eq!(tx.input[0].sequence.to_consensus_u32(), swap.csv);
    }

    #[test]
    fn reads_each_spend_path_from_the_witness() {
        let ctx = context();
        let server = SecretKey::from_slice(&SERVICE_SIGNING_KEY).unwrap();
        for chain in [Chain::Bitcoin, Chain::Liquid] {
            let swap = swap_in(&ctx, chain, canceled());
            let script = swap.script(&ctx).unwrap();
            let (opening_tx, destination) = match chain {
                Chain::Bitcoin => (
                    bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000]),
                    BITCOIN_DESTINATION.to_string(),
                ),
                Chain::Liquid => (
                    confidential_tx(&liquid_script(&swap, &ctx), &[100_000]),
                    liquid_destination(),
                ),
            };
            let utxos = swap.outputs(&ctx, &opening_tx).unwrap();
            let preimage = ctx.wallet().preimage(&swap.swap_id).unwrap();
            let path = |tx_hex: String| script.spend_path(&Tx::decode(chain, &tx_hex).unwrap(), 0);

            let keypath = swap.refund_by_keypath(&ctx, &utxos, &destination, 1.0);
            let refund = swap.refund_by_csv(&ctx, &utxos, &destination, 1.0);
            let claim = script.claim_by_preimage(&utxos, server, preimage, &destination, 1.0);
            assert_eq!(path(keypath.unwrap()), Some(SpendPath::Keypath));
            assert_eq!(path(refund.unwrap()), Some(SpendPath::Csv));
            assert_eq!(path(claim.unwrap()), Some(SpendPath::Preimage(preimage)));
        }
    }

    #[test]
    fn reads_the_spend_path_past_an_annex() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Bitcoin, canceled());
        let script = swap.script(&ctx).unwrap();
        let opening_tx = bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000]);
        let utxos = swap.outputs(&ctx, &opening_tx).unwrap();

        let keypath = swap.refund_by_keypath(&ctx, &utxos, BITCOIN_DESTINATION, 1.0);
        let refund = swap.refund_by_csv(&ctx, &utxos, BITCOIN_DESTINATION, 1.0);
        for (tx_hex, expected) in [
            (keypath.unwrap(), SpendPath::Keypath),
            (refund.unwrap(), SpendPath::Csv),
        ] {
            let mut tx = anyswap_core::transaction::bitcoin::decode_tx_hex(&tx_hex).unwrap();
            tx.input[0].witness.push([0x50, 1]);
            assert_eq!(script.spend_path(&Tx::Bitcoin(tx), 0), Some(expected));
        }
    }

    #[test]
    fn reads_no_spend_path_from_a_witness_the_script_does_not_open() {
        let ctx = context();
        let swap = swap_in(&ctx, Chain::Bitcoin, canceled());
        let script = swap.script(&ctx).unwrap();
        let opening_tx = bitcoin_tx(&bitcoin_script(&swap, &ctx), &[100_000]);
        let utxos = swap.outputs(&ctx, &opening_tx).unwrap();
        let tx_hex = swap
            .refund_by_keypath(&ctx, &utxos, BITCOIN_DESTINATION, 1.0)
            .unwrap();

        let mut tx = anyswap_core::transaction::bitcoin::decode_tx_hex(&tx_hex).unwrap();
        tx.input[0].witness.push([1]);
        let tx = Tx::Bitcoin(tx);
        assert_eq!(script.spend_path(&tx, 0), None);
        assert_eq!(script.spend_path(&tx, 1), None);
    }

    /// The swap's Liquid script, for building the opening a counterparty funds.
    fn liquid_script(swap: &SwapIn, ctx: &SwapContext<Wallet>) -> LiquidSwapScript {
        swap.script(ctx).unwrap().liquid().unwrap().clone()
    }

    fn bitcoin_script(swap: &SwapIn, ctx: &SwapContext<Wallet>) -> BitcoinSwapScript {
        swap.script(ctx).unwrap().bitcoin().unwrap().clone()
    }

    /// A transaction paying `values` to a Bitcoin swap script.
    fn bitcoin_tx(script: &BitcoinSwapScript, values: &[u64]) -> String {
        let tx = bitcoin::Transaction {
            version: bitcoin::transaction::Version::TWO,
            lock_time: bitcoin::absolute::LockTime::ZERO,
            input: vec![],
            output: values
                .iter()
                .map(|value| bitcoin::TxOut {
                    value: bitcoin::Amount::from_sat(*value),
                    script_pubkey: script.script_pubkey(),
                })
                .collect(),
        };
        anyswap_core::transaction::bitcoin::encode_tx_hex(&tx)
    }
}