anyswap-sdk 1.3.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
//! The swap script of one on-chain side with everything spending it needs:
//! the chain, the network, and on Liquid the shared blinding key and chain
//! parameters. [`SwapIn`](crate::swap_in::SwapIn),
//! [`SwapOut`](crate::swap_out::SwapOut) and the driver all build their
//! transactions through here.

use std::fmt;

#[cfg(feature = "driver")]
use anyswap_core::types::Outpoint;
use anyswap_core::{
    script::{BitcoinSwapScript, LiquidSwapScript, derive_liquid_blinding_key},
    transaction::{
        self, ClaimByPreimageParams, KeypathSpendParams, LiquidChainCtx, RefundByCsvParams, TxError,
    },
    types::{Chain, SwapNetwork},
    utils::sha256_payment_hash,
};
use bitcoin::secp256k1::{PublicKey, SecretKey};
use elements::AssetId;
use thiserror::Error;
use uuid::Uuid;

use crate::{
    context::SwapContext,
    utxo::{self, SwapUtxo, UtxoError},
    wallet::SwapWallet,
};

#[derive(Clone, Debug, Error)]
pub enum ScriptError {
    #[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("missing field: {0}")]
    MissingField(&'static str),

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

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

/// Which side of a swap an on-chain output is. `Source`: we refund and the
/// server claims. `Dest`: the reverse.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Side {
    Source,
    Dest,
}

impl fmt::Display for Side {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Source => "source",
            Self::Dest => "dest",
        })
    }
}

/// One on-chain side of a swap: what its script is built from. Our own key
/// and blinding key derive from `swap_id`, so only the server's are kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Terms {
    pub swap_id: Uuid,
    pub side: Side,
    pub chain: Chain,
    pub asset: String,
    pub csv: u32,
    pub payment_hash: [u8; 32],
    pub server_pubkey: PublicKey,
    pub server_blinding_pubkey: Option<PublicKey>,
}

/// A decoded transaction of either chain.
pub enum Tx {
    Bitcoin(bitcoin::Transaction),
    Liquid(elements::Transaction),
}

impl Tx {
    pub fn decode(chain: Chain, hex: &str) -> Result<Self, TxError> {
        Ok(match chain {
            Chain::Bitcoin => Self::Bitcoin(transaction::bitcoin::decode_tx_hex(hex)?),
            Chain::Liquid => Self::Liquid(transaction::liquid::decode_tx_hex(hex)?),
        })
    }

    pub fn txid(&self) -> String {
        match self {
            Self::Bitcoin(tx) => tx.compute_txid().to_string(),
            Self::Liquid(tx) => tx.txid().to_string(),
        }
    }

    #[cfg(feature = "driver")]
    pub fn inputs(&self) -> Vec<Outpoint> {
        let outpoint = |txid: String, vout| Outpoint::new(txid, vout);
        match self {
            Self::Bitcoin(tx) => tx
                .input
                .iter()
                .map(|i| outpoint(i.previous_output.txid.to_string(), i.previous_output.vout))
                .collect(),
            Self::Liquid(tx) => tx
                .input
                .iter()
                .map(|i| outpoint(i.previous_output.txid.to_string(), i.previous_output.vout))
                .collect(),
        }
    }
}

/// How an input spent a swap output: the three ways its script opens.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SpendPath {
    Keypath,
    Preimage([u8; 32]),
    Csv,
}

enum Inner {
    Bitcoin(Box<BitcoinSwapScript>),
    Liquid {
        script: Box<LiquidSwapScript>,
        blinding_key: SecretKey,
        ctx: LiquidChainCtx,
    },
}

pub struct SwapScript {
    chain: Chain,
    network: SwapNetwork,
    payment_hash: [u8; 32],
    inner: Inner,
}

