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::util::hash::BitcoinHash;
21 use bitcoin::network::constants::Network;
22 use bitcoin::hash_types::{Txid, BlockHash};
24 use std::sync::{Mutex, MutexGuard, Arc};
25 use std::sync::atomic::{AtomicUsize, Ordering};
26 use std::collections::HashSet;
28 use std::marker::PhantomData;
31 /// Used to give chain error details upstream
34 /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
36 /// Chain isn't the one watched
38 /// Tx doesn't exist or is unconfirmed
42 /// An interface to request notification of certain scripts as they appear the
45 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
46 /// called from inside the library in response to ChainListener events, P2P events, or timer
48 pub trait ChainWatchInterface: Sync + Send {
49 /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
50 fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script);
52 /// Provides an outpoint which must be watched for, providing any transactions which spend the
54 fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script);
56 /// Indicates that a listener needs to see all transactions.
57 fn watch_all_txn(&self);
59 /// Gets the script and value in satoshis for a given unspent transaction output given a
60 /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
61 /// bytes are the block height, the next 3 the transaction index within the block, and the
62 /// final two the output within the transaction.
63 fn get_chain_utxo(&self, genesis_hash: BlockHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
65 /// Gets the list of transaction indices within a given block that the ChainWatchInterface is
67 fn filter_block(&self, block: &Block) -> Vec<usize>;
69 /// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
70 /// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
71 /// determine whether they need to re-filter a given block.
72 fn reentered(&self) -> usize;
75 /// An interface to send a transaction to the Bitcoin network.
76 pub trait BroadcasterInterface: Sync + Send {
77 /// Sends a transaction out to (hopefully) be mined.
78 fn broadcast_transaction(&self, tx: &Transaction);
81 /// A trait indicating a desire to listen for events from the chain
82 pub trait ChainListener: Sync + Send {
83 /// Notifies a listener that a block was connected.
85 /// The txn_matched array should be set to references to transactions which matched the
86 /// relevant installed watch outpoints/txn, or the full set of transactions in the block.
88 /// Note that if txn_matched includes only matched transactions, and a new
89 /// transaction/outpoint is watched during a block_connected call, the block *must* be
90 /// re-scanned with the new transaction/outpoints and block_connected should be called
91 /// again with the same header and (at least) the new transactions.
93 /// Note that if non-new transaction/outpoints are be registered during a call, a second call
94 /// *must not* happen.
96 /// This also means those counting confirmations using block_connected callbacks should watch
97 /// for duplicate headers and not count them towards confirmations!
98 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]);
99 /// Notifies a listener that a block was disconnected.
100 /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
101 /// Height must be the one of the block which was disconnected (not new height of the best chain)
102 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
105 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
107 pub enum ConfirmationTarget {
108 /// We are happy with this transaction confirming slowly when feerate drops some.
110 /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
112 /// We'd like this transaction to confirm in the next few blocks.
116 /// A trait which should be implemented to provide feerate information on a number of time
119 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
120 /// called from inside the library in response to ChainListener events, P2P events, or timer
122 pub trait FeeEstimator: Sync + Send {
123 /// Gets estimated satoshis of fee required per 1000 Weight-Units.
125 /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
126 /// don't put us below 1 satoshi-per-byte).
128 /// This translates to:
129 /// * satoshis-per-byte * 250
130 /// * ceil(satoshis-per-kbyte / 4)
131 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
134 /// Minimum relay fee as required by bitcoin network mempool policy.
135 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
137 /// Utility for tracking registered txn/outpoints and checking for matches
138 #[cfg_attr(test, derive(PartialEq))]
139 pub struct ChainWatchedUtil {
142 // We are more conservative in matching during testing to ensure everything matches *exactly*,
143 // even though during normal runtime we take more optimized match approaches...
145 watched_txn: HashSet<(Txid, Script)>,
147 watched_txn: HashSet<Script>,
149 watched_outpoints: HashSet<(Txid, u32)>,
152 impl ChainWatchedUtil {
153 /// Constructs an empty (watches nothing) ChainWatchedUtil
154 pub fn new() -> Self {
157 watched_txn: HashSet::new(),
158 watched_outpoints: HashSet::new(),
162 /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
163 /// been watching for it.
164 pub fn register_tx(&mut self, txid: &Txid, script_pub_key: &Script) -> bool {
165 if self.watch_all { return false; }
168 self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
172 let _tx_unused = txid; // It's used in cfg(test), though
173 self.watched_txn.insert(script_pub_key.clone())
177 /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
178 /// we'd already been watching for it
179 pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
180 if self.watch_all { return false; }
181 self.watched_outpoints.insert(outpoint)
184 /// Sets us to match all transactions, returning true if this is a new setting and false if
185 /// we'd already been set to match everything.
186 pub fn watch_all(&mut self) -> bool {
187 if self.watch_all { return false; }
188 self.watch_all = true;
192 /// Checks if a given transaction matches the current filter.
193 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
197 for out in tx.output.iter() {
199 for &(ref txid, ref script) in self.watched_txn.iter() {
200 if *script == out.script_pubkey {
201 if tx.txid() == *txid {
207 for script in self.watched_txn.iter() {
208 if *script == out.script_pubkey {
213 for input in tx.input.iter() {
214 for outpoint in self.watched_outpoints.iter() {
215 let &(outpoint_hash, outpoint_index) = outpoint;
216 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
225 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
226 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
227 /// parameters with static lifetimes). Other times you can afford a reference, which is more
228 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
229 /// aliases prevents issues such as overly long function definitions.
230 pub type BlockNotifierArc<C> = Arc<BlockNotifier<'static, Arc<ChainListener>, C>>;
232 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
233 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
234 /// lifetimes are more efficient but less flexible, and should be used by default unless static
235 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
236 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
237 /// appropriate type. Defining these type aliases for common usages prevents issues such as
238 /// overly long function definitions.
239 pub type BlockNotifierRef<'a, C> = BlockNotifier<'a, &'a ChainListener, C>;
241 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
242 /// data is registered.
244 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
245 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
246 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
247 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
248 pub struct BlockNotifier<'a, CL: Deref + 'a, C: Deref>
249 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
250 listeners: Mutex<Vec<CL>>,
252 phantom: PhantomData<&'a ()>,
255 impl<'a, CL: Deref + 'a, C: Deref> BlockNotifier<'a, CL, C>
256 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
257 /// Constructs a new BlockNotifier without any listeners.
258 pub fn new(chain_monitor: C) -> BlockNotifier<'a, CL, C> {
260 listeners: Mutex::new(Vec::new()),
262 phantom: PhantomData,
266 /// Register the given listener to receive events.
267 pub fn register_listener(&self, listener: CL) {
268 let mut vec = self.listeners.lock().unwrap();
271 /// Unregister the given listener to no longer
274 /// If the same listener is registered multiple times, unregistering
275 /// will remove ALL occurrences of that listener. Comparison is done using
276 /// the pointer returned by the Deref trait implementation.
277 pub fn unregister_listener(&self, listener: CL) {
278 let mut vec = self.listeners.lock().unwrap();
279 // item is a ref to an abstract thing that dereferences to a ChainListener,
280 // so dereference it twice to get the ChainListener itself
281 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
284 /// Notify listeners that a block was connected given a full, unfiltered block.
286 /// Handles re-scanning the block and calling block_connected again if listeners register new
287 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
288 pub fn block_connected(&self, block: &Block, height: u32) {
289 let mut reentered = true;
291 let matched_indexes = self.chain_monitor.filter_block(block);
292 let mut matched_txn = Vec::new();
293 for index in matched_indexes.iter() {
294 matched_txn.push(&block.txdata[*index]);
296 reentered = self.block_connected_checked(&block.header, height, matched_txn.as_slice(), matched_indexes.as_slice());
300 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
301 /// block which matched the filter (probably using does_match_tx).
303 /// Returns true if notified listeners registered additional watch data (implying that the
304 /// block must be re-scanned and this function called again prior to further block_connected
305 /// calls, see ChainListener::block_connected for more info).
306 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) -> bool {
307 let last_seen = self.chain_monitor.reentered();
309 let listeners = self.listeners.lock().unwrap();
310 for listener in listeners.iter() {
311 listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
313 return last_seen != self.chain_monitor.reentered();
316 /// Notify listeners that a block was disconnected.
317 pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
318 let listeners = self.listeners.lock().unwrap();
319 for listener in listeners.iter() {
320 listener.block_disconnected(&header, disconnected_height);
325 /// Utility to capture some common parts of ChainWatchInterface implementors.
327 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
328 pub struct ChainWatchInterfaceUtil {
330 watched: Mutex<ChainWatchedUtil>,
331 reentered: AtomicUsize,
334 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
335 // only comparing a subset of fields (essentially just checking that the set of things we're
336 // watching is the same).
338 impl PartialEq for ChainWatchInterfaceUtil {
339 fn eq(&self, o: &Self) -> bool {
340 self.network == o.network &&
341 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
345 /// Register listener
346 impl ChainWatchInterface for ChainWatchInterfaceUtil {
347 fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
348 let mut watched = self.watched.lock().unwrap();
349 if watched.register_tx(txid, script_pub_key) {
350 self.reentered.fetch_add(1, Ordering::Relaxed);
354 fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
355 let mut watched = self.watched.lock().unwrap();
356 if watched.register_outpoint(outpoint, out_script) {
357 self.reentered.fetch_add(1, Ordering::Relaxed);
361 fn watch_all_txn(&self) {
362 let mut watched = self.watched.lock().unwrap();
363 if watched.watch_all() {
364 self.reentered.fetch_add(1, Ordering::Relaxed);
368 fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
369 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
370 return Err(ChainError::NotWatched);
372 Err(ChainError::NotSupported)
375 fn filter_block(&self, block: &Block) -> Vec<usize> {
376 let mut matched_index = Vec::new();
378 let watched = self.watched.lock().unwrap();
379 for (index, transaction) in block.txdata.iter().enumerate() {
380 if self.does_match_tx_unguarded(transaction, &watched) {
381 matched_index.push(index);
388 fn reentered(&self) -> usize {
389 self.reentered.load(Ordering::Relaxed)
393 impl ChainWatchInterfaceUtil {
394 /// Creates a new ChainWatchInterfaceUtil for the given network
395 pub fn new(network: Network) -> ChainWatchInterfaceUtil {
396 ChainWatchInterfaceUtil {
398 watched: Mutex::new(ChainWatchedUtil::new()),
399 reentered: AtomicUsize::new(1),
403 /// Checks if a given transaction matches the current filter.
404 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
405 let watched = self.watched.lock().unwrap();
406 self.does_match_tx_unguarded (tx, &watched)
409 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
410 watched.does_match_tx(tx)
416 use ln::functional_test_utils::{create_chanmon_cfgs, create_node_cfgs};
417 use super::{BlockNotifier, ChainListener};
421 fn register_listener_test() {
422 let chanmon_cfgs = create_chanmon_cfgs(1);
423 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
424 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
425 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
426 let listener = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
427 block_notifier.register_listener(listener);
428 let vec = block_notifier.listeners.lock().unwrap();
429 assert_eq!(vec.len(), 1);
430 let item = vec.first().clone().unwrap();
431 assert!(ptr::eq(&(**item), &(*listener)));
435 fn unregister_single_listener_test() {
436 let chanmon_cfgs = create_chanmon_cfgs(2);
437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
438 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
439 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
440 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
441 block_notifier.register_listener(listener1);
442 block_notifier.register_listener(listener2);
443 let vec = block_notifier.listeners.lock().unwrap();
444 assert_eq!(vec.len(), 2);
446 block_notifier.unregister_listener(listener1);
447 let vec = block_notifier.listeners.lock().unwrap();
448 assert_eq!(vec.len(), 1);
449 let item = vec.first().clone().unwrap();
450 assert!(ptr::eq(&(**item), &(*listener2)));
454 fn unregister_single_listener_ref_test() {
455 let chanmon_cfgs = create_chanmon_cfgs(2);
456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
457 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
458 block_notifier.register_listener(&node_cfgs[0].chan_monitor.simple_monitor as &ChainListener);
459 block_notifier.register_listener(&node_cfgs[1].chan_monitor.simple_monitor as &ChainListener);
460 let vec = block_notifier.listeners.lock().unwrap();
461 assert_eq!(vec.len(), 2);
463 block_notifier.unregister_listener(&node_cfgs[0].chan_monitor.simple_monitor);
464 let vec = block_notifier.listeners.lock().unwrap();
465 assert_eq!(vec.len(), 1);
466 let item = vec.first().clone().unwrap();
467 assert!(ptr::eq(&(**item), &(*&node_cfgs[1].chan_monitor.simple_monitor)));
471 fn unregister_multiple_of_the_same_listeners_test() {
472 let chanmon_cfgs = create_chanmon_cfgs(2);
473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
474 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
475 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
476 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
477 block_notifier.register_listener(listener1);
478 block_notifier.register_listener(listener1);
479 block_notifier.register_listener(listener2);
480 let vec = block_notifier.listeners.lock().unwrap();
481 assert_eq!(vec.len(), 3);
483 block_notifier.unregister_listener(listener1);
484 let vec = block_notifier.listeners.lock().unwrap();
485 assert_eq!(vec.len(), 1);
486 let item = vec.first().clone().unwrap();
487 assert!(ptr::eq(&(**item), &(*listener2)));