bark-bitcoin-ext 0.1.1

Extension library to the rust-bitcoin ecosystem crates used in bark
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#[cfg(feature = "rpc-socks5-proxy")]
mod socks5_transport;

pub use bdk_bitcoind_rpc::bitcoincore_rpc::{self, json, jsonrpc, Auth, Client, Error, RpcApi};

use std::borrow::Borrow;
use std::collections::HashMap;

use bdk_bitcoind_rpc::bitcoincore_rpc::Result as RpcResult;
use bitcoin::address::NetworkUnchecked;
use bitcoin::hex::FromHex;
use bitcoin::{Address, Amount, FeeRate, Transaction, Txid};
use serde::{self, Deserialize, Serialize};
use serde::de::Error as SerdeError;

use crate::{BlockHeight, BlockRef, TxStatus, DEEPLY_CONFIRMED};

#[cfg(all(feature = "wasm-web", feature = "rpc-socks5-proxy"))]
compile_error!("`wasm-web` does not support the `rpc-socks5-proxy` feature");

/// Error code for RPC_VERIFY_ALREADY_IN_UTXO_SET.
const RPC_VERIFY_ALREADY_IN_UTXO_SET: i32 = -27;

/// Error code for RPC_INVALID_ADDRESS_OR_KEY, used when a tx is not found.
const RPC_INVALID_ADDRESS_OR_KEY: i32 = -5;

/// Clonable bitcoind rpc client.
#[derive(Debug)]
pub struct BitcoinRpcClient {
	client: Client,
	url: String,
	auth: Auth,
}

impl BitcoinRpcClient {
	pub fn new(url: &str, auth: Auth) -> Result<Self, Error> {
		Ok(BitcoinRpcClient {
			client: Client::new(url, auth.clone())?,
			url: url.to_owned(),
			auth: auth,
		})
	}
}

impl RpcApi for BitcoinRpcClient {
	fn call<T: for<'a> serde::de::Deserialize<'a>>(
		&self, cmd: &str, args: &[serde_json::Value],
	) -> Result<T, Error> {
		self.client.call(cmd, args)
	}
}

impl Clone for BitcoinRpcClient {
	fn clone(&self) -> Self {
		Self::new(&self.url, self.auth.clone()).unwrap()
	}
}

/// A module used for serde serialization of bytes in hexadecimal format.
///
/// The module is compatible with the serde attribute.
mod serde_hex {
	use bitcoin::hex::{DisplayHex, FromHex};
	use serde::de::Error;
	use serde::{Deserializer, Serializer};

	pub fn serialize<S: Serializer>(b: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
		s.serialize_str(&b.to_lower_hex_string())
	}

	pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
		let hex_str: String = ::serde::Deserialize::deserialize(d)?;
		Ok(FromHex::from_hex(&hex_str).map_err(D::Error::custom)?)
	}

	pub mod opt {
		use bitcoin::hex::{DisplayHex, FromHex};
		use serde::de::Error;
		use serde::{Deserializer, Serializer};

		pub fn serialize<S: Serializer>(b: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
			match *b {
				None => s.serialize_none(),
				Some(ref b) => s.serialize_str(&b.to_lower_hex_string()),
			}
		}

		pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
			let hex_str: String = ::serde::Deserialize::deserialize(d)?;
			Ok(Some(FromHex::from_hex(&hex_str).map_err(D::Error::custom)?))
		}
	}
}

/// deserialize_hex_array_opt deserializes a vector of hex-encoded byte arrays.
fn deserialize_hex_array_opt<'de, D>(deserializer: D) -> Result<Option<Vec<Vec<u8>>>, D::Error>
where
	D: serde::Deserializer<'de>,
{
	//TODO(stevenroose) Revisit when issue is fixed:
	// https://github.com/serde-rs/serde/issues/723

	let v: Vec<String> = Vec::deserialize(deserializer)?;
	let mut res = Vec::new();
	for h in v.into_iter() {
		res.push(FromHex::from_hex(&h).map_err(D::Error::custom)?);
	}
	Ok(Some(res))
}

