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<Target = ChainListener + 'a> + 'a, C: Deref> where C::Target: ChainWatchInterface {
249 listeners: Mutex<Vec<CL>>,
251 phantom: PhantomData<&'a ()>,
254 impl<'a, CL: Deref<Target = ChainListener + 'a> + 'a, C: Deref> BlockNotifier<'a, CL, C> where C::Target: ChainWatchInterface {
255 /// Constructs a new BlockNotifier without any listeners.
256 pub fn new(chain_monitor: C) -> BlockNotifier<'a, CL, C> {
258 listeners: Mutex::new(Vec::new()),
260 phantom: PhantomData,
264 /// Register the given listener to receive events.
265 pub fn register_listener(&self, listener: CL) {
266 let mut vec = self.listeners.lock().unwrap();
269 /// Unregister the given listener to no longer
272 /// If the same listener is registered multiple times, unregistering
273 /// will remove ALL occurrences of that listener. Comparison is done using
274 /// the pointer returned by the Deref trait implementation.
275 pub fn unregister_listener(&self, listener: CL) {
276 let mut vec = self.listeners.lock().unwrap();
277 // item is a ref to an abstract thing that dereferences to a ChainListener,
278 // so dereference it twice to get the ChainListener itself
279 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
282 /// Notify listeners that a block was connected given a full, unfiltered block.
284 /// Handles re-scanning the block and calling block_connected again if listeners register new
285 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
286 pub fn block_connected(&self, block: &Block, height: u32) {
287 let mut reentered = true;
289 let matched_indexes = self.chain_monitor.filter_block(block);
290 let mut matched_txn = Vec::new();
291 for index in matched_indexes.iter() {
292 matched_txn.push(&block.txdata[*index]);
294 reentered = self.block_connected_checked(&block.header, height, matched_txn.as_slice(), matched_indexes.as_slice());
298 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
299 /// block which matched the filter (probably using does_match_tx).
301 /// Returns true if notified listeners registered additional watch data (implying that the
302 /// block must be re-scanned and this function called again prior to further block_connected
303 /// calls, see ChainListener::block_connected for more info).
304 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) -> bool {
305 let last_seen = self.chain_monitor.reentered();
307 let listeners = self.listeners.lock().unwrap();
308 for listener in listeners.iter() {
309 listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
311 return last_seen != self.chain_monitor.reentered();
314 /// Notify listeners that a block was disconnected.
315 pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
316 let listeners = self.listeners.lock().unwrap();
317 for listener in listeners.iter() {
318 listener.block_disconnected(&header, disconnected_height);
323 /// Utility to capture some common parts of ChainWatchInterface implementors.
325 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
326 pub struct ChainWatchInterfaceUtil {
328 watched: Mutex<ChainWatchedUtil>,
329 reentered: AtomicUsize,
332 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
333 // only comparing a subset of fields (essentially just checking that the set of things we're
334 // watching is the same).
336 impl PartialEq for ChainWatchInterfaceUtil {
337 fn eq(&self, o: &Self) -> bool {
338 self.network == o.network &&
339 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
343 /// Register listener
344 impl ChainWatchInterface for ChainWatchInterfaceUtil {
345 fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
346 let mut watched = self.watched.lock().unwrap();
347 if watched.register_tx(txid, script_pub_key) {
348 self.reentered.fetch_add(1, Ordering::Relaxed);
352 fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
353 let mut watched = self.watched.lock().unwrap();
354 if watched.register_outpoint(outpoint, out_script) {
355 self.reentered.fetch_add(1, Ordering::Relaxed);
359 fn watch_all_txn(&self) {
360 let mut watched = self.watched.lock().unwrap();
361 if watched.watch_all() {
362 self.reentered.fetch_add(1, Ordering::Relaxed);
366 fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
367 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
368 return Err(ChainError::NotWatched);
370 Err(ChainError::NotSupported)
373 fn filter_block(&self, block: &Block) -> Vec<usize> {
374 let mut matched_index = Vec::new();
376 let watched = self.watched.lock().unwrap();
377 for (index, transaction) in block.txdata.iter().enumerate() {
378 if self.does_match_tx_unguarded(transaction, &watched) {
379 matched_index.push(index);
386 fn reentered(&self) -> usize {
387 self.reentered.load(Ordering::Relaxed)
391 impl ChainWatchInterfaceUtil {
392 /// Creates a new ChainWatchInterfaceUtil for the given network
393 pub fn new(network: Network) -> ChainWatchInterfaceUtil {
394 ChainWatchInterfaceUtil {
396 watched: Mutex::new(ChainWatchedUtil::new()),
397 reentered: AtomicUsize::new(1),
401 /// Checks if a given transaction matches the current filter.
402 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
403 let watched = self.watched.lock().unwrap();
404 self.does_match_tx_unguarded (tx, &watched)
407 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
408 watched.does_match_tx(tx)
414 use ln::functional_test_utils::{create_chanmon_cfgs, create_node_cfgs};
415 use super::{BlockNotifier, ChainListener};
419 fn register_listener_test() {
420 let chanmon_cfgs = create_chanmon_cfgs(1);
421 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
422 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
423 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
424 let listener = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
425 block_notifier.register_listener(listener);
426 let vec = block_notifier.listeners.lock().unwrap();
427 assert_eq!(vec.len(), 1);
428 let item = vec.first().clone().unwrap();
429 assert!(ptr::eq(&(**item), &(*listener)));
433 fn unregister_single_listener_test() {
434 let chanmon_cfgs = create_chanmon_cfgs(2);
435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
436 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
437 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
438 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
439 block_notifier.register_listener(listener1);
440 block_notifier.register_listener(listener2);
441 let vec = block_notifier.listeners.lock().unwrap();
442 assert_eq!(vec.len(), 2);
444 block_notifier.unregister_listener(listener1);
445 let vec = block_notifier.listeners.lock().unwrap();
446 assert_eq!(vec.len(), 1);
447 let item = vec.first().clone().unwrap();
448 assert!(ptr::eq(&(**item), &(*listener2)));
452 fn unregister_single_listener_ref_test() {
453 let chanmon_cfgs = create_chanmon_cfgs(2);
454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
455 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
456 block_notifier.register_listener(&node_cfgs[0].chan_monitor.simple_monitor as &ChainListener);
457 block_notifier.register_listener(&node_cfgs[1].chan_monitor.simple_monitor as &ChainListener);
458 let vec = block_notifier.listeners.lock().unwrap();
459 assert_eq!(vec.len(), 2);
461 block_notifier.unregister_listener(&node_cfgs[0].chan_monitor.simple_monitor);
462 let vec = block_notifier.listeners.lock().unwrap();
463 assert_eq!(vec.len(), 1);
464 let item = vec.first().clone().unwrap();
465 assert!(ptr::eq(&(**item), &(*&node_cfgs[1].chan_monitor.simple_monitor)));
469 fn unregister_multiple_of_the_same_listeners_test() {
470 let chanmon_cfgs = create_chanmon_cfgs(2);
471 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
472 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
473 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
474 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
475 block_notifier.register_listener(listener1);
476 block_notifier.register_listener(listener1);
477 block_notifier.register_listener(listener2);
478 let vec = block_notifier.listeners.lock().unwrap();
479 assert_eq!(vec.len(), 3);
481 block_notifier.unregister_listener(listener1);
482 let vec = block_notifier.listeners.lock().unwrap();
483 assert_eq!(vec.len(), 1);
484 let item = vec.first().clone().unwrap();
485 assert!(ptr::eq(&(**item), &(*listener2)));