1
2
3use std::borrow::Borrow;
4use std::collections::{HashMap, HashSet};
5use std::str::FromStr as _;
6
7use anyhow::Context;
8use bdk_core::{BlockId, CheckPoint};
9use bdk_esplora::esplora_client;
10use bitcoin::constants::genesis_block;
11use bitcoin::{
12 Amount, Block, BlockHash, FeeRate, Network, OutPoint, Transaction, Txid, Weight, Wtxid,
13};
14use log::{debug, info, warn};
15use tokio::sync::RwLock;
16
17use bitcoin_ext::{BlockHeight, BlockRef, FeeRateExt, TxStatus};
18use bitcoin_ext::rpc::{self, BitcoinRpcExt, BitcoinRpcErrorExt, RpcApi};
19use bitcoin_ext::esplora::EsploraClientExt;
20
21const FEE_RATE_TARGET_CONF_FAST: u16 = 1;
22const FEE_RATE_TARGET_CONF_REGULAR: u16 = 3;
23const FEE_RATE_TARGET_CONF_SLOW: u16 = 6;
24
25const TX_ALREADY_IN_CHAIN_ERROR: i32 = -27;
26const MIN_BITCOIND_VERSION: usize = 290000;
27
28#[derive(Clone, Debug)]
40pub enum ChainSourceSpec {
41 Bitcoind {
42 url: String,
44 auth: rpc::Auth,
46 },
47 Esplora {
48 url: String,
50 },
51}
52
53pub enum ChainSourceClient {
54 Bitcoind(rpc::Client),
55 Esplora(esplora_client::AsyncClient),
56}
57
58impl ChainSourceClient {
59 async fn check_network(&self, expected: Network) -> anyhow::Result<()> {
60 match self {
61 ChainSourceClient::Bitcoind(bitcoind) => {
62 let network = bitcoind.get_blockchain_info()?;
63 if expected != network.chain {
64 bail!("Network mismatch: expected {:?}, got {:?}", expected, network.chain);
65 }
66 },
67 ChainSourceClient::Esplora(client) => {
68 let res = client.client().get(format!("{}/block-height/0", client.url()))
69 .send().await?.text().await?;
70 let genesis_hash = BlockHash::from_str(&res)
71 .context("bad response from server (not a blockhash). Esplora client possibly misconfigured")?;
72 if genesis_hash != genesis_block(expected).block_hash() {
73 bail!("Network mismatch: expected {:?}, got {:?}", expected, genesis_hash);
74 }
75 },
76 };
77
78 Ok(())
79 }
80}
81
82pub struct ChainSource {
114 inner: ChainSourceClient,
115 network: Network,
116 fee_rates: RwLock<FeeRates>,
117}
118
119impl ChainSource {
120 pub fn require_version(&self) -> anyhow::Result<()> {
125 if let ChainSourceClient::Bitcoind(bitcoind) = self.inner() {
126 if bitcoind.version()? < MIN_BITCOIND_VERSION {
127 bail!("Bitcoin Core version is too old, you can participate in rounds but won't be able to unilaterally exit. Please upgrade to 29.0 or higher.");
128 }
129 }
130
131 Ok(())
132 }
133
134 pub(crate) fn inner(&self) -> &ChainSourceClient {
135 &self.inner
136 }
137
138 pub async fn fee_rates(&self) -> FeeRates {
140 self.fee_rates.read().await.clone()
141 }
142
143 pub fn network(&self) -> Network {
145 self.network
146 }
147
148 pub async fn new(spec: ChainSourceSpec, network: Network, fallback_fee: Option<FeeRate>) -> anyhow::Result<Self> {
181 let inner = match spec {
182 ChainSourceSpec::Bitcoind { url, auth } => ChainSourceClient::Bitcoind(
183 rpc::Client::new(&url, auth)
184 .context("failed to create bitcoind rpc client")?
185 ),
186 ChainSourceSpec::Esplora { url } => ChainSourceClient::Esplora({
187 let url = url.strip_suffix("/").unwrap_or(&url);
189 esplora_client::Builder::new(url).build_async()
190 .with_context(|| format!("failed to create esplora client for url {}", url))?
191 }),
192 };
193
194 inner.check_network(network).await?;
195
196 let fee = fallback_fee.unwrap_or(FeeRate::BROADCAST_MIN);
197 let fee_rates = RwLock::new(FeeRates { fast: fee, regular: fee, slow: fee });
198
199 Ok(Self { inner, network, fee_rates })
200 }
201
202 async fn fetch_fee_rates(&self) -> anyhow::Result<FeeRates> {
203 match self.inner() {
204 ChainSourceClient::Bitcoind(bitcoind) => {
205 let get_fee_rate = |target| {
206 let fee = bitcoind.estimate_smart_fee(
207 target, Some(rpc::json::EstimateMode::Economical),
208 )?;
209 if let Some(fee_rate) = fee.fee_rate {
210 Ok(FeeRate::from_amount_per_kvb_ceil(fee_rate))
211 } else {
212 Err(anyhow!("No rate returned from estimate_smart_fee for a {} confirmation target", target))
213 }
214 };
215 Ok(FeeRates {
216 fast: get_fee_rate(FEE_RATE_TARGET_CONF_FAST)?,
217 regular: get_fee_rate(FEE_RATE_TARGET_CONF_REGULAR).expect("should exist"),
218 slow: get_fee_rate(FEE_RATE_TARGET_CONF_SLOW).expect("should exist"),
219 })
220 },
221 ChainSourceClient::Esplora(client) => {
222 let estimates = client.get_fee_estimates().await?;
224 let get_fee_rate = |target| {
225 let fee = estimates.get(&target).with_context(||
226 format!("No rate returned from get_fee_estimates for a {} confirmation target", target)
227 )?;
228 FeeRate::from_sat_per_vb_decimal_checked_ceil(*fee).with_context(||
229 format!("Invalid rate returned from get_fee_estimates {} for a {} confirmation target", fee, target)
230 )
231 };
232 Ok(FeeRates {
233 fast: get_fee_rate(FEE_RATE_TARGET_CONF_FAST)?,
234 regular: get_fee_rate(FEE_RATE_TARGET_CONF_REGULAR)?,
235 slow: get_fee_rate(FEE_RATE_TARGET_CONF_SLOW)?,
236 })
237 }
238 }
239 }
240
241 pub async fn tip(&self) -> anyhow::Result<BlockHeight> {
242 match self.inner() {
243 ChainSourceClient::Bitcoind(bitcoind) => {
244 Ok(bitcoind.get_block_count()? as BlockHeight)
245 },
246 ChainSourceClient::Esplora(client) => {
247 Ok(client.get_height().await?)
248 },
249 }
250 }
251
252 pub async fn block_ref(&self, height: BlockHeight) -> anyhow::Result<BlockRef> {
253 match self.inner() {
254 ChainSourceClient::Bitcoind(bitcoind) => {
255 let hash = bitcoind.get_block_hash(height as u64)?;
256 Ok(BlockRef { height, hash })
257 },
258 ChainSourceClient::Esplora(client) => {
259 let hash = client.get_block_hash(height).await?;
260 Ok(BlockRef { height, hash })
261 },
262 }
263 }
264
265 pub async fn block(&self, hash: BlockHash) -> anyhow::Result<Option<Block>> {
266 match self.inner() {
267 ChainSourceClient::Bitcoind(bitcoind) => {
268 match bitcoind.get_block(&hash) {
269 Ok(b) => Ok(Some(b)),
270 Err(e) if e.is_not_found() => Ok(None),
271 Err(e) => Err(e.into()),
272 }
273 },
274 ChainSourceClient::Esplora(client) => {
275 Ok(client.get_block_by_hash(&hash).await?)
276 },
277 }
278 }
279
280 pub async fn mempool_ancestor_info(&self, txid: Txid) -> anyhow::Result<MempoolAncestorInfo> {
283 let mut result = MempoolAncestorInfo::new(txid);
284
285 match self.inner() {
288 ChainSourceClient::Bitcoind(bitcoind) => {
289 let entry = bitcoind.get_mempool_entry(&txid)?;
290 let err = || anyhow!("missing weight parameter from getmempoolentry");
291
292 result.total_fee = entry.fees.ancestor;
293 result.total_weight = Weight::from_wu(entry.weight.ok_or_else(err)?) +
294 Weight::from_vb(entry.ancestor_size).ok_or_else(err)?;
295 },
296 ChainSourceClient::Esplora(client) => {
297 let status = self.tx_status(txid).await?;
300 if !matches!(status, TxStatus::Mempool) {
301 return Err(anyhow!("{} is not in the mempool, status is {:?}", txid, status));
302 }
303
304 let mut info_map: HashMap<Txid, esplora_client::Tx> = HashMap::new();
305 let mut set = HashSet::from([txid]);
306 while !set.is_empty() {
307 let requests = set.iter().filter_map(|txid| if info_map.contains_key(txid) {
309 None
310 } else {
311 Some((txid, client.get_tx_info(&txid)))
312 }).collect::<Vec<_>>();
313
314 let mut next_set = HashSet::new();
316
317 for (txid, request) in requests {
319 let info = request.await?
320 .ok_or_else(|| anyhow!("unable to retrieve tx info for {}", txid))?;
321 if !info.status.confirmed {
322 for vin in info.vin.iter() {
323 next_set.insert(vin.txid);
324 }
325 }
326 info_map.insert(*txid, info);
327 }
328 set = next_set;
329 }
330 for info in info_map.into_values().filter(|info| !info.status.confirmed) {
332 result.total_fee += info.fee();
333 result.total_weight += info.weight();
334 }
335 },
336 }
337 Ok(result)
339 }
340
341 pub async fn txs_spending_inputs<T: IntoIterator<Item = OutPoint>>(
344 &self,
345 outpoints: T,
346 block_scan_start: BlockHeight,
347 ) -> anyhow::Result<TxsSpendingInputsResult> {
348 let mut res = TxsSpendingInputsResult::new();
349 match self.inner() {
350 ChainSourceClient::Bitcoind(bitcoind) => {
351 let start = block_scan_start.saturating_sub(1);
353 let block_ref = self.block_ref(start).await?;
354 let cp = CheckPoint::new(BlockId {
355 height: block_ref.height,
356 hash: block_ref.hash,
357 });
358
359 let mut emitter = bdk_bitcoind_rpc::Emitter::new(
360 bitcoind, cp.clone(), cp.height(), bdk_bitcoind_rpc::NO_EXPECTED_MEMPOOL_TXS,
361 );
362
363 debug!("Scanning blocks for spent outpoints with bitcoind, starting at block height {}...", block_scan_start);
364 let outpoint_set = outpoints.into_iter().collect::<HashSet<_>>();
365 while let Some(em) = emitter.next_block()? {
366 if em.block_height() % 1000 == 0 {
368 info!("Scanned for spent outpoints until block height {}", em.block_height());
369 }
370 for tx in &em.block.txdata {
371 for txin in tx.input.iter() {
372 if outpoint_set.contains(&txin.previous_output) {
373 res.add(
374 txin.previous_output.clone(),
375 tx.compute_txid(),
376 TxStatus::Confirmed(BlockRef {
377 height: em.block_height(), hash: em.block.block_hash().clone()
378 })
379 );
380 if res.map.len() == outpoint_set.len() {
382 return Ok(res);
383 }
384 }
385 }
386 }
387 }
388
389 debug!("Finished scanning blocks for spent outpoints, now checking the mempool...");
390 let mempool = emitter.mempool()?;
391 for (tx, _last_seen) in &mempool.update {
392 for txin in tx.input.iter() {
393 if outpoint_set.contains(&txin.previous_output) {
394 res.add(
395 txin.previous_output.clone(),
396 tx.compute_txid(),
397 TxStatus::Mempool,
398 );
399
400 if res.map.len() == outpoint_set.len() {
402 return Ok(res);
403 }
404 }
405 }
406 }
407 debug!("Finished checking the mempool for spent outpoints");
408 },
409 ChainSourceClient::Esplora(client) => {
410 for outpoint in outpoints {
411 let output_status = client.get_output_status(&outpoint.txid, outpoint.vout.into()).await?;
412
413 if let Some(output_status) = output_status {
414 if output_status.spent {
415 let tx_status = {
416 let status = output_status.status.expect("Status should be valid if an outpoint is spent");
417 if status.confirmed {
418 TxStatus::Confirmed(BlockRef {
419 height: status.block_height.expect("Confirmed transaction missing block_height"),
420 hash: status.block_hash.expect("Confirmed transaction missing block_hash"),
421 })
422 } else {
423 TxStatus::Mempool
424 }
425 };
426 let txid = output_status.txid.expect("Txid should be valid if an outpoint is spent");
427 res.add(outpoint, txid, tx_status);
428 }
429 }
430 }
431 },
432 }
433
434 Ok(res)
435 }
436
437 pub async fn broadcast_tx(&self, tx: &Transaction) -> anyhow::Result<()> {
438 match self.inner() {
439 ChainSourceClient::Bitcoind(bitcoind) => {
440 match bitcoind.send_raw_transaction(tx) {
441 Ok(_) => Ok(()),
442 Err(rpc::Error::JsonRpc(
443 rpc::jsonrpc::Error::Rpc(e))
444 ) if e.code == TX_ALREADY_IN_CHAIN_ERROR => Ok(()),
445 Err(e) => Err(e.into()),
446 }
447 },
448 ChainSourceClient::Esplora(client) => {
449 client.broadcast(tx).await?;
450 Ok(())
451 },
452 }
453 }
454
455 pub async fn broadcast_package(&self, txs: &[impl Borrow<Transaction>]) -> anyhow::Result<()> {
456 #[derive(Debug, Deserialize)]
457 struct PackageTxInfo {
458 txid: Txid,
459 error: Option<String>,
460 }
461 #[derive(Debug, Deserialize)]
462 struct SubmitPackageResponse {
463 #[serde(rename = "tx-results")]
464 tx_results: HashMap<Wtxid, PackageTxInfo>,
465 package_msg: String,
466 }
467
468 match self.inner() {
469 ChainSourceClient::Bitcoind(bitcoind) => {
470 let hexes = txs.iter()
471 .map(|t| bitcoin::consensus::encode::serialize_hex(t.borrow()))
472 .collect::<Vec<_>>();
473 let res = bitcoind.call::<SubmitPackageResponse>("submitpackage", &[hexes.into()])?;
474 if res.package_msg != "success" {
475 let errors = res.tx_results.values()
476 .map(|t| format!("tx {}: {}",
477 t.txid, t.error.as_ref().map(|s| s.as_str()).unwrap_or("(no error)"),
478 ))
479 .collect::<Vec<_>>();
480 bail!("msg: '{}', errors: {:?}", res.package_msg, errors);
481 }
482 Ok(())
483 },
484 ChainSourceClient::Esplora(client) => {
485 let txs = txs.iter().map(|t| t.borrow().clone()).collect::<Vec<_>>();
486 let res = client.submit_package(&txs, None, None).await?;
487 if res.package_msg != "success" {
488 let errors = res.tx_results.values()
489 .map(|t| format!("tx {}: {}",
490 t.txid, t.error.as_ref().map(|s| s.as_str()).unwrap_or("(no error)"),
491 ))
492 .collect::<Vec<_>>();
493 bail!("msg: '{}', errors: {:?}", res.package_msg, errors);
494 }
495
496 Ok(())
497 },
498 }
499 }
500
501 pub async fn get_tx(&self, txid: &Txid) -> anyhow::Result<Option<Transaction>> {
502 match self.inner() {
503 ChainSourceClient::Bitcoind(bitcoind) => {
504 match bitcoind.get_raw_transaction(txid, None) {
505 Ok(tx) => Ok(Some(tx)),
506 Err(e) if e.is_not_found() => Ok(None),
507 Err(e) => Err(e.into()),
508 }
509 },
510 ChainSourceClient::Esplora(client) => {
511 Ok(client.get_tx(txid).await?)
512 },
513 }
514 }
515
516 pub async fn tx_confirmed(&self, txid: Txid) -> anyhow::Result<Option<BlockHeight>> {
518 Ok(self.tx_status(txid).await?.confirmed_height())
519 }
520
521 pub async fn tx_status(&self, txid: Txid) -> anyhow::Result<TxStatus> {
523 match self.inner() {
524 ChainSourceClient::Bitcoind(bitcoind) => Ok(bitcoind.tx_status(&txid)?),
525 ChainSourceClient::Esplora(esplora) => {
526 match esplora.get_tx_info(&txid).await? {
527 Some(info) => match (info.status.block_height, info.status.block_hash) {
528 (Some(block_height), Some(block_hash)) => Ok(TxStatus::Confirmed(BlockRef {
529 height: block_height,
530 hash: block_hash,
531 } )),
532 _ => Ok(TxStatus::Mempool),
533 },
534 None => Ok(TxStatus::NotFound),
535 }
536 },
537 }
538 }
539
540 #[allow(unused)]
541 pub async fn txout_value(&self, outpoint: &OutPoint) -> anyhow::Result<Amount> {
542 let tx = match self.inner() {
543 ChainSourceClient::Bitcoind(bitcoind) => {
544 bitcoind.get_raw_transaction(&outpoint.txid, None)
545 .with_context(|| format!("tx {} unknown", outpoint.txid))?
546 },
547 ChainSourceClient::Esplora(client) => {
548 client.get_tx(&outpoint.txid).await?
549 .with_context(|| format!("tx {} unknown", outpoint.txid))?
550 },
551 };
552 Ok(tx.output.get(outpoint.vout as usize).context("outpoint vout out of range")?.value)
553 }
554
555 pub async fn update_fee_rates(&self, fallback_fee: Option<FeeRate>) -> anyhow::Result<()> {
558 let fee_rates = match (self.fetch_fee_rates().await, fallback_fee) {
559 (Ok(fee_rates), _) => Ok(fee_rates),
560 (Err(e), None) => Err(e),
561 (Err(e), Some(fallback)) => {
562 warn!("Error getting fee rates, falling back to {} sat/kvB: {}",
563 fallback.to_btc_per_kvb(), e,
564 );
565 Ok(FeeRates { fast: fallback, regular: fallback, slow: fallback })
566 }
567 }?;
568
569 *self.fee_rates.write().await = fee_rates;
570 Ok(())
571 }
572}
573
574#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
576pub struct FeeRates {
577 pub fast: FeeRate,
579 pub regular: FeeRate,
581 pub slow: FeeRate,
583}
584
585#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
587pub struct MempoolAncestorInfo {
588 pub txid: Txid,
590 pub total_fee: Amount,
593 pub total_weight: Weight,
595}
596
597impl MempoolAncestorInfo {
598 pub fn new(txid: Txid) -> Self {
599 Self {
600 txid,
601 total_fee: Amount::ZERO,
602 total_weight: Weight::ZERO,
603 }
604 }
605
606 pub fn effective_fee_rate(&self) -> Option<FeeRate> {
607 FeeRate::from_amount_and_weight_ceil(self.total_fee, self.total_weight)
608 }
609}
610
611#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
612pub struct TxsSpendingInputsResult {
613 pub map: HashMap<OutPoint, (Txid, TxStatus)>,
614}
615
616impl TxsSpendingInputsResult {
617 pub fn new() -> Self {
618 Self { map: HashMap::new() }
619 }
620
621 pub fn add(&mut self, outpoint: OutPoint, txid: Txid, status: TxStatus) {
622 self.map.insert(outpoint, (txid, status));
623 }
624
625 pub fn get(&self, outpoint: &OutPoint) -> Option<&(Txid, TxStatus)> {
626 self.map.get(outpoint)
627 }
628
629 pub fn confirmed_txids(&self) -> impl Iterator<Item = (Txid, BlockRef)> + '_ {
630 self.map
631 .iter()
632 .filter_map(|(_, (txid, status))| {
633 match status {
634 TxStatus::Confirmed(block) => Some((*txid, *block)),
635 _ => None,
636 }
637 })
638 }
639
640 pub fn mempool_txids(&self) -> impl Iterator<Item = Txid> + '_ {
641 self.map
642 .iter()
643 .filter(|(_, (_, status))| matches!(status, TxStatus::Mempool))
644 .map(|(_, (txid, _))| *txid)
645 }
646}