anyswap-core 1.9.0

Shared on-chain primitives and API types for AnySwap: swaps between Lightning and on-chain Bitcoin or Liquid
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
//! Liquid Esplora client and its chain-neutral [`ChainClient`] adapter.

use std::{
    collections::HashMap,
    str::FromStr,
    sync::{Arc, Mutex, PoisonError},
    time::Duration,
};

use async_trait::async_trait;
use elements::{Address, AssetId, BlockHash, Transaction, TxOut, Txid, encode};
use serde::Deserialize;

use super::{
    AddressUtxo, ChainClient, ChainClientError, DEFAULT_TIMEOUT, EsploraError, OutpointSpend,
    SpendingTx,
};
use crate::{fee, types::Chain};

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct ApiTxStatus {
    confirmed: bool,
    block_height: Option<u32>,
}

impl ApiTxStatus {
    /// A response claiming confirmation without a height is treated as unconfirmed.
    fn confirmation_height(self) -> Option<u32> {
        self.block_height.filter(|_| self.confirmed)
    }
}

/// A spend as the explorer reports it, only when it names the spending txid
/// and input; anything less reads as unspent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiquidOutspend {
    pub txid: Txid,
    pub vin: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiquidUtxo {
    pub txid: Txid,
    pub vout: u32,
    pub value: Option<u64>,
    pub asset: Option<AssetId>,
}

#[derive(Debug, Clone)]
pub struct LiquidEsplora {
    client: reqwest::Client,
    base_url: String,
    /// Bodies already fetched, by txid. A body never changes under its txid,
    /// so a history read fetches only what it has not seen. Clones share it.
    txs: Arc<Mutex<HashMap<Txid, Transaction>>>,
}

impl LiquidEsplora {
    pub fn new(url: &str) -> Self {
        Self::with_timeout(url, DEFAULT_TIMEOUT)
    }

    /// A client whose every request fails once it goes unanswered for
    /// `timeout`. Panics where `reqwest::Client::new` would: when the TLS
    /// backend cannot start.
    pub fn with_timeout(url: &str, timeout: Duration) -> Self {
        let client = reqwest::Client::builder()
            .timeout(timeout)
            .build()
            .expect("TLS backend starts");
        Self {
            client,
            base_url: url.trim_end_matches('/').to_owned(),
            txs: Arc::default(),
        }
    }

    pub async fn get_fee_rate(&self, target: usize) -> Result<f64, EsploraError> {
        let min = fee::min_fee_rate(Chain::Liquid);
        // Liquid blocks are never full, so its fee is the relay minimum
        // whether or not there is an estimate.
        let estimate = self
            .fee_estimates()
            .await
            .ok()
            .and_then(|estimates| convert_fee_rate(target, estimates))
            .unwrap_or(min);

        if !estimate.is_finite() || estimate < 0.0 {
            return Err(EsploraError::InvalidFeeRate(estimate));
        }
        Ok(estimate.max(min))
    }

    async fn fee_estimates(&self) -> Result<HashMap<u16, f64>, EsploraError> {
        Ok(self
            .client
            .get(format!("{}/fee-estimates", self.base_url))
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }

    pub async fn get_tx_confirmations(&self, txid: &Txid) -> Result<Option<u32>, EsploraError> {
        // `/tx/:txid/status` reports an unknown txid as unconfirmed; `/tx/:txid` 404s.
        let response = self
            .client
            .get(format!("{}/tx/{txid}", self.base_url))
            .send()
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(None);
        }
        let tx = response
            .error_for_status()?
            .json::<serde_json::Value>()
            .await?;
        let status = serde_json::from_value::<ApiTxStatus>(tx["status"].clone())
            .map_err(|e| EsploraError::InvalidResponse(format!("transaction status: {e}")))?;
        let Some(block_height) = status.confirmation_height() else {
            return Ok(Some(0));
        };
        let tip = self.get_height().await?;
        Ok(Some(tip.saturating_sub(block_height) + 1))
    }

