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
use std::{collections::BTreeMap, sync::Mutex};

use anyswap_core::types::{Chain, Outpoint, SwapInStatus, SwapOutStatus, SwapType};
use async_trait::async_trait;
use bitcoin::secp256k1::{PublicKey, SecretKey};
use serde::{Deserialize, Serialize};
use serde_with::{DisplayFromStr, serde_as};
use thiserror::Error;
use uuid::Uuid;

use super::{
    error::DriverError,
    rt::{MaybeSend, MaybeSync},
};
use crate::swap_script::{Side, Terms};

/// Unix seconds.
pub type Timestamp = u64;

/// A block height on the swap's chain.
pub type Height = u32;

/// One swap as the driver keeps it: both ends frozen at acceptance, the
/// status, and what the chain cannot report. Our own keys derive from
/// `swap_id`. Amounts serialize as decimal strings, as the API's do.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SwapRecord {
    pub version: u32,
    pub swap_id: Uuid,
    pub payment_hash: [u8; 32],
    pub source: Endpoint,
    pub dest: Endpoint,
    #[serde_as(as = "DisplayFromStr")]
    pub send_amount: u64,
    #[serde_as(as = "DisplayFromStr")]
    pub receive_amount: u64,
    /// The server's split of `send_amount - receive_amount`: `base_fee` for
    /// its transactions, `service_fee` the rest.
    #[serde_as(as = "DisplayFromStr")]
    pub base_fee: u64,
    #[serde_as(as = "DisplayFromStr")]
    pub service_fee: u64,
    /// Our own clock at acceptance.
    pub started_at: Timestamp,
    pub status: Status,
    /// SwapIn: what under the script is ours, as the last pass left it.
    #[serde(default)]
    pub funds: Vec<Fund>,
    /// When the status first became final: our clock, or the server's on
    /// restore. What `refund_timeout` counts from.
    #[serde(default)]
    pub ended_at: Option<Timestamp>,
    /// The preimage once seen and hashed to `payment_hash`: on a SwapIn the
    /// server's, from its report or its claim, on a SwapOut ours, from a claim
    /// of ours on chain.
    pub preimage: Option<[u8; 32]>,
    pub sent: Sent,
    /// The server's status as the last pass that reached it read it, `None`
    /// before one. Shown, never decided on.
    #[serde(default)]
    pub server_status: Option<String>,
    /// The server's cancel, kept from the first pass that read one. Never
    /// cleared, since a cancel is final on the server.
    #[serde(default)]
    pub server_cancel: Option<ServerCancel>,
}

/// The server's status by name, `In` for a SwapIn and `Out` for a SwapOut.
#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display)]
pub enum ServerStatus {
    #[strum(default)]
    In(SwapInStatus),
    #[strum(default)]
    Out(SwapOutStatus),
}

impl ServerStatus {
    pub fn is_terminal(&self) -> bool {
        match self {
            Self::In(status) => matches!(status, SwapInStatus::Claimed | SwapInStatus::Canceled),
            Self::Out(status) => matches!(
                status,
                SwapOutStatus::Claimed | SwapOutStatus::Canceled | SwapOutStatus::Refunded
            ),
        }
    }
}

/// One end of a swap: on chain when `chain` is set, Lightning when it is
/// not. The server holds the opposite role on each end, the claim key of a
/// source and the refund key of a dest.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Endpoint {
    pub chain: Option<Chain>,
    pub asset: Option<String>,
    pub csv: Option<u32>,
    pub server_pubkey: Option<PublicKey>,
    pub server_blinding_pubkey: Option<PublicKey>,
    /// On chain, where the end pays out: the refund address of a source, the
    /// claim address of a dest.
    pub destination: Option<String>,
    /// Lightning: the invoice, paid to a SwapIn, paid by a SwapOut.
    pub invoice: Option<String>,
    /// The server's key, once it arrived and verified against `server_pubkey`.
    pub server_privkey: Option<SecretKey>,
}

impl Endpoint {
    pub fn lightning(invoice: String) -> Self {
        Self {
            invoice: Some(invoice),
            ..Self::default()
        }
    }

    pub fn on_chain(terms: Terms, destination: Option<String>) -> Self {
        Self {
            chain: Some(terms.chain),
            asset: Some(terms.asset),
            csv: Some(terms.csv),
            server_pubkey: Some(terms.server_pubkey),
            server_blinding_pubkey: terms.server_blinding_pubkey,
            destination,
            invoice: None,
            server_privkey: None,
        }
    }
}

impl SwapRecord {
    /// The record form this SDK writes and drives.
    pub const VERSION: u32 = 1;