#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRawTransactionResultVinScriptSig {
	pub asm: String,
	#[serde(with = "serde_hex")]
	pub hex: Vec<u8>,
}

#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRawTransactionResultVin {
	pub sequence: u32,
	/// The raw scriptSig in case of a coinbase tx.
	#[serde(default, with = "serde_hex::opt")]
	pub coinbase: Option<Vec<u8>>,
	/// Not provided for coinbase txs.
	pub txid: Option<Txid>,
	/// Not provided for coinbase txs.
	pub vout: Option<u32>,
	/// The scriptSig in case of a non-coinbase tx.
	pub script_sig: Option<GetRawTransactionResultVinScriptSig>,
	/// Not provided for coinbase txs.
	#[serde(default, deserialize_with = "deserialize_hex_array_opt")]
	pub txinwitness: Option<Vec<Vec<u8>>>,
}

#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRawTransactionResultVout {
	#[serde(with = "bitcoin::amount::serde::as_btc")]
	pub value: Amount,
	pub n: u32,
	pub script_pub_key: GetRawTransactionResultVoutScriptPubKey,
}

#[allow(non_camel_case_types)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ScriptPubkeyType {
	Nonstandard,
	Anchor,
	Pubkey,
	PubkeyHash,
	ScriptHash,
	MultiSig,
	NullData,
	Witness_v0_KeyHash,
	Witness_v0_ScriptHash,
	Witness_v1_Taproot,
	Witness_Unknown,
}

#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRawTransactionResultVoutScriptPubKey {
	pub asm: String,
	#[serde(with = "serde_hex")]
	pub hex: Vec<u8>,
	pub req_sigs: Option<usize>,
	#[serde(rename = "type")]
	pub type_: Option<ScriptPubkeyType>,
	// Deprecated in Bitcoin Core 22
	#[serde(default)]
	pub addresses: Vec<Address<NetworkUnchecked>>,
	// Added in Bitcoin Core 22
	#[serde(default)]
	pub address: Option<Address<NetworkUnchecked>>,
}

#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetRawTransactionResult {
	#[serde(rename = "in_active_chain")]
	pub in_active_chain: Option<bool>,
	#[serde(with = "serde_hex")]
	pub hex: Vec<u8>,
	pub txid: Txid,
	pub hash: bitcoin::Wtxid,
	pub size: usize,
	pub vsize: usize,
	pub version: u32,
	pub locktime: u32,
	pub vin: Vec<GetRawTransactionResultVin>,
	pub vout: Vec<GetRawTransactionResultVout>,
	pub blockhash: Option<bitcoin::BlockHash>,
	pub confirmations: Option<u32>,
	pub time: Option<usize>,
	pub blocktime: Option<usize>,
}

/// Result from the `submitpackage` RPC call.
#[derive(Clone, Debug, Deserialize)]
pub struct SubmitPackageResult {
	#[serde(rename = "tx-results")]
	pub tx_results: HashMap<bitcoin::Wtxid, SubmitPackageTxResult>,
	pub package_msg: String,
}

/// Per-transaction result from the `submitpackage` RPC call.
#[derive(Clone, Debug, Deserialize)]
pub struct SubmitPackageTxResult {
	pub txid: Txid,
	pub error: Option<String>,
}

/// Shorthand for converting a variable into a serde_json::Value.
fn into_json<T>(val: T) -> RpcResult<serde_json::Value>
where
	T: serde::ser::Serialize,
{
	Ok(serde_json::to_value(val)?)
}

/// Shorthand for converting an Option into an Option<serde_json::Value>.
fn opt_into_json<T>(opt: Option<T>) -> RpcResult<serde_json::Value>
where
	T: serde::ser::Serialize,
{
	match opt {
		Some(val) => Ok(into_json(val)?),
		None => Ok(serde_json::Value::Null),
	}
}