    pub async fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, EsploraError> {
        let response = self
            .client
            .get(format!("{}/tx/{txid}/hex", self.base_url))
            .send()
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(None);
        }
        let raw = response.error_for_status()?.text().await?;
        let bytes = hex::decode(raw.trim())
            .map_err(|e| EsploraError::InvalidResponse(format!("transaction hex: {e}")))?;
        let tx = encode::deserialize(&bytes)
            .map_err(|e| EsploraError::InvalidResponse(format!("transaction: {e}")))?;
        Ok(Some(tx))
    }

    pub async fn broadcast(&self, tx: &Transaction) -> Result<Txid, EsploraError> {
        let txid = tx.txid();
        self.client
            .post(format!("{}/tx", self.base_url))
            .body(hex::encode(encode::serialize(tx)))
            .send()
            .await?
            .error_for_status()?;
        Ok(txid)
    }

    pub async fn get_height(&self) -> Result<u32, EsploraError> {
        let raw = self
            .client
            .get(format!("{}/blocks/tip/height", self.base_url))
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?;
        raw.trim()
            .parse()
            .map_err(|e| EsploraError::InvalidResponse(format!("block height: {e}")))
    }

    /// Block hash at `height`, as reported by Esplora.
    pub async fn get_block_hash(&self, height: u32) -> Result<BlockHash, EsploraError> {
        let raw = self
            .client
            .get(format!("{}/block-height/{height}", self.base_url))
            .send()
            .await?
            .error_for_status()?
            .text()
            .await?;
        parse_block_hash(raw.trim(), height)
    }

    pub async fn get_outspend(
        &self,
        txid: &Txid,
        vout: u32,
    ) -> Result<Option<LiquidOutspend>, EsploraError> {
        #[derive(Debug, Deserialize)]
        struct ApiOutspend {
            spent: bool,
            txid: Option<Txid>,
            vin: Option<u32>,
        }

        let response = self
            .client
            .get(format!("{}/tx/{txid}/outspend/{vout}", self.base_url))
            .send()
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(None);
        }
        let outspend = response.error_for_status()?.json::<ApiOutspend>().await?;
        Ok(match (outspend.spent, outspend.txid, outspend.vin) {
            (true, Some(txid), Some(vin)) => Some(LiquidOutspend { txid, vin }),
            _ => None,
        })
    }

    pub async fn get_confirmation_height(&self, txid: &Txid) -> Result<Option<u32>, EsploraError> {
        self.get_tx_status_optional(txid)
            .await?
            .ok_or_else(|| EsploraError::InvalidResponse(format!("transaction {txid} not found")))
            .map(ApiTxStatus::confirmation_height)
    }

    async fn get_tx_status_optional(
        &self,
        txid: &Txid,
    ) -> Result<Option<ApiTxStatus>, EsploraError> {
        let response = self
            .client
            .get(format!("{}/tx/{txid}/status", self.base_url))
            .send()
            .await?;
        if response.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(None);
        }
        Ok(Some(response.error_for_status()?.json().await?))
    }

    pub async fn address_utxos(&self, address: &Address) -> Result<Vec<LiquidUtxo>, EsploraError> {
        #[derive(Debug, Deserialize)]
        struct ApiUtxo {
            txid: Txid,
            vout: u32,
            #[serde(default)]
            value: Option<u64>,
            #[serde(default)]
            asset: Option<AssetId>,
        }

        let utxos = self
            .client
            .get(format!("{}/address/{address}/utxo", self.base_url))
            .send()
            .await?
            .error_for_status()?
            .json::<Vec<ApiUtxo>>()
            .await?;
        Ok(utxos
            .into_iter()
            .map(|u| LiquidUtxo {
                txid: u.txid,
                vout: u.vout,
                value: u.value,
                asset: u.asset,
            })
            .collect())
    }

    /// Every transaction touching `address` with its confirmation height,
    /// newest first, paged to the end. Bodies are fetched once and kept as
    /// each arrives, so a read that fails partway leaves the next one less to
    /// fetch; an entry whose body the explorer no longer serves is skipped.
    pub async fn address_txs(
        &self,
        address: &Address,
    ) -> Result<Vec<(Transaction, Option<u32>)>, EsploraError> {
        let history = self.history(address).await?;
        let missing: Vec<Txid> = {
            let txs = self.txs.lock().unwrap_or_else(PoisonError::into_inner);
            history
                .iter()
                .map(|(txid, _)| *txid)
                .filter(|txid| !txs.contains_key(txid))
                .collect()
        };
        for txid in missing {
            if let Some(tx) = self.get_tx(&txid).await? {
                let mut txs = self.txs.lock().unwrap_or_else(PoisonError::into_inner);
                txs.insert(txid, tx);
            }
        }
        let txs = self.txs.lock().unwrap_or_else(PoisonError::into_inner);
        Ok(history
            .into_iter()
            .filter_map(|(txid, height)| txs.get(&txid).cloned().map(|tx| (tx, height)))
            .collect())
    }

    /// Txid and confirmation height of every transaction touching `address`,
    /// newest first, paged to the end.
    async fn history(&self, address: &Address) -> Result<Vec<(Txid, Option<u32>)>, EsploraError> {
        #[derive(Deserialize)]
        struct ApiTx {
            txid: Txid,
            status: ApiTxStatus,
        }

        let mut txs = Vec::new();
        let mut last_seen: Option<Txid> = None;
        loop {
            let path = match last_seen {
                Some(txid) => format!("{}/address/{address}/txs/chain/{txid}", self.base_url),
                None => format!("{}/address/{address}/txs", self.base_url),
            };
            let page: Vec<ApiTx> = self
                .client
                .get(path)
                .send()
                .await?
                .error_for_status()?
                .json()
                .await?;
            let confirmed = page.iter().filter(|tx| tx.status.confirmed).count();
            last_seen = page
                .iter()
                .rev()
                .find(|tx| tx.status.confirmed)
                .map(|tx| tx.txid);
            txs.extend(
                page.into_iter()
                    .map(|tx| (tx.txid, tx.status.confirmation_height())),
            );
            if confirmed < super::bitcoin::HISTORY_PAGE {
                return Ok(txs);
            }
        }
    }

    pub async fn get_prevout(&self, txid: &Txid, vout: u32) -> Result<TxOut, EsploraError> {
        let tx = self.get_tx(txid).await?.ok_or_else(|| {
            EsploraError::InvalidResponse(format!("transaction {txid} not found"))
        })?;
        tx.output.get(vout as usize).cloned().ok_or_else(|| {
            EsploraError::InvalidResponse(format!("output {vout} not found in {txid}"))
        })
    }
}