impl<W: SwapWallet> SwapContext<W> {
    /// The script of `terms`, with our key in the role the side gives it and,
    /// on Liquid, the blinding key shared with the server. Every Liquid path
    /// goes through here, so none can skip the asset check.
    pub fn script(&self, terms: &Terms) -> Result<SwapScript, ScriptError> {
        let wallet = self.wallet();
        let wallet_error = |e: W::Error| ScriptError::Wallet(e.to_string());
        let script_error = |e: anyhow::Error| ScriptError::Script(e.to_string());
        let (claim, refund) = match terms.side {
            Side::Source => (
                terms.server_pubkey,
                wallet
                    .source_refund_pubkey(&terms.swap_id)
                    .map_err(wallet_error)?,
            ),
            Side::Dest => (
                wallet
                    .dest_claim_pubkey(&terms.swap_id)
                    .map_err(wallet_error)?,
                terms.server_pubkey,
            ),
        };
        let (claim, refund) = (claim.x_only_public_key().0, refund.x_only_public_key().0);
        let inner = match terms.chain {
            Chain::Bitcoin => Inner::Bitcoin(Box::new(
                BitcoinSwapScript::new(claim, refund, terms.payment_hash, terms.csv)
                    .map_err(script_error)?,
            )),
            Chain::Liquid => {
                let liquid = self.liquid().ok_or(ScriptError::LiquidNotConfigured)?;
                if terms.asset != liquid.policy_asset.to_string() {
                    return Err(ScriptError::UnexpectedAsset {
                        expected: liquid.policy_asset.to_string(),
                        found: terms.asset.clone(),
                    });
                }
                let own = match terms.side {
                    Side::Source => wallet.source_blinding_privkey(&terms.swap_id),
                    Side::Dest => wallet.dest_blinding_privkey(&terms.swap_id),
                }
                .map_err(wallet_error)?;
                let peer = terms
                    .server_blinding_pubkey
                    .ok_or(ScriptError::MissingField("server_blinding_pubkey"))?;
                let (blinding_pubkey, blinding_key) =
                    derive_liquid_blinding_key(&own, &peer).map_err(ScriptError::Script)?;
                let script = LiquidSwapScript::new(
                    claim,
                    refund,
                    terms.payment_hash,
                    terms.csv,
                    blinding_pubkey,
                )
                .map_err(script_error)?;
                Inner::Liquid {
                    script: Box::new(script),
                    blinding_key,
                    ctx: liquid,
                }
            }
        };
        Ok(SwapScript {
            chain: terms.chain,
            network: self.network(),
            payment_hash: terms.payment_hash,
            inner,
        })
    }
}

impl SwapScript {
    pub fn address(&self) -> String {
        match &self.inner {
            Inner::Bitcoin(script) => script.address(self.network),
            Inner::Liquid { script, .. } => script.confidential_address(self.network).to_string(),
        }
    }

    /// The outputs of `tx` that are this swap's: paying the script, and on
    /// Liquid unblinding to the policy asset with the shared key.
    pub fn outputs(&self, tx: &Tx) -> Vec<SwapUtxo> {
        let txid = tx.txid();
        match (&self.inner, tx) {
            (Inner::Bitcoin(script), Tx::Bitcoin(tx)) => {
                let spk = script.script_pubkey();
                tx.output
                    .iter()
                    .enumerate()
                    .filter(|(_, o)| o.script_pubkey == spk)
                    .map(|(vout, o)| SwapUtxo::bitcoin(txid.clone(), vout as u32, o.value.to_sat()))
                    .collect()
            }
            (Inner::Liquid { script, .. }, Tx::Liquid(tx)) => {
                let spk = script.script_pubkey();
                tx.output
                    .iter()
                    .enumerate()
                    .filter(|(_, o)| o.script_pubkey == spk)
                    .map(|(vout, o)| SwapUtxo::liquid(txid.clone(), vout as u32, o.clone()))
                    .filter(|utxo| self.value(utxo).is_some())
                    .collect()
            }
            _ => Vec::new(),
        }
    }

    /// The output of `tx` at `vout`, checked to pay this script and, on
    /// Liquid, to hold its asset, with its value.
    pub fn output_at(&self, tx: &Tx, vout: u32) -> Result<(SwapUtxo, u64), TxError> {
        let txid = tx.txid();
        match (&self.inner, tx) {
            (Inner::Bitcoin(script), Tx::Bitcoin(tx)) => {
                let value = transaction::bitcoin::opening_value(tx, vout, script)?.to_sat();
                Ok((SwapUtxo::bitcoin(txid, vout, value), value))
            }
            (
                Inner::Liquid {
                    script,
                    blinding_key,
                    ctx,
                },
                Tx::Liquid(tx),
            ) => {
                let value = transaction::liquid::opening_value(
                    tx,
                    vout,
                    script,
                    blinding_key,
                    ctx.policy_asset,
                )?;
                let output = tx.output[vout as usize].clone();
                Ok((SwapUtxo::liquid(txid, vout, output), value))
            }
            _ => Err(TxError::InvalidPrevout(
                "transaction of another chain".into(),
            )),
        }
    }

    /// The value in sats, or `None` when the output is not this swap's.
    pub fn value(&self, utxo: &SwapUtxo) -> Option<u64> {
        utxo.value(self.unblinding())
    }

    /// Splits `utxos` into the ones worth spending at `fee_rate` and the rest.
    pub fn economical(
        &self,
        utxos: &[SwapUtxo],
        fee_rate: f64,
    ) -> Result<(Vec<SwapUtxo>, Vec<SwapUtxo>), UtxoError> {
        let liquid = self.unblinding().map(|(key, asset)| (*key, asset));
        utxo::partition_economical(utxos, self.chain, fee_rate, liquid)
    }