/// Handle default values in the argument list
///
/// Substitute `Value::Null`s with corresponding values from `defaults` table,
/// except when they are trailing, in which case just skip them altogether
/// in returned list.
///
/// Note, that `defaults` corresponds to the last elements of `args`.
///
/// ```norust
/// arg1 arg2 arg3 arg4
///           def1 def2
/// ```
///
/// Elements of `args` without corresponding `defaults` value, won't
/// be substituted, because they are required.
fn handle_defaults<'a, 'b>(
	args: &'a mut [serde_json::Value],
	defaults: &'b [serde_json::Value],
) -> &'a [serde_json::Value] {
	assert!(args.len() >= defaults.len());

	// Pass over the optional arguments in backwards order, filling in defaults after the first
	// non-null optional argument has been observed.
	let mut first_non_null_optional_idx = None;
	for i in 0..defaults.len() {
		let args_i = args.len() - 1 - i;
		let defaults_i = defaults.len() - 1 - i;
		if args[args_i] == serde_json::Value::Null {
			if first_non_null_optional_idx.is_some() {
				if defaults[defaults_i] == serde_json::Value::Null {
					panic!("Missing `default` for argument idx {}", args_i);
				}
				args[args_i] = defaults[defaults_i].clone();
			}
		} else if first_non_null_optional_idx.is_none() {
			first_non_null_optional_idx = Some(args_i);
		}
	}

	let required_num = args.len() - defaults.len();

	if let Some(i) = first_non_null_optional_idx {
		&args[..i + 1]
	} else {
		&args[..required_num]
	}
}

/// Shorthand for `serde_json::Value::Null`.
fn null() -> serde_json::Value {
	serde_json::Value::Null
}

pub trait BitcoinRpcErrorExt: Borrow<Error> {
	/// Whether this error indicates that the tx was not found.
	fn is_not_found(&self) -> bool {
		if let Error::JsonRpc(jsonrpc::Error::Rpc(e)) = self.borrow() {
			e.code == RPC_INVALID_ADDRESS_OR_KEY
		} else {
			false
		}
	}

	/// Whether this error indicates that the tx is already in the utxo set.
	fn is_in_utxo_set(&self) -> bool {
		if let Error::JsonRpc(jsonrpc::Error::Rpc(e)) = self.borrow() {
			e.code == RPC_VERIFY_ALREADY_IN_UTXO_SET
		} else {
			false
		}
	}

	fn is_already_in_mempool(&self) -> bool {
		if let Error::JsonRpc(jsonrpc::Error::Rpc(e)) = self.borrow() {
			e.message.contains("txn-already-in-mempool")
		} else {
			false
		}
	}
}
impl BitcoinRpcErrorExt for Error {}

pub trait BitcoinRpcExt: RpcApi {
	fn custom_get_raw_transaction_info(
		&self,
		txid: Txid,
		block_hash: Option<&bitcoin::BlockHash>,
	) -> RpcResult<Option<GetRawTransactionResult>> {
		let mut args = [into_json(txid)?, into_json(true)?, opt_into_json(block_hash)?];
		match self.call("getrawtransaction", handle_defaults(&mut args, &[null()])) {
			Ok(ret) => Ok(Some(ret)),
			Err(e) if e.is_not_found() => Ok(None),
			Err(e) => Err(e),
		}
	}

	fn broadcast_tx(&self, tx: &Transaction) -> Result<(), Error> {
		match self.send_raw_transaction(tx) {
			Ok(_) => Ok(()),
			Err(e) if e.is_in_utxo_set() => Ok(()),
			Err(e) => Err(e),
		}
	}

	fn tip(&self) -> Result<BlockRef, Error> {
		let height = self.get_block_count()?;
		let hash = self.get_block_hash(height)?;
		Ok(BlockRef { height: height as BlockHeight, hash })
	}

	fn deep_tip(&self) -> Result<BlockRef, Error> {
		let tip = self.get_block_count()?;
		let height = tip.saturating_sub(DEEPLY_CONFIRMED as u64);
		let hash = self.get_block_hash(height)?;
		Ok(BlockRef { height: height as BlockHeight, hash })
	}

	fn get_block_by_height(&self, height: BlockHeight) -> Result<BlockRef, Error> {
		let hash = self.get_block_hash(height as u64)?;
		Ok(BlockRef { height, hash })
	}

