forked from bitcoindevkit/rust-esplora-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync.rs
420 lines (365 loc) · 13.7 KB
/
async.rs
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
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <[email protected]>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Esplora by way of `reqwest` HTTP client.
use std::collections::HashMap;
use std::str::FromStr;
use bitcoin::consensus::{deserialize, serialize};
use bitcoin::hashes::{sha256, Hash};
use bitcoin::hex::{DisplayHex, FromHex};
use bitcoin::{
block::Header as BlockHeader, Block, BlockHash, MerkleBlock, Script, Transaction, Txid,
};
#[allow(unused_imports)]
use log::{debug, error, info, trace};
use reqwest::{Client, StatusCode};
use crate::{BlockStatus, BlockSummary, Builder, Error, MerkleProof, OutputStatus, Tx, TxStatus};
#[derive(Debug, Clone)]
pub struct AsyncClient {
url: String,
client: Client,
}
impl AsyncClient {
/// build an async client from a builder
pub fn from_builder(builder: Builder) -> Result<Self, Error> {
let mut client_builder = Client::builder();
#[cfg(not(target_arch = "wasm32"))]
if let Some(proxy) = &builder.proxy {
client_builder = client_builder.proxy(reqwest::Proxy::all(proxy)?);
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(timeout) = builder.timeout {
client_builder = client_builder.timeout(core::time::Duration::from_secs(timeout));
}
Ok(Self::from_client(builder.base_url, client_builder.build()?))
}
/// build an async client from the base url and [`Client`]
pub fn from_client(url: String, client: Client) -> Self {
AsyncClient { url, client }
}
/// Get a [`Transaction`] option given its [`Txid`]
pub async fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
let resp = self
.client
.get(&format!("{}/tx/{}/raw", self.url, txid))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Ok(None);
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(Some(deserialize(&resp.bytes().await?)?))
}
}
/// Get a [`Transaction`] given its [`Txid`].
pub async fn get_tx_no_opt(&self, txid: &Txid) -> Result<Transaction, Error> {
match self.get_tx(txid).await {
Ok(Some(tx)) => Ok(tx),
Ok(None) => Err(Error::TransactionNotFound(*txid)),
Err(e) => Err(e),
}
}
/// Get a [`Txid`] of a transaction given its index in a block with a given hash.
pub async fn get_txid_at_block_index(
&self,
block_hash: &BlockHash,
index: usize,
) -> Result<Option<Txid>, Error> {
let resp = self
.client
.get(&format!("{}/block/{}/txid/{}", self.url, block_hash, index))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Ok(None);
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(Some(Txid::from_str(&resp.text().await?)?))
}
}
/// Get the status of a [`Transaction`] given its [`Txid`].
pub async fn get_tx_status(&self, txid: &Txid) -> Result<TxStatus, Error> {
let resp = self
.client
.get(&format!("{}/tx/{}/status", self.url, txid))
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(resp.json().await?)
}
}
/// Get a [`BlockHeader`] given a particular block hash.
pub async fn get_header_by_hash(&self, block_hash: &BlockHash) -> Result<BlockHeader, Error> {
let resp = self
.client
.get(&format!("{}/block/{}/header", self.url, block_hash))
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
let header = deserialize(&Vec::from_hex(&resp.text().await?)?)?;
Ok(header)
}
}
/// Get the [`BlockStatus`] given a particular [`BlockHash`].
pub async fn get_block_status(&self, block_hash: &BlockHash) -> Result<BlockStatus, Error> {
let resp = self
.client
.get(&format!("{}/block/{}/status", self.url, block_hash))
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(resp.json().await?)
}
}
/// Get a [`Block`] given a particular [`BlockHash`].
pub async fn get_block_by_hash(&self, block_hash: &BlockHash) -> Result<Option<Block>, Error> {
let resp = self
.client
.get(&format!("{}/block/{}/raw", self.url, block_hash))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Ok(None);
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(Some(deserialize(&resp.bytes().await?)?))
}
}
/// Get a merkle inclusion proof for a [`Transaction`] with the given [`Txid`].
pub async fn get_merkle_proof(&self, tx_hash: &Txid) -> Result<Option<MerkleProof>, Error> {
let resp = self
.client
.get(&format!("{}/tx/{}/merkle-proof", self.url, tx_hash))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Ok(None);
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(Some(resp.json().await?))
}
}
/// Get a [`MerkleBlock`] inclusion proof for a [`Transaction`] with the given [`Txid`].
pub async fn get_merkle_block(&self, tx_hash: &Txid) -> Result<Option<MerkleBlock>, Error> {
let resp = self
.client
.get(&format!("{}/tx/{}/merkleblock-proof", self.url, tx_hash))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Ok(None);
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
let merkle_block = deserialize(&Vec::from_hex(&resp.text().await?)?)?;
Ok(Some(merkle_block))
}
}
/// Get the spending status of an output given a [`Txid`] and the output index.
pub async fn get_output_status(
&self,
txid: &Txid,
index: u64,
) -> Result<Option<OutputStatus>, Error> {
let resp = self
.client
.get(&format!("{}/tx/{}/outspend/{}", self.url, txid, index))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Ok(None);
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(Some(resp.json().await?))
}
}
/// Broadcast a [`Transaction`] to Esplora
pub async fn broadcast(&self, transaction: &Transaction) -> Result<(), Error> {
let resp = self
.client
.post(&format!("{}/tx", self.url))
.body(serialize(transaction).to_lower_hex_string())
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(())
}
}
/// Get the current height of the blockchain tip
pub async fn get_height(&self) -> Result<u32, Error> {
let resp = self
.client
.get(&format!("{}/blocks/tip/height", self.url))
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(resp.text().await?.parse()?)
}
}
/// Get the [`BlockHash`] of the current blockchain tip.
pub async fn get_tip_hash(&self) -> Result<BlockHash, Error> {
let resp = self
.client
.get(&format!("{}/blocks/tip/hash", self.url))
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(BlockHash::from_str(&resp.text().await?)?)
}
}
/// Get the [`BlockHash`] of a specific block height
pub async fn get_block_hash(&self, block_height: u32) -> Result<BlockHash, Error> {
let resp = self
.client
.get(&format!("{}/block-height/{}", self.url, block_height))
.send()
.await?;
if let StatusCode::NOT_FOUND = resp.status() {
return Err(Error::HeaderHeightNotFound(block_height));
}
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(BlockHash::from_str(&resp.text().await?)?)
}
}
/// Get confirmed transaction history for the specified address/scripthash,
/// sorted with newest first. Returns 25 transactions per page.
/// More can be requested by specifying the last txid seen by the previous query.
pub async fn scripthash_txs(
&self,
script: &Script,
last_seen: Option<Txid>,
) -> Result<Vec<Tx>, Error> {
let script_hash = sha256::Hash::hash(script.as_bytes());
let url = match last_seen {
Some(last_seen) => format!(
"{}/scripthash/{:x}/txs/chain/{}",
self.url, script_hash, last_seen
),
None => format!("{}/scripthash/{:x}/txs", self.url, script_hash),
};
let resp = self.client.get(url).send().await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(resp.json::<Vec<Tx>>().await?)
}
}
/// Get an map where the key is the confirmation target (in number of blocks)
/// and the value is the estimated feerate (in sat/vB).
pub async fn get_fee_estimates(&self) -> Result<HashMap<String, f64>, Error> {
let resp = self
.client
.get(&format!("{}/fee-estimates", self.url,))
.send()
.await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(resp.json::<HashMap<String, f64>>().await?)
}
}
/// Gets some recent block summaries starting at the tip or at `height` if provided.
///
/// The maximum number of summaries returned depends on the backend itself: esplora returns `10`
/// while [mempool.space](https://mempool.space/docs/api) returns `15`.
pub async fn get_blocks(&self, height: Option<u32>) -> Result<Vec<BlockSummary>, Error> {
let url = match height {
Some(height) => format!("{}/blocks/{}", self.url, height),
None => format!("{}/blocks", self.url),
};
let resp = self.client.get(&url).send().await?;
if resp.status().is_server_error() || resp.status().is_client_error() {
Err(Error::HttpResponse {
status: resp.status().as_u16(),
message: resp.text().await?,
})
} else {
Ok(resp.json::<Vec<BlockSummary>>().await?)
}
}
/// Get the underlying base URL.
pub fn url(&self) -> &str {
&self.url
}
/// Get the underlying [`Client`].
pub fn client(&self) -> &Client {
&self.client
}
}