|
| 1 | +use std::sync::Arc; |
| 2 | + |
| 3 | +use bdk_bitcoind_rpc::Emitter; |
| 4 | +use bdk_chain::{bdk_core, Anchor, Balance, ChainPosition, ConfirmationBlockTime}; |
| 5 | +use bdk_testenv::{bitcoincore_rpc::RpcApi, TestEnv}; |
| 6 | +use bdk_tx::{CanonicalUnspents, Input, InputCandidates, RbfParams, TxStatus, TxWithStatus}; |
| 7 | +use bitcoin::{absolute, Address, BlockHash, OutPoint, Transaction, Txid}; |
| 8 | +use miniscript::{ |
| 9 | + plan::{Assets, Plan}, |
| 10 | + Descriptor, DescriptorPublicKey, ForEachKey, |
| 11 | +}; |
| 12 | + |
| 13 | +const EXTERNAL: &str = "external"; |
| 14 | +const INTERNAL: &str = "internal"; |
| 15 | + |
| 16 | +pub struct Wallet { |
| 17 | + pub chain: bdk_chain::local_chain::LocalChain, |
| 18 | + pub graph: bdk_chain::IndexedTxGraph< |
| 19 | + bdk_core::ConfirmationBlockTime, |
| 20 | + bdk_chain::keychain_txout::KeychainTxOutIndex<&'static str>, |
| 21 | + >, |
| 22 | +} |
| 23 | + |
| 24 | +impl Wallet { |
| 25 | + pub fn new( |
| 26 | + genesis_hash: BlockHash, |
| 27 | + external: Descriptor<DescriptorPublicKey>, |
| 28 | + internal: Descriptor<DescriptorPublicKey>, |
| 29 | + ) -> anyhow::Result<Self> { |
| 30 | + let mut indexer = bdk_chain::keychain_txout::KeychainTxOutIndex::default(); |
| 31 | + indexer.insert_descriptor(EXTERNAL, external)?; |
| 32 | + indexer.insert_descriptor(INTERNAL, internal)?; |
| 33 | + let graph = bdk_chain::IndexedTxGraph::new(indexer); |
| 34 | + let (chain, _) = bdk_chain::local_chain::LocalChain::from_genesis_hash(genesis_hash); |
| 35 | + Ok(Self { chain, graph }) |
| 36 | + } |
| 37 | + |
| 38 | + pub fn sync(&mut self, env: &TestEnv) -> anyhow::Result<()> { |
| 39 | + let client = env.rpc_client(); |
| 40 | + let last_cp = self.chain.tip(); |
| 41 | + let mut emitter = Emitter::new(client, last_cp, 0); |
| 42 | + while let Some(event) = emitter.next_block()? { |
| 43 | + let _ = self |
| 44 | + .graph |
| 45 | + .apply_block_relevant(&event.block, event.block_height()); |
| 46 | + let _ = self.chain.apply_update(event.checkpoint); |
| 47 | + } |
| 48 | + let mempool = emitter.mempool()?; |
| 49 | + let _ = self.graph.batch_insert_relevant_unconfirmed(mempool); |
| 50 | + Ok(()) |
| 51 | + } |
| 52 | + |
| 53 | + pub fn next_address(&mut self) -> Option<Address> { |
| 54 | + let ((_, spk), _) = self.graph.index.next_unused_spk(EXTERNAL)?; |
| 55 | + Address::from_script(&spk, bitcoin::consensus::Params::REGTEST).ok() |
| 56 | + } |
| 57 | + |
| 58 | + pub fn balance(&self) -> Balance { |
| 59 | + let outpoints = self.graph.index.outpoints().clone(); |
| 60 | + self.graph.graph().balance( |
| 61 | + &self.chain, |
| 62 | + self.chain.tip().block_id(), |
| 63 | + outpoints, |
| 64 | + |_, _| true, |
| 65 | + ) |
| 66 | + } |
| 67 | + |
| 68 | + /// TODO: Add to chain sources. |
| 69 | + pub fn tip_info( |
| 70 | + &self, |
| 71 | + client: &impl RpcApi, |
| 72 | + ) -> anyhow::Result<(absolute::Height, absolute::Time)> { |
| 73 | + let tip = self.chain.tip().block_id(); |
| 74 | + let tip_info = client.get_block_header_info(&tip.hash)?; |
| 75 | + let tip_height = absolute::Height::from_consensus(tip.height)?; |
| 76 | + let tip_time = |
| 77 | + absolute::Time::from_consensus(tip_info.median_time.unwrap_or(tip_info.time) as _)?; |
| 78 | + Ok((tip_height, tip_time)) |
| 79 | + } |
| 80 | + |
| 81 | + // TODO: Maybe create an `AssetsBuilder` or `AssetsExt` that makes it easier to add |
| 82 | + // assets from descriptors, etc. |
| 83 | + pub fn assets(&self) -> Assets { |
| 84 | + let index = &self.graph.index; |
| 85 | + let tip = self.chain.tip().block_id(); |
| 86 | + Assets::new() |
| 87 | + .after(absolute::LockTime::from_height(tip.height).expect("must be valid height")) |
| 88 | + .add({ |
| 89 | + let mut pks = vec![]; |
| 90 | + for (_, desc) in index.keychains() { |
| 91 | + desc.for_each_key(|k| { |
| 92 | + pks.extend(k.clone().into_single_keys()); |
| 93 | + true |
| 94 | + }); |
| 95 | + } |
| 96 | + pks |
| 97 | + }) |
| 98 | + } |
| 99 | + |
| 100 | + pub fn plan_of_output(&self, outpoint: OutPoint, assets: &Assets) -> Option<Plan> { |
| 101 | + let index = &self.graph.index; |
| 102 | + let ((k, i), _txout) = index.txout(outpoint)?; |
| 103 | + let desc = index.get_descriptor(k)?.at_derivation_index(i).ok()?; |
| 104 | + let plan = desc.plan(assets).ok()?; |
| 105 | + Some(plan) |
| 106 | + } |
| 107 | + |
| 108 | + pub fn canonical_txs(&self) -> impl Iterator<Item = TxWithStatus<Arc<Transaction>>> + '_ { |
| 109 | + pub fn status_from_position(pos: ChainPosition<ConfirmationBlockTime>) -> Option<TxStatus> { |
| 110 | + match pos { |
| 111 | + bdk_chain::ChainPosition::Confirmed { anchor, .. } => Some(TxStatus { |
| 112 | + height: absolute::Height::from_consensus( |
| 113 | + anchor.confirmation_height_upper_bound(), |
| 114 | + ) |
| 115 | + .expect("must convert to height"), |
| 116 | + time: absolute::Time::from_consensus(anchor.confirmation_time as _) |
| 117 | + .expect("must convert from time"), |
| 118 | + }), |
| 119 | + bdk_chain::ChainPosition::Unconfirmed { .. } => None, |
| 120 | + } |
| 121 | + } |
| 122 | + self.graph |
| 123 | + .graph() |
| 124 | + .list_canonical_txs(&self.chain, self.chain.tip().block_id()) |
| 125 | + .map(|c_tx| (c_tx.tx_node.tx, status_from_position(c_tx.chain_position))) |
| 126 | + } |
| 127 | + |
| 128 | + pub fn all_candidates(&self) -> bdk_tx::InputCandidates { |
| 129 | + let index = &self.graph.index; |
| 130 | + let assets = self.assets(); |
| 131 | + let canon_utxos = CanonicalUnspents::new(self.canonical_txs()); |
| 132 | + let can_select = canon_utxos.try_get_unspents( |
| 133 | + index |
| 134 | + .outpoints() |
| 135 | + .iter() |
| 136 | + .filter_map(|(_, op)| Some((*op, self.plan_of_output(*op, &assets)?))), |
| 137 | + ); |
| 138 | + InputCandidates::new([], can_select) |
| 139 | + } |
| 140 | + |
| 141 | + pub fn rbf_candidates( |
| 142 | + &self, |
| 143 | + replace: impl IntoIterator<Item = Txid>, |
| 144 | + tip_height: absolute::Height, |
| 145 | + ) -> anyhow::Result<(bdk_tx::InputCandidates, RbfParams)> { |
| 146 | + let index = &self.graph.index; |
| 147 | + let assets = self.assets(); |
| 148 | + let mut canon_utxos = CanonicalUnspents::new(self.canonical_txs()); |
| 149 | + |
| 150 | + // Exclude txs that reside-in `rbf_set`. |
| 151 | + let rbf_set = canon_utxos.extract_replacements(replace)?; |
| 152 | + let must_select = rbf_set |
| 153 | + .must_select_largest_input_of_each_original_tx(&canon_utxos)? |
| 154 | + .into_iter() |
| 155 | + .map(|op| canon_utxos.try_get_unspent(op, self.plan_of_output(op, &assets)?)) |
| 156 | + .collect::<Option<Vec<Input>>>() |
| 157 | + .ok_or(anyhow::anyhow!( |
| 158 | + "failed to find input of tx we are intending to replace" |
| 159 | + ))?; |
| 160 | + |
| 161 | + let can_select = index.outpoints().iter().filter_map(|(_, op)| { |
| 162 | + canon_utxos.try_get_unspent(*op, self.plan_of_output(*op, &assets)?) |
| 163 | + }); |
| 164 | + Ok(( |
| 165 | + InputCandidates::new(must_select, can_select) |
| 166 | + .filter(rbf_set.candidate_filter(tip_height)), |
| 167 | + rbf_set.selector_rbf_params(), |
| 168 | + )) |
| 169 | + } |
| 170 | +} |
0 commit comments