    /// Nothing a pass could move. A SwapOut once its status is final. A SwapIn
    /// once its status is final, no refund of ours is unconfirmed, nothing of
    /// ours waits for a destination to take it, and `window` has passed since
    /// it ended, so a deposit that crossed the end is still found. `hook` is
    /// whether the driver can ask for a refund address.
    pub fn is_quiet(&self, now: Timestamp, window: u64, hook: bool) -> bool {
        let destination = hook || self.source.destination.is_some();
        let busy = self.funds.iter().any(|fund| match fund.state {
            FundState::Refunding { .. } => true,
            FundState::Locked { .. } | FundState::Refundable => destination,
            FundState::Dust | FundState::Refunded { .. } => false,
        });
        let watched = self
            .ended_at
            .is_none_or(|ended| now < ended.saturating_add(window));
        let swap_in = matches!(self.swap_type(), Ok(SwapType::SwapIn));
        self.status.is_terminal() && !busy && !(swap_in && watched)
    }

    /// SwapIn: the server's key while our refund key is home, which is when a
    /// refund takes the keypath. Once our key leaves the server holds both, so
    /// a keypath spend from then on is read as the server's.
    pub(crate) fn refund_keypath(&self) -> Option<SecretKey> {
        self.source.server_privkey.filter(|_| !self.sent.refund_key)
    }

    /// SwapIn: whether an output with `confs` confirmations is out of our
    /// reach: unconfirmed, so a refund never spends a mempool chain, or its
    /// CSV still running and no keypath to refund it by.
    pub(crate) fn locked(&self, csv: u32, confs: u32) -> bool {
        confs == 0 || (self.refund_keypath().is_none() && confs < csv)
    }

    pub fn server_status(&self) -> Option<ServerStatus> {
        let label = self.server_status.as_deref()?;
        match self.swap_type().ok()? {
            SwapType::SwapIn => label.parse().ok().map(ServerStatus::In),
            SwapType::SwapOut => label.parse().ok().map(ServerStatus::Out),
            SwapType::SwapChain => None,
        }
    }

    /// What the ends make: one on chain is a SwapIn or a SwapOut, both a
    /// SwapChain.
    pub fn swap_type(&self) -> Result<SwapType, DriverError> {
        match (self.source.chain, self.dest.chain) {
            (Some(_), None) => Ok(SwapType::SwapIn),
            (None, Some(_)) => Ok(SwapType::SwapOut),
            (Some(_), Some(_)) => Ok(SwapType::SwapChain),
            (None, None) => Err(self.missing("chain")),
        }
    }

    pub fn endpoint(&self, side: Side) -> &Endpoint {
        match side {
            Side::Source => &self.source,
            Side::Dest => &self.dest,
        }
    }

    pub fn endpoint_mut(&mut self, side: Side) -> &mut Endpoint {
        match side {
            Side::Source => &mut self.source,
            Side::Dest => &mut self.dest,
        }
    }

    /// The script terms of the end on `side`. Every use of our keys starts
    /// here, so a record of another version stops here.
    pub fn terms(&self, side: Side) -> Result<Terms, DriverError> {
        if self.version != Self::VERSION {
            return Err(DriverError::RecordVersion(self.swap_id, self.version));
        }
        let end = self.endpoint(side);
        let missing = |name: &str| self.missing(&format!("{side} {name}"));
        Ok(Terms {
            swap_id: self.swap_id,
            side,
            chain: end.chain.ok_or_else(|| missing("chain"))?,
            asset: end.asset.clone().ok_or_else(|| missing("asset"))?,
            csv: end.csv.ok_or_else(|| missing("csv"))?,
            payment_hash: self.payment_hash,
            server_pubkey: end.server_pubkey.ok_or_else(|| missing("server pubkey"))?,
            server_blinding_pubkey: end.server_blinding_pubkey,
        })
    }

    pub(crate) fn missing(&self, what: &str) -> DriverError {
        DriverError::MissingField(self.swap_id, what.to_owned())
    }
}

/// The messages already delivered, since a message leaves no trace on chain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sent {
    pub cancel: bool,
    pub refund_key: bool,
    pub preimage: bool,
}

/// Where a swap stands, resolved from the chain on every pass. Deadlines are
/// absolute so two quiet passes produce an equal status.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status")]
pub enum Status {
    /// Restored, before its first pass: where it stands is not known yet.
    Restoring,
    Funding {
        expires_at: Timestamp,
        cancel_sent: bool,
    },
    /// `max_fee_rate` is the chain's, in sat/vB. SwapOut: `fee_rate_spike` is
    /// the fee estimate while it is above `max_fee_rate` and holds the
    /// preimage.
    Confirming {
        txid: String,
        confs: u32,
        needed: u32,
        #[serde(default)]
        max_fee_rate: f64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fee_rate_spike: Option<f64>,
    },
    /// SwapOut only. The preimage may have left: claiming the opening, with
    /// `claim` and its `fee` once a claim of ours is broadcast.
    Claiming {
        opening: String,
        claim: Option<String>,
        confs: u32,
        #[serde(default)]
        #[serde_as(as = "Option<DisplayFromStr>")]
        fee: Option<u64>,
    },
    /// `fee` is our claim's on a SwapOut, and `None` on a SwapIn, whose
    /// payout is the server's.
    Completed {
        opening: String,
        payout: Option<String>,
        #[serde(default)]
        #[serde_as(as = "Option<DisplayFromStr>")]
        fee: Option<u64>,
    },
    /// The swap did not happen, for `reason`. On a SwapOut the invoice fails
    /// back: the server canceled before any opening, or `opening` is left to
    /// its CSV refund. On a SwapIn the deposit stays ours, with the rest of
    /// `funds`.
    Canceled {
        opening: Option<String>,
        reason: CancelReason,
    },
}

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

