bark/onchain/
chain.rs

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/// Configuration for the onchain data source.
29///
30/// [ChainSource] selects which backend to use for blockchain data and transaction broadcasting:
31/// - Bitcoind: uses a Bitcoin Core node via JSON-RPC
32/// - Esplora: uses the HTTP API endpoint of [esplora-electrs](https://github.com/Blockstream/electrs)
33///
34/// Typical usage is to construct a ChainSource from configuration and pass it to
35/// [ChainSource::new] along with the expected [Network].
36///
37/// Notes:
38/// - For [ChainSourceSpec::Bitcoind], authentication must be provided (cookie file or user/pass).
39#[derive(Clone, Debug)]
40pub enum ChainSourceSpec {
41	Bitcoind {
42		/// RPC URL of the Bitcoin Core node (e.g. <http://127.0.0.1:8332>).
43		url: String,
44		/// Authentication method for JSON-RPC (cookie file or user/pass).
45		auth: rpc::Auth,
46	},
47	Esplora {
48		/// Base URL of the esplora-electrs instance (e.g. <https://esplora.signet.2nd.dev>).
49		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
82/// Client for interacting with the configured on-chain backend.
83///
84/// [ChainSource] abstracts over multiple backends using [ChainSourceSpec] to provide:
85/// - Chain queries (tip, block headers/blocks, transaction status and fetching)
86/// - Mempool-related utilities (ancestor fee/weight, spending lookups)
87/// - Broadcasting single transactions or packages (RBF/CPFP workflows)
88/// - Fee estimation and caching with optional fallback values
89///
90/// Behavior notes:
91/// - [ChainSource::update_fee_rates] refreshes internal fee estimates; if backend estimates
92///   fail and a fallback fee is provided, it will be used for all tiers.
93/// - [ChainSource::fee_rates] returns the last cached [FeeRates].
94///
95/// Examples:
96///
97/// ```rust
98/// # async fn func() {
99/// use bark::onchain::{ChainSource, ChainSourceSpec};
100/// use bdk_bitcoind_rpc::bitcoincore_rpc::Auth;
101/// use bitcoin::{FeeRate, Network};
102///
103/// let spec = ChainSourceSpec::Bitcoind {
104///     url: "http://localhost:8332".into(),
105///     auth: Auth::UserPass("user".into(), "password".into()),
106/// };
107/// let network = Network::Bitcoin;
108/// let fallback_fee = FeeRate::from_sat_per_vb(5);
109///
110/// let instance = ChainSource::new(spec, network, fallback_fee).await.unwrap();
111/// # }
112/// ```
113pub struct ChainSource {
114	inner: ChainSourceClient,
115	network: Network,
116	fee_rates: RwLock<FeeRates>,
117}
118
119impl ChainSource {
120	/// Checks that the version of the chain source is compatible with Bark.
121	///
122	/// For bitcoind, it checks if the version is at least 29.0
123	/// This is the first version for which 0 fee-anchors are considered standard
124	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	/// Gets a cached copy of the calculated network [FeeRates]
139	pub async fn fee_rates(&self) -> FeeRates {
140		self.fee_rates.read().await.clone()
141	}
142
143	/// Gets the network that the [ChainSource] was validated against.
144	pub fn network(&self) -> Network {
145		self.network
146	}
147
148	/// Creates a new instance of the object with the specified chain source, network, and optional
149	/// fallback fee rate.
150	///
151	/// This function initializes the internal chain source client based on the provided `chain_source`:
152	/// - If `chain_source` is of type [ChainSourceSpec::Bitcoind], it creates a Bitcoin Core RPC client
153	///   using the provided URL and authentication parameters.
154	/// - If `chain_source` is of type [ChainSourceSpec::Esplora], it creates an Esplora client with the
155	///   given URL.
156	///
157	/// Both clients are initialized asynchronously, and any errors encountered during their
158	/// creation will be returned as part of the [anyhow::Result].
159	///
160	/// Additionally, the function performs a network consistency check to ensure the specified
161	/// network (e.g., `mainnet` or `signet`) matches the network configuration of the initialized
162	/// chain source client.
163	///
164	/// The `fallback_fee` parameter is optional. If provided, it is used as the default fee rate
165	/// for transactions. If not specified, the `FeeRate::BROADCAST_MIN` is used as the default fee
166	/// rate.
167	///
168	/// # Arguments
169	///
170	/// * `chain_source` - Specifies the backend to use for blockchain data.
171	/// * `network` - The Bitcoin network to operate on (e.g., `mainnet`, `testnet`, `regtest`).
172	/// * `fallback_fee` - An optional fallback fee rate to use for transaction fee estimation. If
173	///   not provided, a default fee rate of [FeeRate::BROADCAST_MIN] will be used.
174	///
175	/// # Returns
176	///
177	/// * `Ok(Self)` - If the object is successfully created with all necessary configurations.
178	/// * `Err(anyhow::Error)` - If there is an error in initializing the chain source client or
179	///   verifying the network.
180	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				// the esplora client doesn't deal well with trailing slash in url
188				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				// The API should return rates for targets 1-25, 144 and 1008
223				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	/// Retrieves basic CPFP ancestry information of the given transaction. Confirmed transactions
281	/// are ignored as they are not relevant to CPFP.
282	pub async fn mempool_ancestor_info(&self, txid: Txid) -> anyhow::Result<MempoolAncestorInfo> {
283		let mut result = MempoolAncestorInfo::new(txid);
284
285		// TODO: Determine if any line of descendant transactions increase the effective fee rate
286		//		 of the target txid.
287		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				// We should first verify the transaction is in the mempool to maintain the same
298				// behavior as Bitcoin Core
299				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					// Start requests asynchronously
308					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					// Collect txids to be added to the set
315					let mut next_set = HashSet::new();
316
317					// Process each request, ignoring parents of confirmed transactions
318					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				// Calculate the total weight and fee of the unconfirmed ancestry
331				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		// Now calculate the effective fee rate of the package
338		Ok(result)
339	}
340
341	/// For each provided outpoint, fetches the ID of any confirmed or unconfirmed in which the
342	/// outpoint is spent.
343	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				// We must offset the height to account for the fact we iterate using next_block()
352				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					// Provide updates as the scan can take a long time
367					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								// We can stop early if we've found a spending tx for each outpoint
381								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							// We can stop early if we've found a spending tx for each outpoint
401							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	/// Returns the block height the tx is confirmed in, if any.
517	pub async fn tx_confirmed(&self, txid: Txid) -> anyhow::Result<Option<BlockHeight>> {
518		Ok(self.tx_status(txid).await?.confirmed_height())
519	}
520
521	/// Returns the status of the given transaction, including the block height if it is confirmed
522	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	/// Gets the current fee rates from the chain source, falling back to user-specified values if
556	/// necessary
557	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/// The [FeeRates] struct represents the fee rates for transactions categorized by speed or urgency.
575#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
576pub struct FeeRates {
577	/// The fee for fast transactions (higher cost, lower time delay).
578	pub fast: FeeRate,
579	/// The fee for standard-priority transactions.
580	pub regular: FeeRate,
581	/// The fee for slower transactions (lower cost, higher time delay).
582	pub slow: FeeRate,
583}
584
585/// Contains the fee information for an unconfirmed transaction found in the mempool.
586#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
587pub struct MempoolAncestorInfo {
588	/// The ID of the transaction that was queried.
589	pub txid: Txid,
590	/// The total fee of this transaction and all of its unconfirmed ancestors. If the transaction
591	/// is to be replaced, the total fees of the published package MUST exceed this.
592	pub total_fee: Amount,
593	/// The total weight of this transaction and all of its unconfirmed ancestors.
594	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}