#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
use web_time::{SystemTime, UNIX_EPOCH};
use std::fmt;
use serde::de::DeserializeOwned;
use crate::{
chains::bitcoin::{EsploraClient, EsploraConfig, TransactionReader},
config::HttpConfig,
domain::{
Source, Timestamp,
bitcoin::{
BlockHash, NetworkId, Observation as BitcoinObservation, Transaction,
TransactionStatus, Txid,
},
mempool_space::{
Context, MempoolSummary, Observation, Operation, RecentTransactions, RecommendedFees,
TransactionIds, TransactionLimit,
},
},
error::{Error, ProviderError},
transport::{HttpClient, OperationBudget},
};
use super::{MempoolSpaceReader, wire};
#[derive(Clone, Debug)]
pub struct MempoolSpaceHttpConfig {
network: NetworkId,
http: HttpConfig,
}
impl MempoolSpaceHttpConfig {
#[must_use]
pub const fn new(network: NetworkId, http: HttpConfig) -> Self {
Self { network, http }
}
#[must_use]
pub const fn network(&self) -> &NetworkId {
&self.network
}
#[must_use]
pub const fn http_config(&self) -> &HttpConfig {
&self.http
}
}
pub struct MempoolSpaceClient {
config: MempoolSpaceHttpConfig,
http: HttpClient,
bitcoin: EsploraClient,
}
impl fmt::Debug for MempoolSpaceClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MempoolSpaceClient")
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl MempoolSpaceClient {
pub async fn connect(config: MempoolSpaceHttpConfig) -> Result<Self, Error> {
let budget = OperationBudget::new(config.http_config().limits())?;
budget
.run(async {
let http = HttpClient::new(config.http_config())?;
let bitcoin = EsploraClient::connect(EsploraConfig::new(
config.network().clone(),
config.http_config().clone(),
))
.await?;
Ok(Self {
config,
http,
bitcoin,
})
})
.await
}
#[must_use]
pub const fn config(&self) -> &MempoolSpaceHttpConfig {
&self.config
}
pub async fn get_mempool_summary(&self) -> Result<Observation<MempoolSummary>, Error> {
let budget = OperationBudget::new(self.config.http_config().limits())?;
budget
.run(async {
self.verify_genesis(&budget).await?;
let value: wire::Summary = self.read(&["mempool"], &budget).await?;
Observation::summary(
value.into_domain()?,
self.context(Operation::Summary, "mempool")?,
)
.map_err(|_| wire::invalid())
})
.await
}
pub async fn get_recent_transactions(&self) -> Result<Observation<RecentTransactions>, Error> {
let budget = OperationBudget::new(self.config.http_config().limits())?;
budget
.run(async {
self.verify_genesis(&budget).await?;
let values = self.read(&["mempool", "recent"], &budget).await?;
Observation::recent_transactions(
wire::recent(values)?,
self.context(Operation::RecentTransactions, "mempool-recent")?,
)
.map_err(|_| wire::invalid())
})
.await
}
pub async fn get_mempool_txids(
&self,
limit: TransactionLimit,
) -> Result<Observation<TransactionIds>, Error> {
let budget = OperationBudget::new(self.config.http_config().limits())?;
budget
.run(async {
self.verify_genesis(&budget).await?;
let values = self.read(&["mempool", "txids"], &budget).await?;
Observation::transaction_ids(
wire::txids(values, limit)?,
self.context(Operation::TransactionIds { limit }, "mempool-txids")?,
)
.map_err(|_| wire::invalid())
})
.await
}
pub async fn get_recommended_fees(&self) -> Result<Observation<RecommendedFees>, Error> {
let budget = OperationBudget::new(self.config.http_config().limits())?;
budget
.run(async {
self.verify_genesis(&budget).await?;
let values: wire::Fees = self.read(&["v1", "fees", "recommended"], &budget).await?;
Observation::recommended_fees(
values.into_domain()?,
self.context(Operation::RecommendedFees, "fees-recommended")?,
)
.map_err(|_| wire::invalid())
})
.await
}
pub async fn get_transaction(
&self,
txid: Txid,
) -> Result<BitcoinObservation<Transaction>, Error> {
self.bitcoin.get_transaction(txid).await
}
pub async fn get_transaction_status(
&self,
txid: Txid,
) -> Result<BitcoinObservation<TransactionStatus>, Error> {
self.bitcoin.get_transaction_status(txid).await
}
async fn verify_genesis(&self, budget: &OperationBudget) -> Result<(), Error> {
let bytes = self
.http
.read(&["block-height", "0"], &[], None, budget)
.await?
.into_success()?;
let hash = std::str::from_utf8(&bytes)
.map_err(|_| wire::invalid())
.and_then(|value| BlockHash::parse(value).map_err(|_| wire::invalid()))?;
if &hash != self.config.network().genesis_hash() {
return Err(Error::Provider(ProviderError::ChainMismatch));
}
Ok(())
}
async fn read<T: DeserializeOwned>(
&self,
path: &[&str],
budget: &OperationBudget,
) -> Result<T, Error> {
let bytes = self
.http
.read(path, &[], None, budget)
.await?
.into_success()?;
wire::decode(&bytes)
}
fn context(&self, operation: Operation, method: &str) -> Result<Context, Error> {
let time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| Error::Configuration)?
.as_secs();
Ok(Context::new(
self.config.network().clone(),
operation,
Source::new(
self.config.http_config().provider_id(),
method,
env!("CARGO_PKG_VERSION"),
)?,
Timestamp::from_unix_seconds(time),
))
}
}
impl MempoolSpaceReader for MempoolSpaceClient {
async fn get_mempool_summary(&self) -> Result<Observation<MempoolSummary>, Error> {
Self::get_mempool_summary(self).await
}
async fn get_recent_transactions(&self) -> Result<Observation<RecentTransactions>, Error> {
Self::get_recent_transactions(self).await
}
async fn get_mempool_txids(
&self,
limit: TransactionLimit,
) -> Result<Observation<TransactionIds>, Error> {
Self::get_mempool_txids(self, limit).await
}
async fn get_recommended_fees(&self) -> Result<Observation<RecommendedFees>, Error> {
Self::get_recommended_fees(self).await
}
async fn get_transaction(&self, txid: Txid) -> Result<BitcoinObservation<Transaction>, Error> {
Self::get_transaction(self, txid).await
}
async fn get_transaction_status(
&self,
txid: Txid,
) -> Result<BitcoinObservation<TransactionStatus>, Error> {
Self::get_transaction_status(self, txid).await
}
}
impl TransactionReader for MempoolSpaceClient {
async fn get_transaction(&self, txid: Txid) -> Result<BitcoinObservation<Transaction>, Error> {
Self::get_transaction(self, txid).await
}
}