// `max_fee_rate` is finite and `fee_rate_spike` is above it, so neither is NaN.
impl Eq for Status {}

/// Why a swap ended `Canceled`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum CancelReason {
    /// The server gave the swap up, in its words: a SwapIn's key, a SwapOut's
    /// report before any opening.
    ServerCanceled(ServerCancel),
    /// SwapIn: the deposit's CSV matured with neither the server's key nor
    /// its preimage.
    CsvMatured,
    /// SwapOut: the server's CSV refund took the opening.
    ServerRefunded,
    /// SwapOut: less than `claim_margin` of the CSV was left before the
    /// preimage went out, so it never will. The invoice fails back once the
    /// server's CSV refund takes the opening, from block `at`.
    ClaimWindowClosed { at: Height },
}

/// The server's cancel in its words: its `ErrorType` name and the message
/// the cancel came with.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerCancel {
    pub error_type: Option<String>,
    pub cancel_message: Option<String>,
}

/// SwapIn: one output under the script that is ours, and where its refund
/// stands. The deposit the server was paid for is not listed, nor is an
/// output the server took by its own path.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fund {
    pub outpoint: Outpoint,
    #[serde_as(as = "DisplayFromStr")]
    pub amount: u64,
    pub state: FundState,
}

#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state")]
pub enum FundState {
    /// Under the CSV until `at`, or unconfirmed.
    Locked { at: Option<Height> },
    /// Spendable now and worth its refund: the next refund takes it.
    Refundable,
    /// Spendable, but not worth its fee and the smallest output a refund
    /// address takes at the last rate. `run` takes the swap up again once
    /// the rate makes it worth its refund.
    Dust,
    /// In our refund `txid`, not yet in a block. `fee` is the whole
    /// transaction's, shared by every fund it took.
    Refunding {
        txid: String,
        #[serde(default)]
        #[serde_as(as = "Option<DisplayFromStr>")]
        fee: Option<u64>,
    },
    /// In our refund `txid`, in a block, with `fee` as in `Refunding`.
    Refunded {
        txid: String,
        #[serde(default)]
        #[serde_as(as = "Option<DisplayFromStr>")]
        fee: Option<u64>,
    },
}

#[derive(Clone, Debug, Error)]
#[error("store: {0}")]
pub struct StoreError(pub String);

/// Durable records, wanted by id and nothing else.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait SwapStore: MaybeSend + MaybeSync {
    /// Replaces any record already stored under the same swap id.
    async fn save(&self, record: &SwapRecord) -> Result<(), StoreError>;
    async fn load(&self, swap_id: &Uuid) -> Result<Option<SwapRecord>, StoreError>;
    /// Every stored swap id, without reading the records, so one that fails
    /// to load stops only its own swap.
    async fn list(&self) -> Result<Vec<Uuid>, StoreError>;
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<S: SwapStore + ?Sized> SwapStore for std::sync::Arc<S> {
    async fn save(&self, record: &SwapRecord) -> Result<(), StoreError> {
        (**self).save(record).await
    }

    async fn load(&self, swap_id: &Uuid) -> Result<Option<SwapRecord>, StoreError> {
        (**self).load(swap_id).await
    }

    async fn list(&self) -> Result<Vec<Uuid>, StoreError> {
        (**self).list().await
    }
}

/// Records kept in memory, for tests and short-lived tools.
#[derive(Default)]
pub struct MemoryStore(Mutex<BTreeMap<Uuid, SwapRecord>>);

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl SwapStore for MemoryStore {
    async fn save(&self, record: &SwapRecord) -> Result<(), StoreError> {
        self.0
            .lock()
            .unwrap()
            .insert(record.swap_id, record.clone());
        Ok(())
    }

    async fn load(&self, swap_id: &Uuid) -> Result<Option<SwapRecord>, StoreError> {
        Ok(self.0.lock().unwrap().get(swap_id).cloned())
    }

    async fn list(&self) -> Result<Vec<Uuid>, StoreError> {
        Ok(self.0.lock().unwrap().keys().copied().collect())
    }
}