Skip to main content

smplx_sdk_test/provider/
esplora.rs

1use std::collections::HashMap;
2use std::collections::HashSet;
3use std::str::FromStr;
4use std::time::Duration;
5
6use simplicityhl::elements::hashes::{Hash, sha256};
7
8use simplicityhl::elements::encode;
9use simplicityhl::elements::{Address, OutPoint, Script, Transaction, Txid};
10
11use serde::Deserialize;
12
13use crate::provider::SimplicityNetwork;
14use crate::transaction::{TxReceipt, UTXO};
15
16use super::core::{DEFAULT_ESPLORA_TIMEOUT_SECS, ProviderTrait};
17use super::error::ProviderError;
18
19/// A provider implementation that interacts with the Esplora REST API backend.
20#[derive(Debug)]
21pub struct EsploraProvider {
22    /// The base URL of the Esplora REST API.
23    pub esplora_url: String,
24    /// The currently configured Simplicity network (e.g. Liquid, Testnet, Regtest).
25    pub network: SimplicityNetwork,
26    /// Timeout duration used in underlying HTTP requests.
27    pub timeout: Duration,
28}
29
30#[derive(Deserialize)]
31#[allow(dead_code)]
32struct TxStatus {
33    confirmed: bool,
34    block_height: Option<u32>,
35}
36
37#[derive(Deserialize)]
38#[allow(dead_code)]
39struct EsploraBlock {
40    id: String,
41    height: u32,
42    timestamp: u64,
43    tx_count: u32,
44}
45
46#[derive(Clone, Deserialize)]
47#[allow(dead_code)]
48struct UtxoStatus {
49    pub confirmed: bool,
50    pub block_height: Option<u64>,
51    pub block_hash: Option<String>,
52    pub block_time: Option<u64>,
53}
54
55#[derive(Clone, Deserialize)]
56#[allow(dead_code)]
57struct EsploraUtxo {
58    pub txid: String,
59    pub vout: u32,
60    pub value: Option<u64>,
61    pub valuecommitment: Option<String>,
62    pub asset: Option<String>,
63    pub assetcommitment: Option<String>,
64    pub status: UtxoStatus,
65}
66
67impl EsploraProvider {
68    /// Creates a new `EsploraProvider` connected to the provided endpoint targeting the specific network.
69    #[must_use]
70    pub fn new(url: String, network: SimplicityNetwork) -> Self {
71        Self {
72            esplora_url: url,
73            network,
74            timeout: Duration::from_secs(DEFAULT_ESPLORA_TIMEOUT_SECS),
75        }
76    }
77
78    fn esplora_utxo_to_outpoint(utxo: &EsploraUtxo) -> Result<OutPoint, ProviderError> {
79        let txid = Txid::from_str(&utxo.txid).map_err(|e| ProviderError::InvalidTxid(e.to_string()))?;
80
81        Ok(OutPoint::new(txid, utxo.vout))
82    }
83
84    fn populate_txouts_from_outpoints(&self, outpoints: &[OutPoint]) -> Result<Vec<UTXO>, ProviderError> {
85        let set: HashSet<_> = outpoints.iter().collect();
86        let mut map = HashMap::new();
87
88        // filter unique transactions
89        for point in set {
90            let tx = self.fetch_transaction(&point.txid)?;
91            map.insert(point.txid, tx);
92        }
93
94        let mut utxos = Vec::with_capacity(outpoints.len());
95
96        for point in outpoints {
97            let txout = map
98                .get(&point.txid)
99                .unwrap()
100                .output
101                .get(point.vout as usize)
102                .ok_or_else(ProviderError::BadResponse)?;
103
104            utxos.push(UTXO {
105                outpoint: *point,
106                txout: txout.clone(),
107                secrets: None,
108            });
109        }
110
111        Ok(utxos)
112    }
113}
114
115impl ProviderTrait for EsploraProvider {
116    fn get_network(&self) -> &SimplicityNetwork {
117        &self.network
118    }
119
120    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
121    fn broadcast_transaction(&self, tx: &Transaction) -> Result<TxReceipt<'_>, ProviderError> {
122        let tx_hex = encode::serialize_hex(tx);
123        let url = format!("{}/tx", self.esplora_url);
124        let timeout_secs = self.timeout.as_secs();
125
126        let response = minreq::post(&url)
127            .with_timeout(timeout_secs)
128            .with_body(tx_hex)
129            .send()
130            .map_err(|e| ProviderError::Request(e.to_string()))?;
131
132        let status = response.status_code;
133        let body = response.as_str().unwrap_or("").trim().to_owned();
134
135        if !(200..300).contains(&status) {
136            return Err(ProviderError::BroadcastRejected {
137                status: status as u16,
138                url: format!("{}/tx", self.esplora_url),
139                message: body,
140            });
141        }
142
143        Txid::from_str(&body)
144            .map_err(|e| ProviderError::InvalidTxid(e.to_string()))
145            .map(|tx_id| TxReceipt::new(self, tx_id))
146    }
147
148    fn wait(&self, txid: &Txid) -> Result<(), ProviderError> {
149        let url = format!("{}/tx/{}/status", self.esplora_url, txid);
150        let timeout_secs = self.timeout.as_secs();
151
152        let confirmation_poll = match self.network {
153            SimplicityNetwork::ElementsRegtest { .. } => Duration::from_millis(100),
154            _ => Duration::from_secs(10),
155        };
156
157        // polling needs to be > 1 min on mainnet/testnet
158        for _ in 1..10 {
159            let response = minreq::get(&url)
160                .with_timeout(timeout_secs)
161                .send()
162                .map_err(|e| ProviderError::Request(e.to_string()))?;
163
164            if response.status_code != 200 {
165                std::thread::sleep(confirmation_poll);
166                continue;
167            }
168
169            let status: TxStatus = response.json().map_err(|e| ProviderError::Deserialize(e.to_string()))?;
170
171            if status.confirmed {
172                return Ok(());
173            }
174
175            std::thread::sleep(confirmation_poll);
176        }
177
178        Err(ProviderError::Confirmation())
179    }
180
181    fn fetch_tip_height(&self) -> Result<u32, ProviderError> {
182        let url = format!("{}/blocks/tip/height", self.esplora_url);
183        let timeout_secs = self.timeout.as_secs();
184
185        let response = minreq::get(&url)
186            .with_timeout(timeout_secs)
187            .send()
188            .map_err(|e| ProviderError::Request(e.to_string()))?;
189
190        if response.status_code != 200 {
191            return Err(ProviderError::Request(format!(
192                "HTTP {}: {}",
193                response.status_code, response.reason_phrase
194            )));
195        }
196
197        let body_str = response
198            .as_str()
199            .map_err(|e| ProviderError::Deserialize(e.to_string()))?;
200
201        let height: u32 = body_str
202            .trim()
203            .parse()
204            .map_err(|e: std::num::ParseIntError| ProviderError::Deserialize(e.to_string()))?;
205
206        Ok(height)
207    }
208
209    fn fetch_tip_block_hash(&self) -> Result<String, ProviderError> {
210        let url = format!("{}/blocks/tip/hash", self.esplora_url);
211        let timeout_secs = self.timeout.as_secs();
212
213        let response = minreq::get(&url)
214            .with_timeout(timeout_secs)
215            .send()
216            .map_err(|e| ProviderError::Request(e.to_string()))?;
217
218        if response.status_code != 200 {
219            return Err(ProviderError::Request(format!(
220                "HTTP {}: {}",
221                response.status_code, response.reason_phrase
222            )));
223        }
224
225        let tip_block_hash = response
226            .as_str()
227            .map_err(|e| ProviderError::Deserialize(e.to_string()))?
228            .trim();
229
230        Ok(tip_block_hash.into())
231    }
232
233    fn fetch_tip_timestamp(&self) -> Result<u64, ProviderError> {
234        let tip_hash = self.fetch_tip_block_hash()?;
235
236        let url = format!("{}/block/{}", self.esplora_url, tip_hash);
237        let timeout_secs = self.timeout.as_secs();
238
239        let response = minreq::get(&url)
240            .with_timeout(timeout_secs)
241            .send()
242            .map_err(|e| ProviderError::Request(e.to_string()))?;
243
244        if response.status_code != 200 {
245            return Err(ProviderError::Request(format!(
246                "HTTP {}: {}",
247                response.status_code, response.reason_phrase
248            )));
249        }
250
251        let block: EsploraBlock = response.json().map_err(|e| ProviderError::Deserialize(e.to_string()))?;
252
253        Ok(block.timestamp)
254    }
255
256    fn fetch_block_hash_at_height(&self, block_height: u32) -> Result<String, ProviderError> {
257        let url = format!("{}/block-height/{}", self.esplora_url, block_height);
258        let timeout_secs = self.timeout.as_secs();
259
260        let response = minreq::get(&url)
261            .with_timeout(timeout_secs)
262            .send()
263            .map_err(|e| ProviderError::Request(e.to_string()))?;
264
265        if response.status_code != 200 {
266            return Err(ProviderError::Request(format!(
267                "HTTP {}: {}",
268                response.status_code, response.reason_phrase
269            )));
270        }
271
272        let block_hash = response
273            .as_str()
274            .map_err(|e| ProviderError::Deserialize(e.to_string()))?
275            .trim();
276
277        Ok(block_hash.into())
278    }
279
280    fn fetch_block_txids(&self, block_hash: &str) -> Result<Vec<Txid>, ProviderError> {
281        let url = format!("{}/block/{}/txids", self.esplora_url, block_hash);
282        let timeout_secs = self.timeout.as_secs();
283
284        let response = minreq::get(&url)
285            .with_timeout(timeout_secs)
286            .send()
287            .map_err(|e| ProviderError::Request(e.to_string()))?;
288
289        if response.status_code != 200 {
290            return Err(ProviderError::Request(format!(
291                "HTTP {}: {}",
292                response.status_code, response.reason_phrase
293            )));
294        }
295
296        let block_txids: Vec<Txid> = response.json().map_err(|e| ProviderError::Deserialize(e.to_string()))?;
297
298        Ok(block_txids)
299    }
300
301    fn fetch_transaction(&self, txid: &Txid) -> Result<Transaction, ProviderError> {
302        let url = format!("{}/tx/{}/raw", self.esplora_url, txid);
303        let timeout_secs = self.timeout.as_secs();
304
305        let response = minreq::get(&url)
306            .with_timeout(timeout_secs)
307            .send()
308            .map_err(|e| ProviderError::Request(e.to_string()))?;
309
310        if response.status_code != 200 {
311            return Err(ProviderError::Request(format!(
312                "HTTP {}: {}",
313                response.status_code, response.reason_phrase
314            )));
315        }
316
317        let bytes = response.as_bytes();
318        let tx: Transaction = encode::deserialize(bytes).map_err(|e| ProviderError::Deserialize(e.to_string()))?;
319
320        Ok(tx)
321    }
322
323    fn fetch_address_utxos(&self, address: &Address) -> Result<Vec<UTXO>, ProviderError> {
324        let url = format!("{}/address/{}/utxo", self.esplora_url, address);
325        let timeout_secs = self.timeout.as_secs();
326
327        let response = minreq::get(&url)
328            .with_timeout(timeout_secs)
329            .send()
330            .map_err(|e| ProviderError::Request(e.to_string()))?;
331
332        if response.status_code != 200 {
333            return Err(ProviderError::Request(format!(
334                "HTTP {}: {}",
335                response.status_code, response.reason_phrase
336            )));
337        }
338
339        let utxos: Vec<EsploraUtxo> = response.json().map_err(|e| ProviderError::Deserialize(e.to_string()))?;
340        let outpoints = utxos
341            .iter()
342            .map(Self::esplora_utxo_to_outpoint)
343            .collect::<Result<Vec<OutPoint>, ProviderError>>()?;
344
345        self.populate_txouts_from_outpoints(&outpoints)
346    }
347
348    fn fetch_scripthash_utxos(&self, script: &Script) -> Result<Vec<UTXO>, ProviderError> {
349        let hash = sha256::Hash::hash(script.as_bytes());
350        let hash_bytes = hash.to_byte_array();
351        let scripthash = hex::encode(hash_bytes);
352
353        let url = format!("{}/scripthash/{}/utxo", self.esplora_url, scripthash);
354        let timeout_secs = self.timeout.as_secs();
355
356        let response = minreq::get(&url)
357            .with_timeout(timeout_secs)
358            .send()
359            .map_err(|e| ProviderError::Request(e.to_string()))?;
360
361        if response.status_code != 200 {
362            return Err(ProviderError::Request(format!(
363                "HTTP {}: {}",
364                response.status_code, response.reason_phrase
365            )));
366        }
367
368        let utxos: Vec<EsploraUtxo> = response.json().map_err(|e| ProviderError::Deserialize(e.to_string()))?;
369        let outpoints = utxos
370            .iter()
371            .map(Self::esplora_utxo_to_outpoint)
372            .collect::<Result<Vec<OutPoint>, ProviderError>>()?;
373
374        self.populate_txouts_from_outpoints(&outpoints)
375    }
376
377    fn fetch_fee_estimates(&self) -> Result<HashMap<String, f64>, ProviderError> {
378        let url = format!("{}/fee-estimates", self.esplora_url);
379        let timeout_secs = self.timeout.as_secs();
380
381        let response = minreq::get(&url)
382            .with_timeout(timeout_secs)
383            .send()
384            .map_err(|e| ProviderError::Request(e.to_string()))?;
385
386        if response.status_code != 200 {
387            return Err(ProviderError::Request(format!(
388                "HTTP {}: {}",
389                response.status_code, response.reason_phrase
390            )));
391        }
392
393        let estimates: HashMap<String, f64> = response.json().map_err(|e| ProviderError::Deserialize(e.to_string()))?;
394
395        Ok(estimates)
396    }
397}