	fn tx_status(&self, txid: Txid) -> Result<TxStatus, Error> {
		match self.custom_get_raw_transaction_info(txid, None)? {
			Some(tx) => match tx.blockhash {
				Some(hash) => {
					let block = self.get_block_header_info(&hash)?;
					if block.confirmations > 0 {
						Ok(TxStatus::Confirmed(BlockRef { height: block.height as BlockHeight, hash: block.hash }))
					} else {
						Ok(TxStatus::Mempool)
					}
				},
				None => Ok(TxStatus::Mempool),
			},
			None => Ok(TxStatus::NotFound)
		}
	}

	fn submit_package(&self, txs: &[impl Borrow<Transaction>]) -> Result<SubmitPackageResult, Error> {
		let hexes = txs.iter()
			.map(|t| bitcoin::consensus::encode::serialize_hex(t.borrow()))
			.collect::<Vec<_>>();
		self.call("submitpackage", &[hexes.into()])
	}

	/// Get the transaction currently spending a given outpoint from the mempool.
	///
	/// Returns None if the outpoint is not being spent by any mempool transaction.
	fn get_mempool_spending_tx(
		&self,
		outpoint: bitcoin::OutPoint,
	) -> Result<Option<Txid>, Error> {
		// Get all mempool txids
		let mempool_txids: Vec<Txid> = self.call("getrawmempool", &[false.into()])?;

		for txid in mempool_txids {
			let tx = self.get_raw_transaction(&txid, None)?;
			for input in &tx.input {
				if input.previous_output == outpoint {
					return Ok(Some(txid));
				}
			}
		}
		Ok(None)
	}

	/// Estimate the effective feerate of a mempool transaction.
	///
	/// Returns the effective feerate considering ancestors and CPFP from direct descendants.
	/// Returns None if the transaction is not in the mempool.
	fn estimate_mempool_feerate(
		&self,
		txid: Txid,
	) -> RpcResult<Option<FeeRate>> {
		let entry = match self.get_mempool_entry(&txid) {
			Ok(e) => e,
			Err(e) if e.is_not_found() => return Ok(None),
			Err(e) => return Err(e),
		};

		// Compute ancestor fee rate: sat/kwu = sat * 1000 / (vbytes * 4) = sat * 250 / vbytes
		let ancestor_feerate = |e: &json::GetMempoolEntryResult| -> Result<FeeRate, Error> {
			Ok(FeeRate::from_sat_per_kwu(
				e.fees.ancestor.to_sat() * 250u64.checked_div(e.ancestor_size)
					.ok_or_else(|| Error::UnexpectedStructure)?
			))
		};

		// Start with this tx's ancestor fee rate
		let mut feerate = ancestor_feerate(&entry)?;

		// Check direct descendants - if any has better ancestor rate, use that (CPFP)
		for descendant_txid in &entry.spent_by {
			if let Ok(desc_entry) = self.get_mempool_entry(descendant_txid) {
				feerate = std::cmp::max(feerate, ancestor_feerate(&desc_entry)?);
			}
		}

		Ok(Some(feerate))
	}
}

impl <T: RpcApi> BitcoinRpcExt for T {}

/// Creates a bitcoind RPC client, optionally routing through a SOCKS5 proxy.
///
/// When no proxy is set, the standard transport is used.
/// When a proxy is set, a ureq-based transport routes traffic through the SOCKS5 proxy.
pub fn create_client(
	url: &str,
	auth: Auth,
	#[cfg(feature = "rpc-socks5-proxy")]
	socks5_proxy: Option<&str>,
) -> Result<Client, Error> {
	#[cfg(feature = "rpc-socks5-proxy")]
	if let Some(proxy) = socks5_proxy {
		let (user, pass) = auth.get_user_pass()?;
		let rpc_auth = user.map(|u| (u, pass));
		let transport = socks5_transport::Socks5Transport::new(url, proxy, rpc_auth)
			.map_err(|e| Error::JsonRpc(jsonrpc::Error::Transport(e.into())))?;

		return Ok(Client::from_jsonrpc(jsonrpc::Client::with_transport(transport)));
	}
	Client::new(url, auth)
}