    /// How input `vin` of `tx` spent this script, read from its witness.
    /// `None` when the witness opens none of its paths.
    pub fn spend_path(&self, tx: &Tx, vin: u32) -> Option<SpendPath> {
        let mut items: Vec<&[u8]> = match tx {
            Tx::Bitcoin(tx) => tx.input.get(vin as usize)?.witness.iter().collect(),
            Tx::Liquid(tx) => tx
                .input
                .get(vin as usize)?
                .witness
                .script_witness
                .iter()
                .collect(),
        };
        // The last item starting 0x50 is the annex (BIP341).
        if items.len() > 1 && items.last()?.first() == Some(&0x50) {
            items.pop();
        }
        let (claim, refund) = match &self.inner {
            Inner::Bitcoin(script) => (
                script.claim_script().as_bytes(),
                script.refund_script().as_bytes(),
            ),
            Inner::Liquid { script, .. } => (
                script.claim_script().as_bytes(),
                script.refund_script().as_bytes(),
            ),
        };
        match items.as_slice() {
            [_signature] => Some(SpendPath::Keypath),
            [_signature, leaf, _control] if *leaf == refund => Some(SpendPath::Csv),
            [_signature, preimage, leaf, _control] if *leaf == claim => {
                let preimage = <[u8; 32]>::try_from(*preimage).ok()?;
                (sha256_payment_hash(&preimage) == self.payment_hash)
                    .then_some(SpendPath::Preimage(preimage))
            }
            _ => None,
        }
    }

    /// A cooperative keypath spend, claim or refund, with both keys in hand.
    pub fn keypath(
        &self,
        utxos: &[SwapUtxo],
        claim_privkey: SecretKey,
        refund_privkey: SecretKey,
        destination: &str,
        fee_rate: f64,
    ) -> Result<String, TxError> {
        let params = match &self.inner {
            Inner::Bitcoin(script) => KeypathSpendParams::Bitcoin {
                inputs: utxo::bitcoin_inputs(utxos).map_err(wrong_chain)?,
                script: (**script).clone(),
                claim_privkey,
                refund_privkey,
            },
            Inner::Liquid {
                script,
                blinding_key,
                ctx,
            } => KeypathSpendParams::Liquid {
                inputs: utxo::liquid_inputs(utxos).map_err(wrong_chain)?,
                blinding_key: *blinding_key,
                script: (**script).clone(),
                genesis_hash: ctx.genesis_hash,
                policy_asset: ctx.policy_asset,
                claim_privkey,
                refund_privkey,
            },
        };
        transaction::build_refund_by_keypath(params, destination, fee_rate)
    }

    pub fn refund_by_csv(
        &self,
        utxos: &[SwapUtxo],
        refund_privkey: SecretKey,
        destination: &str,
        fee_rate: f64,
    ) -> Result<String, TxError> {
        let params = match &self.inner {
            Inner::Bitcoin(script) => RefundByCsvParams::Bitcoin {
                inputs: utxo::bitcoin_inputs(utxos).map_err(wrong_chain)?,
                script: (**script).clone(),
                refund_privkey,
            },
            Inner::Liquid {
                script,
                blinding_key,
                ctx,
            } => RefundByCsvParams::Liquid {
                inputs: utxo::liquid_inputs(utxos).map_err(wrong_chain)?,
                blinding_key: *blinding_key,
                script: (**script).clone(),
                genesis_hash: ctx.genesis_hash,
                policy_asset: ctx.policy_asset,
                refund_privkey,
            },
        };
        transaction::build_refund_by_csv(params, destination, fee_rate)
    }

    pub fn claim_by_preimage(
        &self,
        utxos: &[SwapUtxo],
        claim_privkey: SecretKey,
        preimage: [u8; 32],
        destination: &str,
        fee_rate: f64,
    ) -> Result<String, TxError> {
        let params = match &self.inner {
            Inner::Bitcoin(script) => ClaimByPreimageParams::Bitcoin {
                inputs: utxo::bitcoin_inputs(utxos).map_err(wrong_chain)?,
                script: (**script).clone(),
                claim_privkey,
                preimage,
            },
            Inner::Liquid {
                script,
                blinding_key,
                ctx,
            } => ClaimByPreimageParams::Liquid {
                inputs: utxo::liquid_inputs(utxos).map_err(wrong_chain)?,
                blinding_key: *blinding_key,
                script: (**script).clone(),
                genesis_hash: ctx.genesis_hash,
                policy_asset: ctx.policy_asset,
                claim_privkey,
                preimage,
            },
        };
        transaction::build_claim_by_preimage(params, destination, fee_rate)
    }

    #[cfg(test)]
    pub(crate) fn bitcoin(&self) -> Option<&BitcoinSwapScript> {
        match &self.inner {
            Inner::Bitcoin(script) => Some(script),
            Inner::Liquid { .. } => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn liquid(&self) -> Option<&LiquidSwapScript> {
        match &self.inner {
            Inner::Liquid { script, .. } => Some(script),
            Inner::Bitcoin(_) => None,
        }
    }

    fn unblinding(&self) -> Option<(&SecretKey, AssetId)> {
        match &self.inner {
            Inner::Bitcoin(_) => None,
            Inner::Liquid {
                blinding_key, ctx, ..
            } => Some((blinding_key, ctx.policy_asset)),
        }
    }
}

fn wrong_chain(e: UtxoError) -> TxError {
    TxError::InvalidPrevout(e.to_string())
}