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, header: &BlockHeader, txdata: &[(usize, &Transaction)]) -> 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. Transactions may be filtered and are given
83 /// paired with their position within the block.
84 fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32);
86 /// Notifies a listener that a block was disconnected.
87 /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
88 /// Height must be the one of the block which was disconnected (not new height of the best chain)
89 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
92 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
94 pub enum ConfirmationTarget {
95 /// We are happy with this transaction confirming slowly when feerate drops some.
97 /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
99 /// We'd like this transaction to confirm in the next few blocks.
103 /// A trait which should be implemented to provide feerate information on a number of time
106 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
107 /// called from inside the library in response to ChainListener events, P2P events, or timer
109 pub trait FeeEstimator: Sync + Send {
110 /// Gets estimated satoshis of fee required per 1000 Weight-Units.
112 /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
113 /// don't put us below 1 satoshi-per-byte).
115 /// This translates to:
116 /// * satoshis-per-byte * 250
117 /// * ceil(satoshis-per-kbyte / 4)
118 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
121 /// Minimum relay fee as required by bitcoin network mempool policy.
122 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
124 /// Utility for tracking registered txn/outpoints and checking for matches
125 #[cfg_attr(test, derive(PartialEq))]
126 pub struct ChainWatchedUtil {
129 // We are more conservative in matching during testing to ensure everything matches *exactly*,
130 // even though during normal runtime we take more optimized match approaches...
132 watched_txn: HashSet<(Txid, Script)>,
134 watched_txn: HashSet<Script>,
136 watched_outpoints: HashSet<(Txid, u32)>,
139 impl ChainWatchedUtil {
140 /// Constructs an empty (watches nothing) ChainWatchedUtil
141 pub fn new() -> Self {
144 watched_txn: HashSet::new(),
145 watched_outpoints: HashSet::new(),
149 /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
150 /// been watching for it.
151 pub fn register_tx(&mut self, txid: &Txid, script_pub_key: &Script) -> bool {
152 if self.watch_all { return false; }
155 self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
159 let _tx_unused = txid; // It's used in cfg(test), though
160 self.watched_txn.insert(script_pub_key.clone())
164 /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
165 /// we'd already been watching for it
166 pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
167 if self.watch_all { return false; }
168 self.watched_outpoints.insert(outpoint)
171 /// Sets us to match all transactions, returning true if this is a new setting and false if
172 /// we'd already been set to match everything.
173 pub fn watch_all(&mut self) -> bool {
174 if self.watch_all { return false; }
175 self.watch_all = true;
179 /// Checks if a given transaction matches the current filter.
180 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
184 for out in tx.output.iter() {
186 for &(ref txid, ref script) in self.watched_txn.iter() {
187 if *script == out.script_pubkey {
188 if tx.txid() == *txid {
194 for script in self.watched_txn.iter() {
195 if *script == out.script_pubkey {
200 for input in tx.input.iter() {
201 for outpoint in self.watched_outpoints.iter() {
202 let &(outpoint_hash, outpoint_index) = outpoint;
203 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
212 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
213 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
214 /// parameters with static lifetimes). Other times you can afford a reference, which is more
215 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
216 /// aliases prevents issues such as overly long function definitions.
218 /// (C-not exported) as we let clients handle any reference counting they need to do
219 pub type BlockNotifierArc = Arc<BlockNotifier<'static, Arc<ChainListener>>>;
221 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
222 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
223 /// lifetimes are more efficient but less flexible, and should be used by default unless static
224 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
225 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
226 /// appropriate type. Defining these type aliases for common usages prevents issues such as
227 /// overly long function definitions.
228 pub type BlockNotifierRef<'a> = BlockNotifier<'a, &'a ChainListener>;
230 /// Utility for notifying listeners when blocks are connected or disconnected.
232 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
233 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
234 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
235 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
236 pub struct BlockNotifier<'a, CL: Deref + 'a>
237 where CL::Target: ChainListener + 'a {
238 listeners: Mutex<Vec<CL>>,
239 phantom: PhantomData<&'a ()>,
242 impl<'a, CL: Deref + 'a> BlockNotifier<'a, CL>
243 where CL::Target: ChainListener + 'a {
244 /// Constructs a new BlockNotifier without any listeners.
245 pub fn new() -> BlockNotifier<'a, CL> {
247 listeners: Mutex::new(Vec::new()),
248 phantom: PhantomData,
252 /// Register the given listener to receive events.
253 pub fn register_listener(&self, listener: CL) {
254 let mut vec = self.listeners.lock().unwrap();
257 /// Unregister the given listener to no longer
260 /// If the same listener is registered multiple times, unregistering
261 /// will remove ALL occurrences of that listener. Comparison is done using
262 /// the pointer returned by the Deref trait implementation.
264 /// (C-not exported) because the equality check would always fail
265 pub fn unregister_listener(&self, listener: CL) {
266 let mut vec = self.listeners.lock().unwrap();
267 // item is a ref to an abstract thing that dereferences to a ChainListener,
268 // so dereference it twice to get the ChainListener itself
269 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
272 /// Notify listeners that a block was connected.
273 pub fn block_connected(&self, block: &Block, height: u32) {
274 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
275 let listeners = self.listeners.lock().unwrap();
276 for listener in listeners.iter() {
277 listener.block_connected(&block.header, &txdata, height);
281 /// Notify listeners that a block was disconnected.
282 pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
283 let listeners = self.listeners.lock().unwrap();
284 for listener in listeners.iter() {
285 listener.block_disconnected(&header, disconnected_height);
290 /// Utility to capture some common parts of ChainWatchInterface implementors.
292 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
293 pub struct ChainWatchInterfaceUtil {
295 watched: Mutex<ChainWatchedUtil>,
296 reentered: AtomicUsize,
299 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
300 // only comparing a subset of fields (essentially just checking that the set of things we're
301 // watching is the same).
303 impl PartialEq for ChainWatchInterfaceUtil {
304 fn eq(&self, o: &Self) -> bool {
305 self.network == o.network &&
306 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
310 /// Register listener
311 impl ChainWatchInterface for ChainWatchInterfaceUtil {
312 fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
313 let mut watched = self.watched.lock().unwrap();
314 if watched.register_tx(txid, script_pub_key) {
315 self.reentered.fetch_add(1, Ordering::Relaxed);
319 fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
320 let mut watched = self.watched.lock().unwrap();
321 if watched.register_outpoint(outpoint, out_script) {
322 self.reentered.fetch_add(1, Ordering::Relaxed);
326 fn watch_all_txn(&self) {
327 let mut watched = self.watched.lock().unwrap();
328 if watched.watch_all() {
329 self.reentered.fetch_add(1, Ordering::Relaxed);
333 fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
334 if genesis_hash != genesis_block(self.network).header.block_hash() {
335 return Err(ChainError::NotWatched);
337 Err(ChainError::NotSupported)
340 fn filter_block(&self, _header: &BlockHeader, txdata: &[(usize, &Transaction)]) -> Vec<usize> {
341 let mut matched_index = Vec::new();
342 let mut matched_txids = HashSet::new();
344 let watched = self.watched.lock().unwrap();
345 for (index, transaction) in txdata.iter().enumerate() {
346 // A tx matches the filter if it either matches the filter directly (via
347 // does_match_tx_unguarded) or if it is a descendant of another matched
348 // transaction within the same block, which we check for in the loop.
349 let mut matched = self.does_match_tx_unguarded(transaction.1, &watched);
350 for input in transaction.1.input.iter() {
351 if matched || matched_txids.contains(&input.previous_output.txid) {
357 matched_txids.insert(transaction.1.txid());
358 matched_index.push(index);
365 fn reentered(&self) -> usize {
366 self.reentered.load(Ordering::Relaxed)
370 impl ChainWatchInterfaceUtil {
371 /// Creates a new ChainWatchInterfaceUtil for the given network
372 pub fn new(network: Network) -> ChainWatchInterfaceUtil {
373 ChainWatchInterfaceUtil {
375 watched: Mutex::new(ChainWatchedUtil::new()),
376 reentered: AtomicUsize::new(1),
380 /// Checks if a given transaction matches the current filter.
381 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
382 let watched = self.watched.lock().unwrap();
383 self.does_match_tx_unguarded (tx, &watched)
386 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
387 watched.does_match_tx(tx)
393 use ln::functional_test_utils::{create_chanmon_cfgs, create_node_cfgs};
394 use super::{BlockNotifier, ChainListener};
398 fn register_listener_test() {
399 let chanmon_cfgs = create_chanmon_cfgs(1);
400 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
401 let block_notifier = BlockNotifier::new();
402 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
403 let listener = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
404 block_notifier.register_listener(listener);
405 let vec = block_notifier.listeners.lock().unwrap();
406 assert_eq!(vec.len(), 1);
407 let item = vec.first().clone().unwrap();
408 assert!(ptr::eq(&(**item), &(*listener)));
412 fn unregister_single_listener_test() {
413 let chanmon_cfgs = create_chanmon_cfgs(2);
414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
415 let block_notifier = BlockNotifier::new();
416 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
417 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
418 block_notifier.register_listener(listener1);
419 block_notifier.register_listener(listener2);
420 let vec = block_notifier.listeners.lock().unwrap();
421 assert_eq!(vec.len(), 2);
423 block_notifier.unregister_listener(listener1);
424 let vec = block_notifier.listeners.lock().unwrap();
425 assert_eq!(vec.len(), 1);
426 let item = vec.first().clone().unwrap();
427 assert!(ptr::eq(&(**item), &(*listener2)));
431 fn unregister_single_listener_ref_test() {
432 let chanmon_cfgs = create_chanmon_cfgs(2);
433 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
434 let block_notifier = BlockNotifier::new();
435 block_notifier.register_listener(&node_cfgs[0].chan_monitor.simple_monitor as &ChainListener);
436 block_notifier.register_listener(&node_cfgs[1].chan_monitor.simple_monitor as &ChainListener);
437 let vec = block_notifier.listeners.lock().unwrap();
438 assert_eq!(vec.len(), 2);
440 block_notifier.unregister_listener(&node_cfgs[0].chan_monitor.simple_monitor);
441 let vec = block_notifier.listeners.lock().unwrap();
442 assert_eq!(vec.len(), 1);
443 let item = vec.first().clone().unwrap();
444 assert!(ptr::eq(&(**item), &(*&node_cfgs[1].chan_monitor.simple_monitor)));
448 fn unregister_multiple_of_the_same_listeners_test() {
449 let chanmon_cfgs = create_chanmon_cfgs(2);
450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
451 let block_notifier = BlockNotifier::new();
452 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
453 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
454 block_notifier.register_listener(listener1);
455 block_notifier.register_listener(listener1);
456 block_notifier.register_listener(listener2);
457 let vec = block_notifier.listeners.lock().unwrap();
458 assert_eq!(vec.len(), 3);
460 block_notifier.unregister_listener(listener1);
461 let vec = block_notifier.listeners.lock().unwrap();
462 assert_eq!(vec.len(), 1);
463 let item = vec.first().clone().unwrap();
464 assert!(ptr::eq(&(**item), &(*listener2)));