1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
13 //! Includes traits for monitoring and receiving notifications of new blocks and block
14 //! disconnections, transaction broadcasting, and feerate information requests.
16 use bitcoin::blockdata::block::{Block, BlockHeader};
17 use bitcoin::blockdata::transaction::Transaction;
18 use bitcoin::blockdata::script::Script;
19 use bitcoin::blockdata::constants::genesis_block;
20 use bitcoin::network::constants::Network;
21 use bitcoin::hash_types::{Txid, BlockHash};
23 use std::sync::{Mutex, MutexGuard, Arc};
24 use std::sync::atomic::{AtomicUsize, Ordering};
25 use std::collections::HashSet;
27 use std::marker::PhantomData;
30 /// Used to give chain error details upstream
33 /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
35 /// Chain isn't the one watched
37 /// Tx doesn't exist or is unconfirmed
41 /// An interface to request notification of certain scripts as they appear the
44 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
45 /// called from inside the library in response to ChainListener events, P2P events, or timer
47 pub trait ChainWatchInterface: Sync + Send {
48 /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
49 fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script);
51 /// Provides an outpoint which must be watched for, providing any transactions which spend the
53 fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script);
55 /// Indicates that a listener needs to see all transactions.
56 fn watch_all_txn(&self);
58 /// Gets the script and value in satoshis for a given unspent transaction output given a
59 /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
60 /// bytes are the block height, the next 3 the transaction index within the block, and the
61 /// final two the output within the transaction.
62 fn get_chain_utxo(&self, genesis_hash: BlockHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
64 /// Gets the list of transaction indices within a given block that the ChainWatchInterface is
66 fn filter_block(&self, block: &Block) -> Vec<usize>;
68 /// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
69 /// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
70 /// determine whether they need to re-filter a given block.
71 fn reentered(&self) -> usize;
74 /// An interface to send a transaction to the Bitcoin network.
75 pub trait BroadcasterInterface: Sync + Send {
76 /// Sends a transaction out to (hopefully) be mined.
77 fn broadcast_transaction(&self, tx: &Transaction);
80 /// A trait indicating a desire to listen for events from the chain
81 pub trait ChainListener: Sync + Send {
82 /// Notifies a listener that a block was connected.
84 /// The txn_matched array should be set to references to transactions which matched the
85 /// relevant installed watch outpoints/txn, or the full set of transactions in the block.
87 /// Note that if txn_matched includes only matched transactions, and a new
88 /// transaction/outpoint is watched during a block_connected call, the block *must* be
89 /// re-scanned with the new transaction/outpoints and block_connected should be called
90 /// again with the same header and (at least) the new transactions.
92 /// Note that if non-new transaction/outpoints are be registered during a call, a second call
93 /// *must not* happen.
95 /// This also means those counting confirmations using block_connected callbacks should watch
96 /// for duplicate headers and not count them towards confirmations!
97 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]);
98 /// Notifies a listener that a block was disconnected.
99 /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
100 /// Height must be the one of the block which was disconnected (not new height of the best chain)
101 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
104 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
106 pub enum ConfirmationTarget {
107 /// We are happy with this transaction confirming slowly when feerate drops some.
109 /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
111 /// We'd like this transaction to confirm in the next few blocks.
115 /// A trait which should be implemented to provide feerate information on a number of time
118 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
119 /// called from inside the library in response to ChainListener events, P2P events, or timer
121 pub trait FeeEstimator: Sync + Send {
122 /// Gets estimated satoshis of fee required per 1000 Weight-Units.
124 /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
125 /// don't put us below 1 satoshi-per-byte).
127 /// This translates to:
128 /// * satoshis-per-byte * 250
129 /// * ceil(satoshis-per-kbyte / 4)
130 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
133 /// Minimum relay fee as required by bitcoin network mempool policy.
134 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
136 /// Utility for tracking registered txn/outpoints and checking for matches
137 #[cfg_attr(test, derive(PartialEq))]
138 pub struct ChainWatchedUtil {
141 // We are more conservative in matching during testing to ensure everything matches *exactly*,
142 // even though during normal runtime we take more optimized match approaches...
144 watched_txn: HashSet<(Txid, Script)>,
146 watched_txn: HashSet<Script>,
148 watched_outpoints: HashSet<(Txid, u32)>,
151 impl ChainWatchedUtil {
152 /// Constructs an empty (watches nothing) ChainWatchedUtil
153 pub fn new() -> Self {
156 watched_txn: HashSet::new(),
157 watched_outpoints: HashSet::new(),
161 /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
162 /// been watching for it.
163 pub fn register_tx(&mut self, txid: &Txid, script_pub_key: &Script) -> bool {
164 if self.watch_all { return false; }
167 self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
171 let _tx_unused = txid; // It's used in cfg(test), though
172 self.watched_txn.insert(script_pub_key.clone())
176 /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
177 /// we'd already been watching for it
178 pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
179 if self.watch_all { return false; }
180 self.watched_outpoints.insert(outpoint)
183 /// Sets us to match all transactions, returning true if this is a new setting and false if
184 /// we'd already been set to match everything.
185 pub fn watch_all(&mut self) -> bool {
186 if self.watch_all { return false; }
187 self.watch_all = true;
191 /// Checks if a given transaction matches the current filter.
192 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
196 for out in tx.output.iter() {
198 for &(ref txid, ref script) in self.watched_txn.iter() {
199 if *script == out.script_pubkey {
200 if tx.txid() == *txid {
206 for script in self.watched_txn.iter() {
207 if *script == out.script_pubkey {
212 for input in tx.input.iter() {
213 for outpoint in self.watched_outpoints.iter() {
214 let &(outpoint_hash, outpoint_index) = outpoint;
215 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
224 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
225 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
226 /// parameters with static lifetimes). Other times you can afford a reference, which is more
227 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
228 /// aliases prevents issues such as overly long function definitions.
230 /// (C-not exported) as we let clients handle any reference counting they need to do
231 pub type BlockNotifierArc<C> = Arc<BlockNotifier<'static, Arc<ChainListener>, C>>;
233 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
234 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
235 /// lifetimes are more efficient but less flexible, and should be used by default unless static
236 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
237 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
238 /// appropriate type. Defining these type aliases for common usages prevents issues such as
239 /// overly long function definitions.
240 pub type BlockNotifierRef<'a, C> = BlockNotifier<'a, &'a ChainListener, C>;
242 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
243 /// data is registered.
245 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
246 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
247 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
248 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
249 pub struct BlockNotifier<'a, CL: Deref + 'a, C: Deref>
250 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
251 listeners: Mutex<Vec<CL>>,
253 phantom: PhantomData<&'a ()>,
256 impl<'a, CL: Deref + 'a, C: Deref> BlockNotifier<'a, CL, C>
257 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
258 /// Constructs a new BlockNotifier without any listeners.
259 pub fn new(chain_monitor: C) -> BlockNotifier<'a, CL, C> {
261 listeners: Mutex::new(Vec::new()),
263 phantom: PhantomData,
267 /// Register the given listener to receive events.
268 pub fn register_listener(&self, listener: CL) {
269 let mut vec = self.listeners.lock().unwrap();
272 /// Unregister the given listener to no longer
275 /// If the same listener is registered multiple times, unregistering
276 /// will remove ALL occurrences of that listener. Comparison is done using
277 /// the pointer returned by the Deref trait implementation.
279 /// (C-not exported) because the equality check would always fail
280 pub fn unregister_listener(&self, listener: CL) {
281 let mut vec = self.listeners.lock().unwrap();
282 // item is a ref to an abstract thing that dereferences to a ChainListener,
283 // so dereference it twice to get the ChainListener itself
284 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
287 /// Notify listeners that a block was connected given a full, unfiltered block.
289 /// Handles re-scanning the block and calling block_connected again if listeners register new
290 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
291 pub fn block_connected(&self, block: &Block, height: u32) {
292 let mut reentered = true;
294 let matched_indexes = self.chain_monitor.filter_block(block);
295 let mut matched_txn = Vec::new();
296 for index in matched_indexes.iter() {
297 matched_txn.push(&block.txdata[*index]);
299 reentered = self.block_connected_checked(&block.header, height, matched_txn.as_slice(), matched_indexes.as_slice());
303 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
304 /// block which matched the filter (probably using does_match_tx).
306 /// Returns true if notified listeners registered additional watch data (implying that the
307 /// block must be re-scanned and this function called again prior to further block_connected
308 /// calls, see ChainListener::block_connected for more info).
309 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) -> bool {
310 let last_seen = self.chain_monitor.reentered();
312 let listeners = self.listeners.lock().unwrap();
313 for listener in listeners.iter() {
314 listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
316 return last_seen != self.chain_monitor.reentered();
319 /// Notify listeners that a block was disconnected.
320 pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
321 let listeners = self.listeners.lock().unwrap();
322 for listener in listeners.iter() {
323 listener.block_disconnected(&header, disconnected_height);
328 /// Utility to capture some common parts of ChainWatchInterface implementors.
330 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
331 pub struct ChainWatchInterfaceUtil {
333 watched: Mutex<ChainWatchedUtil>,
334 reentered: AtomicUsize,
337 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
338 // only comparing a subset of fields (essentially just checking that the set of things we're
339 // watching is the same).
341 impl PartialEq for ChainWatchInterfaceUtil {
342 fn eq(&self, o: &Self) -> bool {
343 self.network == o.network &&
344 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
348 /// Register listener
349 impl ChainWatchInterface for ChainWatchInterfaceUtil {
350 fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
351 let mut watched = self.watched.lock().unwrap();
352 if watched.register_tx(txid, script_pub_key) {
353 self.reentered.fetch_add(1, Ordering::Relaxed);
357 fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
358 let mut watched = self.watched.lock().unwrap();
359 if watched.register_outpoint(outpoint, out_script) {
360 self.reentered.fetch_add(1, Ordering::Relaxed);
364 fn watch_all_txn(&self) {
365 let mut watched = self.watched.lock().unwrap();
366 if watched.watch_all() {
367 self.reentered.fetch_add(1, Ordering::Relaxed);
371 fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
372 if genesis_hash != genesis_block(self.network).header.block_hash() {
373 return Err(ChainError::NotWatched);
375 Err(ChainError::NotSupported)
378 fn filter_block(&self, block: &Block) -> Vec<usize> {
379 let mut matched_index = Vec::new();
381 let watched = self.watched.lock().unwrap();
382 for (index, transaction) in block.txdata.iter().enumerate() {
383 if self.does_match_tx_unguarded(transaction, &watched) {
384 matched_index.push(index);
391 fn reentered(&self) -> usize {
392 self.reentered.load(Ordering::Relaxed)
396 impl ChainWatchInterfaceUtil {
397 /// Creates a new ChainWatchInterfaceUtil for the given network
398 pub fn new(network: Network) -> ChainWatchInterfaceUtil {
399 ChainWatchInterfaceUtil {
401 watched: Mutex::new(ChainWatchedUtil::new()),
402 reentered: AtomicUsize::new(1),
406 /// Checks if a given transaction matches the current filter.
407 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
408 let watched = self.watched.lock().unwrap();
409 self.does_match_tx_unguarded (tx, &watched)
412 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
413 watched.does_match_tx(tx)
419 use ln::functional_test_utils::{create_chanmon_cfgs, create_node_cfgs};
420 use super::{BlockNotifier, ChainListener};
424 fn register_listener_test() {
425 let chanmon_cfgs = create_chanmon_cfgs(1);
426 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
427 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
428 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
429 let listener = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
430 block_notifier.register_listener(listener);
431 let vec = block_notifier.listeners.lock().unwrap();
432 assert_eq!(vec.len(), 1);
433 let item = vec.first().clone().unwrap();
434 assert!(ptr::eq(&(**item), &(*listener)));
438 fn unregister_single_listener_test() {
439 let chanmon_cfgs = create_chanmon_cfgs(2);
440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
441 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
442 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
443 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
444 block_notifier.register_listener(listener1);
445 block_notifier.register_listener(listener2);
446 let vec = block_notifier.listeners.lock().unwrap();
447 assert_eq!(vec.len(), 2);
449 block_notifier.unregister_listener(listener1);
450 let vec = block_notifier.listeners.lock().unwrap();
451 assert_eq!(vec.len(), 1);
452 let item = vec.first().clone().unwrap();
453 assert!(ptr::eq(&(**item), &(*listener2)));
457 fn unregister_single_listener_ref_test() {
458 let chanmon_cfgs = create_chanmon_cfgs(2);
459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
460 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
461 block_notifier.register_listener(&node_cfgs[0].chan_monitor.simple_monitor as &ChainListener);
462 block_notifier.register_listener(&node_cfgs[1].chan_monitor.simple_monitor as &ChainListener);
463 let vec = block_notifier.listeners.lock().unwrap();
464 assert_eq!(vec.len(), 2);
466 block_notifier.unregister_listener(&node_cfgs[0].chan_monitor.simple_monitor);
467 let vec = block_notifier.listeners.lock().unwrap();
468 assert_eq!(vec.len(), 1);
469 let item = vec.first().clone().unwrap();
470 assert!(ptr::eq(&(**item), &(*&node_cfgs[1].chan_monitor.simple_monitor)));
474 fn unregister_multiple_of_the_same_listeners_test() {
475 let chanmon_cfgs = create_chanmon_cfgs(2);
476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
477 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
478 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
479 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
480 block_notifier.register_listener(listener1);
481 block_notifier.register_listener(listener1);
482 block_notifier.register_listener(listener2);
483 let vec = block_notifier.listeners.lock().unwrap();
484 assert_eq!(vec.len(), 3);
486 block_notifier.unregister_listener(listener1);
487 let vec = block_notifier.listeners.lock().unwrap();
488 assert_eq!(vec.len(), 1);
489 let item = vec.first().clone().unwrap();
490 assert!(ptr::eq(&(**item), &(*listener2)));