#[derive(Debug, Clone)]
pub struct LiquidChainClient(LiquidEsplora);

impl LiquidChainClient {
    pub fn new(url: &str) -> Self {
        Self(LiquidEsplora::new(url))
    }

    pub fn esplora(&self) -> &LiquidEsplora {
        &self.0
    }
}

#[async_trait]
impl ChainClient for LiquidChainClient {
    async fn get_fee_rate(&self, target: usize) -> Result<f64, ChainClientError> {
        Ok(self.0.get_fee_rate(target).await?)
    }

    async fn get_tx_confirmations(&self, txid: &str) -> Result<Option<u32>, ChainClientError> {
        Ok(self.0.get_tx_confirmations(&parse_txid(txid)?).await?)
    }

    async fn get_tx(&self, txid: &str) -> Result<Option<String>, ChainClientError> {
        Ok(self
            .0
            .get_tx(&parse_txid(txid)?)
            .await?
            .map(|tx| hex::encode(encode::serialize(&tx))))
    }

    async fn broadcast(&self, tx_hex: &str) -> Result<String, ChainClientError> {
        let bytes = hex::decode(tx_hex)
            .map_err(|e| ChainClientError::Other(anyhow::anyhow!("invalid Liquid tx hex: {e}")))?;
        let tx: Transaction = encode::deserialize(&bytes).map_err(|e| {
            ChainClientError::Other(anyhow::anyhow!("invalid Liquid transaction: {e}"))
        })?;
        Ok(self.0.broadcast(&tx).await?.to_string())
    }

    async fn get_height(&self) -> Result<u32, ChainClientError> {
        Ok(self.0.get_height().await?)
    }

