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 futures::stream::{self, FuturesOrdered, StreamExt, TryStreamExt};
|
|
|
|
|
|
|
|
use ::reqwest::{Client, StatusCode};
|
|
|
|
|
|
|
|
use crate::blockchain::esplora::{EsploraError, EsploraGetHistory};
|
|
|
|
use crate::blockchain::utils::{ElectrumLikeSync, ElsGetHistoryRes};
|
|
|
|
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-11-03 22:09:32 +01:00
|
|
|
use crate::wallet::utils::ChunksIterator;
|
2020-08-07 11:23:01 +02:00
|
|
|
use crate::FeeRate;
|
2020-05-07 15:14:05 +02:00
|
|
|
|
2020-11-17 09:58:29 +01:00
|
|
|
const DEFAULT_CONCURRENT_REQUESTS: u8 = 4;
|
2020-11-03 22:09:32 +01:00
|
|
|
|
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-06-01 16:36:09 +10:00
|
|
|
concurrency: 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,
|
|
|
|
progress_update: P,
|
|
|
|
) -> Result<(), Error> {
|
2020-07-20 15:51:57 +02:00
|
|
|
maybe_await!(self
|
2021-07-15 10:55:49 -07:00
|
|
|
.url_client
|
2021-07-15 12:04:03 -07:00
|
|
|
.electrum_like_setup(self.stop_gap, database, progress_update))
|
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-06-01 16:36:09 +10:00
|
|
|
Ok(self.url_client._get_tx(txid).await?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-06 10:44:40 +02:00
|
|
|
fn broadcast(&self, tx: &Transaction) -> Result<(), Error> {
|
2021-06-01 16:36:09 +10:00
|
|
|
Ok(self.url_client._broadcast(tx).await?)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-08-08 12:06:40 +02:00
|
|
|
fn get_height(&self) -> Result<u32, Error> {
|
2021-06-01 16:36:09 +10:00
|
|
|
Ok(self.url_client._get_height().await?)
|
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-06-01 16:36:09 +10:00
|
|
|
let estimates = self.url_client._get_fee_estimates().await?;
|
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 {
|
|
|
|
fn script_to_scripthash(script: &Script) -> String {
|
|
|
|
sha256::Hash::hash(script.as_bytes()).into_inner().to_hex()
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2020-05-07 17:36:45 +02:00
|
|
|
async fn _script_get_history(
|
|
|
|
&self,
|
|
|
|
script: &Script,
|
2021-03-30 16:33:07 +02:00
|
|
|
) -> Result<Vec<ElsGetHistoryRes>, EsploraError> {
|
2020-05-07 15:14:05 +02:00
|
|
|
let mut result = Vec::new();
|
|
|
|
let scripthash = Self::script_to_scripthash(script);
|
|
|
|
|
|
|
|
// Add the unconfirmed transactions first
|
|
|
|
result.extend(
|
|
|
|
self.client
|
|
|
|
.get(&format!(
|
2020-09-05 14:00:50 +10:00
|
|
|
"{}/scripthash/{}/txs/mempool",
|
2020-05-07 15:14:05 +02:00
|
|
|
self.url, scripthash
|
|
|
|
))
|
2020-05-07 17:36:45 +02:00
|
|
|
.send()
|
|
|
|
.await?
|
2020-05-07 15:14:05 +02:00
|
|
|
.error_for_status()?
|
2020-05-07 17:36:45 +02:00
|
|
|
.json::<Vec<EsploraGetHistory>>()
|
|
|
|
.await?
|
2020-05-07 15:14:05 +02:00
|
|
|
.into_iter()
|
2021-03-30 16:33:07 +02:00
|
|
|
.map(|x| ElsGetHistoryRes {
|
2020-05-07 15:14:05 +02:00
|
|
|
tx_hash: x.txid,
|
|
|
|
height: x.status.block_height.unwrap_or(0) as i32,
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
|
|
|
debug!(
|
|
|
|
"Found {} mempool txs for {} - {:?}",
|
|
|
|
result.len(),
|
|
|
|
scripthash,
|
|
|
|
script
|
|
|
|
);
|
|
|
|
|
|
|
|
// Then go through all the pages of confirmed transactions
|
|
|
|
let mut last_txid = String::new();
|
|
|
|
loop {
|
|
|
|
let response = self
|
|
|
|
.client
|
|
|
|
.get(&format!(
|
2020-09-05 14:00:50 +10:00
|
|
|
"{}/scripthash/{}/txs/chain/{}",
|
2020-05-07 15:14:05 +02:00
|
|
|
self.url, scripthash, last_txid
|
|
|
|
))
|
2020-05-07 17:36:45 +02:00
|
|
|
.send()
|
|
|
|
.await?
|
2020-05-07 15:14:05 +02:00
|
|
|
.error_for_status()?
|
2020-05-07 17:36:45 +02:00
|
|
|
.json::<Vec<EsploraGetHistory>>()
|
|
|
|
.await?;
|
2020-05-07 15:14:05 +02:00
|
|
|
let len = response.len();
|
|
|
|
if let Some(elem) = response.last() {
|
|
|
|
last_txid = elem.txid.to_hex();
|
|
|
|
}
|
|
|
|
|
|
|
|
debug!("... adding {} confirmed transactions", len);
|
|
|
|
|
2021-03-30 16:33:07 +02:00
|
|
|
result.extend(response.into_iter().map(|x| ElsGetHistoryRes {
|
2020-05-07 15:14:05 +02:00
|
|
|
tx_hash: x.txid,
|
|
|
|
height: x.status.block_height.unwrap_or(0) as i32,
|
|
|
|
}));
|
|
|
|
|
|
|
|
if len < 25 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(result)
|
|
|
|
}
|
|
|
|
|
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-07-20 15:51:57 +02:00
|
|
|
#[maybe_async]
|
2020-05-07 15:14:05 +02:00
|
|
|
impl ElectrumLikeSync for UrlClient {
|
2020-07-15 18:49:24 +02:00
|
|
|
fn els_batch_script_get_history<'s, I: IntoIterator<Item = &'s Script>>(
|
2020-08-06 10:44:40 +02:00
|
|
|
&self,
|
2020-05-07 15:14:05 +02:00
|
|
|
scripts: I,
|
2021-03-30 16:33:07 +02:00
|
|
|
) -> Result<Vec<Vec<ElsGetHistoryRes>>, Error> {
|
2021-06-01 16:36:09 +10:00
|
|
|
let mut results = vec![];
|
|
|
|
for chunk in ChunksIterator::new(scripts.into_iter(), self.concurrency as usize) {
|
|
|
|
let mut futs = FuturesOrdered::new();
|
|
|
|
for script in chunk {
|
|
|
|
futs.push(self._script_get_history(script));
|
2020-11-03 22:09:32 +01:00
|
|
|
}
|
2021-06-01 16:36:09 +10:00
|
|
|
let partial_results: Vec<Vec<ElsGetHistoryRes>> = futs.try_collect().await?;
|
|
|
|
results.extend(partial_results);
|
|
|
|
}
|
|
|
|
Ok(stream::iter(results).collect().await)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-11-16 12:18:34 +01:00
|
|
|
fn els_batch_transaction_get<'s, I: IntoIterator<Item = &'s Txid>>(
|
2020-08-06 10:44:40 +02:00
|
|
|
&self,
|
2020-11-16 12:18:34 +01:00
|
|
|
txids: I,
|
|
|
|
) -> Result<Vec<Transaction>, Error> {
|
2021-06-01 16:36:09 +10:00
|
|
|
let mut results = vec![];
|
|
|
|
for chunk in ChunksIterator::new(txids.into_iter(), self.concurrency as usize) {
|
|
|
|
let mut futs = FuturesOrdered::new();
|
|
|
|
for txid in chunk {
|
|
|
|
futs.push(self._get_tx_no_opt(txid));
|
2020-11-03 22:09:32 +01:00
|
|
|
}
|
2021-06-01 16:36:09 +10:00
|
|
|
let partial_results: Vec<Transaction> = futs.try_collect().await?;
|
|
|
|
results.extend(partial_results);
|
|
|
|
}
|
|
|
|
Ok(stream::iter(results).collect().await)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
|
2020-11-16 12:18:34 +01:00
|
|
|
fn els_batch_block_header<I: IntoIterator<Item = u32>>(
|
|
|
|
&self,
|
|
|
|
heights: I,
|
|
|
|
) -> Result<Vec<BlockHeader>, Error> {
|
2021-06-01 16:36:09 +10:00
|
|
|
let mut results = vec![];
|
|
|
|
for chunk in ChunksIterator::new(heights.into_iter(), self.concurrency as usize) {
|
|
|
|
let mut futs = FuturesOrdered::new();
|
|
|
|
for height in chunk {
|
|
|
|
futs.push(self._get_header(height));
|
2020-11-03 22:09:32 +01:00
|
|
|
}
|
2021-06-01 16:36:09 +10:00
|
|
|
let partial_results: Vec<BlockHeader> = futs.try_collect().await?;
|
|
|
|
results.extend(partial_results);
|
|
|
|
}
|
|
|
|
Ok(stream::iter(results).collect().await)
|
2020-05-07 15:14:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-10 18:08:37 +02:00
|
|
|
/// Configuration for an [`EsploraBlockchain`]
|
2021-03-25 16:28:38 +11:00
|
|
|
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq)]
|
2020-09-10 18:08:37 +02:00
|
|
|
pub struct EsploraBlockchainConfig {
|
2020-11-27 11:10:10 +01:00
|
|
|
/// Base URL of the esplora service
|
|
|
|
///
|
|
|
|
/// eg. `https://blockstream.info/api/`
|
2020-09-10 18:08:37 +02:00
|
|
|
pub base_url: String,
|
2020-11-27 11:10:10 +01:00
|
|
|
/// Number of parallel requests sent to the esplora service (default: 4)
|
2020-11-17 09:58:29 +01:00
|
|
|
pub concurrency: Option<u8>,
|
2021-06-01 16:36:09 +10:00
|
|
|
/// Stop searching addresses for transactions after finding an unused gap of this length.
|
2021-07-15 10:55:49 -07:00
|
|
|
pub stop_gap: usize,
|
2020-09-10 18:08:37 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ConfigurableBlockchain for EsploraBlockchain {
|
|
|
|
type Config = EsploraBlockchainConfig;
|
|
|
|
|
|
|
|
fn from_config(config: &Self::Config) -> Result<Self, Error> {
|
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;
|
|
|
|
};
|
|
|
|
Ok(blockchain)
|
2020-08-31 10:49:44 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-17 13:48:46 +02:00
|
|
|
#[cfg(test)]
|
2021-06-28 15:04:17 +02:00
|
|
|
#[cfg(feature = "test-esplora")]
|
2021-05-19 13:04:32 +10:00
|
|
|
crate::bdk_blockchain_tests! {
|
2021-06-17 13:48:46 +02:00
|
|
|
fn test_instance(test_client: &TestClient) -> EsploraBlockchain {
|
2021-07-15 12:04:03 -07:00
|
|
|
EsploraBlockchain::new(&format!("http://{}",test_client.electrsd.esplora_url.as_ref().unwrap()), None, 20)
|
2021-05-18 15:21:48 +10:00
|
|
|
}
|
|
|
|
}
|