2021-03-03 13:22:05 -08:00
|
|
|
// Bitcoin Dev Kit
|
|
|
|
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
|
2020-08-31 11:26:36 +02:00
|
|
|
//
|
2021-03-03 13:22:05 -08:00
|
|
|
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
|
2020-08-31 11:26:36 +02:00
|
|
|
//
|
2021-03-03 13:22:05 -08:00
|
|
|
// 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.
|
2020-08-31 11:26:36 +02:00
|
|
|
|
2021-06-01 16:36:09 +10:00
|
|
|
//! Esplora by way of `reqwest` HTTP client.
|
2020-09-03 11:36:07 +02:00
|
|
|
|
2020-08-07 11:23:01 +02:00
|
|
|
use std::collections::{HashMap, HashSet};
|
2020-05-07 15:14:05 +02:00
|
|
|
|
2021-06-01 16:36:09 +10:00
|
|
|
use bitcoin::consensus::{deserialize, serialize};
|
2020-12-04 10:59:06 +01:00
|
|
|
use bitcoin::hashes::hex::{FromHex, ToHex};
|
2020-05-07 15:14:05 +02:00
|
|
|
use bitcoin::hashes::{sha256, Hash};
|
2021-06-01 16:36:09 +10:00
|
|
|
use bitcoin::{BlockHeader, Script, Transaction, Txid};
|
|
|
|
|
2021-07-15 10:55:49 -07:00
|
|
|
#[allow(unused_imports)]
|
|
|
|
use log::{debug, error, info, trace};
|
2020-05-07 15:14:05 +02:00
|
|
|
|
2021-06-01 16:36:09 +10:00
|
|
|
use ::reqwest::{Client, StatusCode};
|
2021-10-29 17:41:02 +11:00
|
|
|
use futures::stream::{FuturesOrdered, TryStreamExt};
|
2021-06-01 16:36:09 +10:00
|
|
|
|
2021-10-29 17:41:02 +11:00
|
|
|
use super::api::Tx;
|
|
|
|
use crate::blockchain::esplora::EsploraError;
|
2021-06-01 16:36:09 +10:00
|
|
|
use crate::blockchain::*;
|
2020-09-03 11:36:07 +02:00
|
|
|
use crate::database::BatchDatabase;
|
2020-05-07 15:14:05 +02:00
|
|
|
use crate::error::Error;
|
2020-08-07 11:23:01 +02:00
|
|
|
use crate::FeeRate;
|
2020-05-07 15:14:05 +02:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
2020-09-03 11:36:07 +02:00
|
|
|
struct UrlClient {
|
2020-05-07 15:14:05 +02:00
|
|
|
url: String,
|
2020-07-15 18:49:24 +02:00
|
|
|
// We use the async client instead of the blocking one because it automatically uses `fetch`
|
2020-07-20 15:51:57 +02:00
|
|
|
// when the target platform is wasm32.
|
2020-05-07 15:14:05 +02:00
|
|
|
client: Client,
|
2020-11-17 09:58:29 +01:00
|
|
|
concurrency: u8,
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-09-03 11:36:07 +02:00
|
|
|
/// Structure that implements the logic to sync with Esplora
|
|
|
|
///
|
|
|
|
/// ## Example
|
|
|
|
/// See the [`blockchain::esplora`](crate::blockchain::esplora) module for a usage example.
|
2020-05-07 15:14:05 +02:00
|
|
|
#[derive(Debug)]
|
2021-07-15 10:55:49 -07:00
|
|
|
pub struct EsploraBlockchain {
|
|
|
|
url_client: UrlClient,
|
|
|
|
stop_gap: usize,
|
|
|
|
}
|
2020-05-07 15:14:05 +02:00
|
|
|
|
|
|
|
impl std::convert::From<UrlClient> for EsploraBlockchain {
|
|
|
|
fn from(url_client: UrlClient) -> Self {
|
2021-07-15 10:55:49 -07:00
|
|
|
EsploraBlockchain {
|
|
|
|
url_client,
|
|
|
|
stop_gap: 20,
|
|
|
|
}
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl EsploraBlockchain {
|
2021-06-01 16:36:09 +10:00
|
|
|
/// Create a new instance of the client from a base URL and `stop_gap`.
|
|
|
|
pub fn new(base_url: &str, stop_gap: usize) -> Self {
|
2021-07-15 10:55:49 -07:00
|
|
|
EsploraBlockchain {
|
|
|
|
url_client: UrlClient {
|
|
|
|
url: base_url.to_string(),
|
|
|
|
client: Client::new(),
|
2021-10-29 17:41:02 +11:00
|
|
|
concurrency: super::DEFAULT_CONCURRENT_REQUESTS,
|
2021-07-15 10:55:49 -07:00
|
|
|
},
|
|
|
|
stop_gap,
|
|
|
|
}
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
2021-06-01 16:36:09 +10:00
|
|
|
|
|
|
|
/// Set the concurrency to use when doing batch queries against the Esplora instance.
|
|
|
|
pub fn with_concurrency(mut self, concurrency: u8) -> Self {
|
|
|
|
self.url_client.concurrency = concurrency;
|
|
|
|
self
|
|
|
|
}
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-07-20 15:51:57 +02:00
|
|
|
#[maybe_async]
|
2020-09-09 18:17:49 +02:00
|
|
|
impl Blockchain for EsploraBlockchain {
|
2020-07-15 18:49:24 +02:00
|
|
|
fn get_capabilities(&self) -> HashSet<Capability> {
|
2020-08-25 16:07:26 +02:00
|
|
|
vec![
|
|
|
|
Capability::FullHistory,
|
|
|
|
Capability::GetAnyTx,
|
|
|
|
Capability::AccurateFees,
|
|
|
|
]
|
|
|
|
.into_iter()
|
|
|
|
.collect()
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-31 10:49:44 +02:00
|
|
|
fn setup<D: BatchDatabase, P: Progress>(
|
2020-08-06 10:44:40 +02:00
|
|
|
&self,
|
2020-05-07 15:14:05 +02:00
|
|
|
database: &mut D,
|
2021-10-29 17:41:02 +11:00
|
|
|
_progress_update: P,
|
2020-05-07 15:14:05 +02:00
|
|
|
) -> Result<(), Error> {
|
2021-10-29 17:41:02 +11:00
|
|
|
use crate::blockchain::script_sync::Request;
|
|
|
|
let mut request = script_sync::start(database, self.stop_gap)?;
|
|
|
|
let mut tx_index: HashMap<Txid, Tx> = HashMap::new();
|
|
|
|
|
|
|
|
let batch_update = loop {
|
|
|
|
request = match request {
|
|
|
|
Request::Script(script_req) => {
|
|
|
|
let futures: FuturesOrdered<_> = script_req
|
|
|
|
.request()
|
|
|
|
.take(self.url_client.concurrency as usize)
|
|
|
|
.map(|script| async move {
|
|
|
|
let mut related_txs: Vec<Tx> =
|
|
|
|
self.url_client._scripthash_txs(script, None).await?;
|
|
|
|
|
|
|
|
let n_confirmed =
|
|
|
|
related_txs.iter().filter(|tx| tx.status.confirmed).count();
|
|
|
|
// esplora pages on 25 confirmed transactions. If there's more than
|
|
|
|
// 25 we need to keep requesting.
|
|
|
|
if n_confirmed >= 25 {
|
|
|
|
loop {
|
|
|
|
let new_related_txs: Vec<Tx> = self
|
|
|
|
.url_client
|
|
|
|
._scripthash_txs(
|
|
|
|
script,
|
|
|
|
Some(related_txs.last().unwrap().txid),
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
let n = new_related_txs.len();
|
|
|
|
related_txs.extend(new_related_txs);
|
|
|
|
// we've reached the end
|
|
|
|
if n < 25 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Result::<_, Error>::Ok(related_txs)
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
let txs_per_script: Vec<Vec<Tx>> = await_or_block!(futures.try_collect())?;
|
|
|
|
let mut satisfaction = vec![];
|
|
|
|
|
|
|
|
for txs in txs_per_script {
|
|
|
|
satisfaction.push(
|
|
|
|
txs.iter()
|
|
|
|
.map(|tx| (tx.txid, tx.status.block_height))
|
|
|
|
.collect(),
|
|
|
|
);
|
|
|
|
for tx in txs {
|
|
|
|
tx_index.insert(tx.txid, tx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
script_req.satisfy(satisfaction)?
|
|
|
|
}
|
|
|
|
Request::Conftime(conftimereq) => {
|
|
|
|
let conftimes = conftimereq
|
|
|
|
.request()
|
|
|
|
.map(|txid| {
|
|
|
|
tx_index
|
|
|
|
.get(txid)
|
|
|
|
.expect("must be in index")
|
|
|
|
.confirmation_time()
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
conftimereq.satisfy(conftimes)?
|
|
|
|
}
|
|
|
|
Request::Tx(txreq) => {
|
|
|
|
let full_txs = txreq
|
|
|
|
.request()
|
|
|
|
.map(|txid| {
|
|
|
|
let tx = tx_index.get(txid).expect("must be in index");
|
|
|
|
(tx.confirmation_time(), tx.previous_outputs(), tx.to_tx())
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
txreq.satisfy(full_txs)?
|
|
|
|
}
|
|
|
|
Request::Finish(batch_update) => break batch_update,
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
database.commit_batch(batch_update)?;
|
|
|
|
|
|
|
|
Ok(())
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-06 10:44:40 +02:00
|
|
|
fn get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, Error> {
|
2021-08-31 14:26:52 +05:30
|
|
|
Ok(await_or_block!(self.url_client._get_tx(txid))?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-06 10:44:40 +02:00
|
|
|
fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
|
2021-08-31 14:26:52 +05:30
|
|
|
Ok(await_or_block!(self.url_client._broadcast(tx))?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-08 12:06:40 +02:00
|
|
|
fn get_height(&self) -> Result<u32, Error> {
|
2021-08-31 14:26:52 +05:30
|
|
|
Ok(await_or_block!(self.url_client._get_height())?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
2020-08-07 11:23:01 +02:00
|
|
|
|
|
|
|
fn estimate_fee(&self, target: usize) -> Result<FeeRate, Error> {
|
2021-08-31 14:26:52 +05:30
|
|
|
let estimates = await_or_block!(self.url_client._get_fee_estimates())?;
|
2021-07-29 09:58:47 +10:00
|
|
|
super::into_fee_rate(target, estimates)
|
2020-08-07 11:23:01 +02:00
|
|
|
}
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl UrlClient {
|
2020-07-20 15:51:57 +02:00
|
|
|
async fn _get_tx(&self, txid: &Txid) -> Result<Option<Transaction>, EsploraError> {
|
|
|
|
let resp = self
|
|
|
|
.client
|
2020-09-05 14:00:50 +10:00
|
|
|
.get(&format!("{}/tx/{}/raw", self.url, txid))
|
2020-07-20 15:51:57 +02:00
|
|
|
.send()
|
|
|
|
.await?;
|
2020-05-07 15:14:05 +02:00
|
|
|
|
|
|
|
if let StatusCode::NOT_FOUND = resp.status() {
|
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2020-07-20 15:51:57 +02:00
|
|
|
Ok(Some(deserialize(&resp.error_for_status()?.bytes().await?)?))
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-11-16 12:18:34 +01:00
|
|
|
async fn _get_tx_no_opt(&self, txid: &Txid) -> Result<Transaction, EsploraError> {
|
|
|
|
match self._get_tx(txid).await {
|
|
|
|
Ok(Some(tx)) => Ok(tx),
|
|
|
|
Ok(None) => Err(EsploraError::TransactionNotFound(*txid)),
|
|
|
|
Err(e) => Err(e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn _get_header(&self, block_height: u32) -> Result<BlockHeader, EsploraError> {
|
|
|
|
let resp = self
|
|
|
|
.client
|
|
|
|
.get(&format!("{}/block-height/{}", self.url, block_height))
|
|
|
|
.send()
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
if let StatusCode::NOT_FOUND = resp.status() {
|
|
|
|
return Err(EsploraError::HeaderHeightNotFound(block_height));
|
|
|
|
}
|
|
|
|
let bytes = resp.bytes().await?;
|
|
|
|
let hash = std::str::from_utf8(&bytes)
|
|
|
|
.map_err(|_| EsploraError::HeaderHeightNotFound(block_height))?;
|
|
|
|
|
|
|
|
let resp = self
|
|
|
|
.client
|
2020-12-04 10:59:06 +01:00
|
|
|
.get(&format!("{}/block/{}/header", self.url, hash))
|
2020-11-16 12:18:34 +01:00
|
|
|
.send()
|
|
|
|
.await?;
|
|
|
|
|
2020-12-04 10:59:06 +01:00
|
|
|
let header = deserialize(&Vec::from_hex(&resp.text().await?)?)?;
|
2020-11-16 12:18:34 +01:00
|
|
|
|
2020-12-04 10:59:06 +01:00
|
|
|
Ok(header)
|
2020-11-16 12:18:34 +01:00
|
|
|
}
|
|
|
|
|
2020-07-20 15:51:57 +02:00
|
|
|
async fn _broadcast(&self, transaction: &Transaction) -> Result<(), EsploraError> {
|
|
|
|
self.client
|
2020-09-05 14:00:50 +10:00
|
|
|
.post(&format!("{}/tx", self.url))
|
2020-07-20 15:51:57 +02:00
|
|
|
.body(serialize(transaction).to_hex())
|
|
|
|
.send()
|
|
|
|
.await?
|
2020-05-07 15:14:05 +02:00
|
|
|
.error_for_status()?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-08-08 12:06:40 +02:00
|
|
|
async fn _get_height(&self) -> Result<u32, EsploraError> {
|
2020-07-20 15:51:57 +02:00
|
|
|
let req = self
|
|
|
|
.client
|
2020-09-05 14:00:50 +10:00
|
|
|
.get(&format!("{}/blocks/tip/height", self.url))
|
2020-07-20 15:51:57 +02:00
|
|
|
.send()
|
|
|
|
.await?;
|
2020-07-15 18:49:24 +02:00
|
|
|
|
2020-07-20 15:51:57 +02:00
|
|
|
Ok(req.error_for_status()?.text().await?.parse()?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2021-10-29 17:41:02 +11:00
|
|
|
async fn _scripthash_txs(
|
2020-05-07 17:36:45 +02:00
|
|
|
&self,
|
|
|
|
script: &Script,
|
2021-10-29 17:41:02 +11:00
|
|
|
last_seen: Option<Txid>,
|
|
|
|
) -> Result<Vec<Tx>, EsploraError> {
|
|
|
|
let script_hash = sha256::Hash::hash(script.as_bytes()).into_inner().to_hex();
|
|
|
|
let url = match last_seen {
|
|
|
|
Some(last_seen) => format!(
|
|
|
|
"{}/scripthash/{}/txs/chain/{}",
|
|
|
|
self.url, script_hash, last_seen
|
|
|
|
),
|
|
|
|
None => format!("{}/scripthash/{}/txs", self.url, script_hash),
|
|
|
|
};
|
|
|
|
Ok(self
|
|
|
|
.client
|
|
|
|
.get(url)
|
|
|
|
.send()
|
|
|
|
.await?
|
|
|
|
.error_for_status()?
|
|
|
|
.json::<Vec<Tx>>()
|
|
|
|
.await?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-07 11:23:01 +02:00
|
|
|
async fn _get_fee_estimates(&self) -> Result<HashMap<String, f64>, EsploraError> {
|
|
|
|
Ok(self
|
|
|
|
.client
|
2020-09-05 14:00:50 +10:00
|
|
|
.get(&format!("{}/fee-estimates", self.url,))
|
2020-08-07 11:23:01 +02:00
|
|
|
.send()
|
|
|
|
.await?
|
|
|
|
.error_for_status()?
|
|
|
|
.json::<HashMap<String, f64>>()
|
|
|
|
.await?)
|
|
|
|
}
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-09-10 18:08:37 +02:00
|
|
|
impl ConfigurableBlockchain for EsploraBlockchain {
|
2021-10-29 17:41:02 +11:00
|
|
|
type Config = super::EsploraBlockchainConfig;
|
2020-09-10 18:08:37 +02:00
|
|
|
|
|
|
|
fn from_config(config: &Self::Config) -> Result<Self, Error> {
|
2021-08-30 15:49:07 +02:00
|
|
|
let map_e = |e: reqwest::Error| Error::Esplora(Box::new(e.into()));
|
|
|
|
|
2021-06-01 16:36:09 +10:00
|
|
|
let mut blockchain = EsploraBlockchain::new(config.base_url.as_str(), config.stop_gap);
|
|
|
|
if let Some(concurrency) = config.concurrency {
|
|
|
|
blockchain.url_client.concurrency = concurrency;
|
2021-08-30 15:49:07 +02:00
|
|
|
}
|
2021-10-29 17:41:02 +11:00
|
|
|
let mut builder = Client::builder();
|
2021-08-30 15:49:07 +02:00
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
|
|
if let Some(proxy) = &config.proxy {
|
2021-10-29 17:41:02 +11:00
|
|
|
builder = builder.proxy(reqwest::Proxy::all(proxy).map_err(map_e)?);
|
2021-08-30 15:49:07 +02:00
|
|
|
}
|
2021-10-29 17:41:02 +11:00
|
|
|
|
|
|
|
#[cfg(not(target_arch = "wasm32"))]
|
|
|
|
if let Some(timeout) = config.timeout {
|
|
|
|
builder = builder.timeout(core::time::Duration::from_secs(timeout));
|
|
|
|
}
|
|
|
|
|
|
|
|
blockchain.url_client.client = builder.build().map_err(map_e)?;
|
|
|
|
|
2021-06-01 16:36:09 +10:00
|
|
|
Ok(blockchain)
|
2020-08-31 10:49:44 +02:00
|
|
|
}
|
|
|
|
}
|