    async fn get_confirmation_height(&self, txid: &str) -> Result<Option<u32>, ChainClientError> {
        Ok(self.0.get_confirmation_height(&parse_txid(txid)?).await?)
    }

    async fn address_utxos(&self, address: &str) -> Result<Vec<AddressUtxo>, ChainClientError> {
        let utxos = self.0.address_utxos(&parse_address(address)?).await?;
        Ok(utxos
            .into_iter()
            .map(|utxo| AddressUtxo {
                txid: utxo.txid.to_string(),
                vout: utxo.vout,
                value: utxo.value,
            })
            .collect())
    }

    async fn outpoint_spend(
        &self,
        txid: &str,
        vout: u32,
    ) -> Result<OutpointSpend, ChainClientError> {
        let Some(outspend) = self.0.get_outspend(&parse_txid(txid)?, vout).await? else {
            return Ok(OutpointSpend::Unspent);
        };
        let (spending_txid, vin) = (outspend.txid, outspend.vin);
        let confirmations = self
            .0
            .get_tx_confirmations(&spending_txid)
            .await?
            .unwrap_or(0);
        // The backend itself reported this txid as the spender, so a missing
        // body is an inconsistent backend.
        let Some(tx) = self.0.get_tx(&spending_txid).await? else {
            return Err(ChainClientError::Other(anyhow::anyhow!(
                "spending tx {spending_txid} reported by outspend but not found"
            )));
        };
        let tx_hex = hex::encode(encode::serialize(&tx));
        Ok(OutpointSpend::Spent(SpendingTx {
            txid: spending_txid.to_string(),
            vin,
            confirmations,
            tx_hex,
        }))
    }
}

fn parse_txid(txid: &str) -> Result<Txid, ChainClientError> {
    Txid::from_str(txid)
        .map_err(|e| ChainClientError::Other(anyhow::anyhow!("invalid Liquid txid {txid}: {e}")))
}

fn parse_block_hash(value: &str, height: u32) -> Result<BlockHash, EsploraError> {
    BlockHash::from_str(value)
        .map_err(|e| EsploraError::InvalidResponse(format!("block hash at height {height}: {e}")))
}

fn parse_address(address: &str) -> Result<Address, ChainClientError> {
    Address::from_str(address).map_err(|e| {
        ChainClientError::Other(anyhow::anyhow!("invalid Liquid address {address}: {e}"))
    })
}

fn convert_fee_rate(target: usize, estimates: HashMap<u16, f64>) -> Option<f64> {
    estimates
        .into_iter()
        .filter(|(blocks, rate)| *blocks as usize <= target && rate.is_finite() && *rate >= 0.0)
        .max_by_key(|(blocks, _)| *blocks)
        .map(|(_, rate)| rate)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fee_estimate_uses_largest_target_not_exceeding_request() {
        let estimates = HashMap::from([(1, 5.0), (3, 2.0), (6, 1.0)]);
        assert_eq!(convert_fee_rate(1, estimates.clone()), Some(5.0));
        assert_eq!(convert_fee_rate(2, estimates.clone()), Some(5.0));
        assert_eq!(convert_fee_rate(3, estimates.clone()), Some(2.0));
        assert_eq!(convert_fee_rate(10, estimates), Some(1.0));
    }

    #[test]
    fn fee_estimate_ignores_invalid_rates() {
        let estimates = HashMap::from([(1, -1.0), (2, f64::NAN), (3, 2.0)]);
        assert_eq!(convert_fee_rate(2, estimates), None);
        assert_eq!(convert_fee_rate(3, HashMap::from([(3, 2.0)])), Some(2.0));
    }

    #[test]
    fn api_status_maps_only_confirmed_blocks() {
        assert_eq!(
            ApiTxStatus {
                confirmed: true,
                block_height: Some(42),
            }
            .confirmation_height(),
            Some(42)
        );
        assert_eq!(
            ApiTxStatus {
                confirmed: false,
                block_height: Some(42),
            }
            .confirmation_height(),
            None
        );
    }

    #[test]
    fn block_hash_parser_reports_the_height() {
        let error = parse_block_hash("not-a-block-hash", 0).unwrap_err();
        assert!(error.to_string().contains("block hash at height 0"));
    }
}