1use crate::config;
2use crate::error::{Context, Error, ensure};
3use crate::node::Node;
4use bitcoin::{Amount, Denomination, OutPoint};
5use serde::{Serialize, Serializer};
6use serde_json::{Value, json};
7use std::{cmp::Reverse, collections::HashMap};
8use urma_wallet::{
9 account::{Account, Branch, KeyPath},
10 funding::Funding,
11};
12
13#[derive(Clone, Debug, Serialize)]
14pub struct Coin {
15 pub outpoint: OutPoint,
16 pub value: u64,
17 pub height: u64,
18 #[serde(serialize_with = "path_text")]
19 pub path: KeyPath,
20}
21
22#[derive(Clone, Debug, Serialize)]
23pub struct WalletView {
24 pub coins: Vec<Coin>,
25 pub next_change: u32,
26 pub reported: usize,
27 pub verified: bool,
28 pub skipped: usize,
29}
30
31pub struct Candidates {
32 coins: Vec<Coin>,
33 reported: usize,
34}
35
36impl Candidates {
37 pub fn new() -> Self {
38 Self {
39 coins: Vec::new(),
40 reported: 0,
41 }
42 }
43
44 pub fn add(&mut self, coin: Coin) {
45 if self.coins.iter().any(|held| held.outpoint == coin.outpoint) {
46 return;
47 }
48 self.reported += 1;
49 let rank = |held: &Coin| (Reverse(held.value), held.outpoint);
50 let position = self.coins.partition_point(|held| rank(held) < rank(&coin));
51 if position < config::WALLET_CHECKS {
52 self.coins.insert(position, coin);
53 self.coins.truncate(config::WALLET_CHECKS);
54 }
55 }
56
57 pub fn retained(&self) -> usize {
58 self.coins.len()
59 }
60
61 pub fn reported(&self) -> usize {
62 self.reported
63 }
64
65 pub fn largest(self) -> Vec<Coin> {
66 self.coins
67 }
68}
69
70impl Default for Candidates {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76#[derive(Clone)]
77pub struct FundingInput {
78 pub funding: Funding,
79 pub path: KeyPath,
80}
81
82pub struct Selection {
83 pub inputs: Vec<FundingInput>,
84 pub total: u64,
85 pub next_change: u32,
86}
87
88fn path_text<S: Serializer>(path: &KeyPath, serializer: S) -> Result<S::Ok, S::Error> {
89 serializer.collect_str(&format_args!("{}/{}", path.branch.index(), path.index))
90}
91
92pub(crate) fn coin_amount(value: &Value) -> Result<Amount, Error> {
93 let coins = value.as_f64().context("missing coin amount")?;
94 Ok(Amount::from_float_in(coins, Denomination::Bitcoin)?)
95}
96
97fn covered(total: u64, inputs: usize, minimum: u64, per_input: u64) -> Result<bool, Error> {
98 let needed = per_input
99 .checked_mul(u64::try_from(inputs)?)
100 .and_then(|inputs| inputs.checked_add(minimum))
101 .context("funding target overflow")?;
102 Ok(total >= needed)
103}
104
105impl Node {
106 pub fn wallet(&self, account: &Account) -> Result<WalletView, Error> {
107 self.verify_network()?;
108 ensure!(
109 account.chain().genesis()? == self.chain().genesis()?,
110 "funding account belongs to another chain"
111 );
112 let candidates = match self.is_public() {
113 true => self.routed_coins(account)?,
114 false => self.local_coins(account)?,
115 };
116 let reported = candidates.reported();
117 let mut live = Vec::new();
118 let mut checked = 0;
119 for coin in candidates.largest() {
120 if live.len() == config::WALLET_VERIFY_OUTPUTS {
121 break;
122 }
123 checked += 1;
124 if self.live(account, &coin)? {
125 live.push(coin);
126 }
127 }
128 let skipped = reported - checked;
129 if skipped > 0 {
130 tracing::warn!(
131 reported,
132 skipped,
133 bound = config::WALLET_VERIFY_OUTPUTS,
134 "wallet keeps only its largest coins; smaller ones are skipped unverified"
135 );
136 }
137 let next_change = live
138 .iter()
139 .filter(|coin| coin.path.branch == Branch::Internal)
140 .fold(0, |next, coin| next.max(coin.path.index + 1));
141 Ok(WalletView {
142 coins: live,
143 next_change,
144 reported,
145 verified: true,
146 skipped,
147 })
148 }
149
150 pub fn select_coins(
151 &self,
152 account: &Account,
153 minimum: u64,
154 per_input: u64,
155 ) -> Result<Selection, Error> {
156 let view = self.wallet(account)?;
157 let mut chosen = Vec::new();
158 let mut total = 0u64;
159 for coin in view.coins {
160 if covered(total, chosen.len(), minimum, per_input)? {
161 break;
162 }
163 ensure!(
164 chosen.len() < config::WALLET_MAX_INPUTS,
165 "funding needs more than {} inputs; consolidate the wallet first",
166 config::WALLET_MAX_INPUTS
167 );
168 total = total.checked_add(coin.value).context("funding overflow")?;
169 chosen.push(coin);
170 }
171 if !covered(total, chosen.len(), minimum, per_input)? {
172 return Err(Error::Missing(
173 "confirmed wallet coins do not cover the spend; fund the receive address and confirm first".into(),
174 ));
175 }
176 let mut inputs = Vec::new();
177 for coin in &chosen {
178 inputs.push(FundingInput {
179 funding: self.parent(account, coin)?,
180 path: coin.path,
181 });
182 }
183 Ok(Selection {
184 inputs,
185 total,
186 next_change: view.next_change,
187 })
188 }
189
190 fn local_coins(&self, account: &Account) -> Result<Candidates, Error> {
191 let mut paths = HashMap::new();
192 let mut descriptors = Vec::new();
193 for branch in [Branch::External, Branch::Internal] {
194 for index in 0..config::WALLET_RANGE {
195 let path = KeyPath::new(branch, index);
196 let script = hex::encode(account.script(path)?.as_bytes());
197 descriptors.push(json!(format!("raw({script})")));
198 paths.insert(script, path);
199 }
200 }
201 let scan = self.call("scantxoutset", &[json!("start"), Value::Array(descriptors)])?;
202 ensure!(scan["success"] == true, "UTXO scan did not complete");
203 let rows = scan["unspents"].as_array().context("missing UTXO scan")?;
204 let mut coins = Candidates::new();
205 for row in rows {
206 let script = row["scriptPubKey"]
207 .as_str()
208 .context("missing UTXO script")?;
209 let path = *paths
210 .get(script)
211 .context("UTXO scan returned a foreign script")?;
212 coins.add(Coin {
213 outpoint: OutPoint {
214 txid: row["txid"].as_str().context("missing UTXO txid")?.parse()?,
215 vout: u32::try_from(row["vout"].as_u64().context("missing UTXO vout")?)?,
216 },
217 value: coin_amount(&row["amount"])?.to_sat(),
218 height: row["height"].as_u64().context("missing UTXO height")?,
219 path,
220 });
221 }
222 Ok(coins)
223 }
224
225 fn routed_coins(&self, account: &Account) -> Result<Candidates, Error> {
226 let mut coins = Candidates::new();
227 for branch in [Branch::External, Branch::Internal] {
228 let mut empty = 0;
229 let mut index = 0;
230 while empty < config::WALLET_GAP && index < config::WALLET_RANGE {
231 let found = self.address_coins(account, KeyPath::new(branch, index))?;
232 empty = match found.is_empty() {
233 true => empty + 1,
234 false => 0,
235 };
236 for coin in found {
237 coins.add(coin);
238 }
239 index += 1;
240 }
241 }
242 Ok(coins)
243 }
244
245 fn address_coins(&self, account: &Account, path: KeyPath) -> Result<Vec<Coin>, Error> {
246 let rows = self.call("addressutxos", &[json!(account.address(path)?)])?;
247 let rows = rows.as_array().context("missing public UTXOs")?;
248 let mut coins = Vec::new();
249 for row in rows {
250 if row["status"]["confirmed"] != true {
251 continue;
252 }
253 coins.push(Coin {
254 outpoint: OutPoint {
255 txid: row["txid"].as_str().context("missing UTXO txid")?.parse()?,
256 vout: u32::try_from(row["vout"].as_u64().context("missing UTXO index")?)?,
257 },
258 value: row["value"].as_u64().context("missing UTXO value")?,
259 height: row["status"]["block_height"]
260 .as_u64()
261 .context("missing UTXO height")?,
262 path,
263 });
264 }
265 Ok(coins)
266 }
267
268 fn live(&self, account: &Account, coin: &Coin) -> Result<bool, Error> {
269 let unspent = self.call(
270 "gettxout",
271 &[
272 json!(coin.outpoint.txid),
273 json!(coin.outpoint.vout),
274 json!(true),
275 ],
276 )?;
277 if unspent.is_null() {
278 return Ok(false);
279 }
280 let confirmations = config::confirmations(&unspent)?;
281 if confirmations < 1 || (unspent["coinbase"] == true && confirmations < 100) {
282 return Ok(false);
283 }
284 ensure!(
285 unspent["scriptPubKey"]["hex"] == hex::encode(account.script(coin.path)?.as_bytes()),
286 "live coin script disagrees with its wallet path"
287 );
288 let amount = coin_amount(&unspent["value"])?;
289 ensure!(
290 amount.to_sat() == coin.value,
291 "live coin value disagrees with the wallet scan"
292 );
293 Ok(true)
294 }
295
296 fn parent(&self, account: &Account, coin: &Coin) -> Result<Funding, Error> {
297 let block = self.call("getblockhash", &[json!(coin.height)])?;
298 let raw = self.call(
299 "getrawtransaction",
300 &[json!(coin.outpoint.txid), json!(false), block],
301 )?;
302 let funding = Funding {
303 raw_transaction: raw.as_str().context("missing funding bytes")?.to_owned(),
304 vout: coin.outpoint.vout,
305 };
306 let (outpoint, previous) = funding.prevout()?;
307 ensure!(
308 outpoint == coin.outpoint && previous.value.to_sat() == coin.value,
309 "funding transaction disagrees with the scanned coin"
310 );
311 ensure!(
312 previous.script_pubkey == account.script(coin.path)?,
313 "funding transaction disagrees with the wallet path"
314 );
315 Ok(funding)
316 }
317}