1 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
4 //! Includes traits for monitoring and receiving notifications of new blocks and block
5 //! disconnections, transaction broadcasting, and feerate information requests.
7 use bitcoin::blockdata::block::{Block, BlockHeader};
8 use bitcoin::blockdata::transaction::Transaction;
9 use bitcoin::blockdata::script::Script;
10 use bitcoin::blockdata::constants::genesis_block;
11 use bitcoin::util::hash::BitcoinHash;
12 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
13 use bitcoin::network::constants::Network;
15 use util::logger::Logger;
17 use std::sync::{Mutex, MutexGuard, Arc};
18 use std::sync::atomic::{AtomicUsize, Ordering};
19 use std::collections::HashSet;
21 use std::marker::PhantomData;
23 /// Used to give chain error details upstream
25 /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
27 /// Chain isn't the one watched
29 /// Tx doesn't exist or is unconfirmed
33 /// An interface to request notification of certain scripts as they appear the
36 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
37 /// called from inside the library in response to ChainListener events, P2P events, or timer
39 pub trait ChainWatchInterface: Sync + Send {
40 /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
41 fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script);
43 /// Provides an outpoint which must be watched for, providing any transactions which spend the
45 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
47 /// Indicates that a listener needs to see all transactions.
48 fn watch_all_txn(&self);
50 /// Gets the script and value in satoshis for a given unspent transaction output given a
51 /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
52 /// bytes are the block height, the next 3 the transaction index within the block, and the
53 /// final two the output within the transaction.
54 fn get_chain_utxo(&self, genesis_hash: Sha256dHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
56 /// Gets the list of transactions and transaction indices that the ChainWatchInterface is
58 fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>);
60 /// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
61 /// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
62 /// determine whether they need to re-filter a given block.
63 fn reentered(&self) -> usize;
66 /// An interface to send a transaction to the Bitcoin network.
67 pub trait BroadcasterInterface: Sync + Send {
68 /// Sends a transaction out to (hopefully) be mined.
69 fn broadcast_transaction(&self, tx: &Transaction);
72 /// A trait indicating a desire to listen for events from the chain
73 pub trait ChainListener: Sync + Send {
74 /// Notifies a listener that a block was connected.
76 /// The txn_matched array should be set to references to transactions which matched the
77 /// relevant installed watch outpoints/txn, or the full set of transactions in the block.
79 /// Note that if txn_matched includes only matched transactions, and a new
80 /// transaction/outpoint is watched during a block_connected call, the block *must* be
81 /// re-scanned with the new transaction/outpoints and block_connected should be called
82 /// again with the same header and (at least) the new transactions.
84 /// Note that if non-new transaction/outpoints are be registered during a call, a second call
85 /// *must not* happen.
87 /// This also means those counting confirmations using block_connected callbacks should watch
88 /// for duplicate headers and not count them towards confirmations!
89 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
90 /// Notifies a listener that a block was disconnected.
91 /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
92 /// Height must be the one of the block which was disconnected (not new height of the best chain)
93 fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
96 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
98 pub enum ConfirmationTarget {
99 /// We are happy with this transaction confirming slowly when feerate drops some.
101 /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
103 /// We'd like this transaction to confirm in the next few blocks.
107 /// A trait which should be implemented to provide feerate information on a number of time
110 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
111 /// called from inside the library in response to ChainListener events, P2P events, or timer
113 pub trait FeeEstimator: Sync + Send {
114 /// Gets estimated satoshis of fee required per 1000 Weight-Units.
116 /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
117 /// don't put us below 1 satoshi-per-byte).
119 /// This translates to:
120 /// * satoshis-per-byte * 250
121 /// * ceil(satoshis-per-kbyte / 4)
122 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
125 /// Minimum relay fee as required by bitcoin network mempool policy.
126 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
128 /// Utility for tracking registered txn/outpoints and checking for matches
129 pub struct ChainWatchedUtil {
132 // We are more conservative in matching during testing to ensure everything matches *exactly*,
133 // even though during normal runtime we take more optimized match approaches...
135 watched_txn: HashSet<(Sha256dHash, Script)>,
137 watched_txn: HashSet<Script>,
139 watched_outpoints: HashSet<(Sha256dHash, u32)>,
142 impl ChainWatchedUtil {
143 /// Constructs an empty (watches nothing) ChainWatchedUtil
144 pub fn new() -> Self {
147 watched_txn: HashSet::new(),
148 watched_outpoints: HashSet::new(),
152 /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
153 /// been watching for it.
154 pub fn register_tx(&mut self, txid: &Sha256dHash, script_pub_key: &Script) -> bool {
155 if self.watch_all { return false; }
158 self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
162 let _tx_unused = txid; // It's used in cfg(test), though
163 self.watched_txn.insert(script_pub_key.clone())
167 /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
168 /// we'd already been watching for it
169 pub fn register_outpoint(&mut self, outpoint: (Sha256dHash, u32), _script_pub_key: &Script) -> bool {
170 if self.watch_all { return false; }
171 self.watched_outpoints.insert(outpoint)
174 /// Sets us to match all transactions, returning true if this is a new setting and false if
175 /// we'd already been set to match everything.
176 pub fn watch_all(&mut self) -> bool {
177 if self.watch_all { return false; }
178 self.watch_all = true;
182 /// Checks if a given transaction matches the current filter.
183 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
187 for out in tx.output.iter() {
189 for &(ref txid, ref script) in self.watched_txn.iter() {
190 if *script == out.script_pubkey {
191 if tx.txid() == *txid {
197 for script in self.watched_txn.iter() {
198 if *script == out.script_pubkey {
203 for input in tx.input.iter() {
204 for outpoint in self.watched_outpoints.iter() {
205 let &(outpoint_hash, outpoint_index) = outpoint;
206 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
215 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
216 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
217 /// parameters with static lifetimes). Other times you can afford a reference, which is more
218 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
219 /// aliases prevents issues such as overly long function definitions.
220 pub type BlockNotifierArc = Arc<BlockNotifier<'static, Arc<ChainListener>>>;
222 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
223 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
224 /// lifetimes are more efficient but less flexible, and should be used by default unless static
225 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
226 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
227 /// appropriate type. Defining these type aliases for common usages prevents issues such as
228 /// overly long function definitions.
229 pub type BlockNotifierRef<'a> = BlockNotifier<'a, &'a ChainListener>;
231 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
232 /// data is registered.
234 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
235 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
236 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
237 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
238 pub struct BlockNotifier<'a, CL: Deref<Target = ChainListener + 'a> + 'a> {
239 listeners: Mutex<Vec<CL>>,
240 chain_monitor: Arc<ChainWatchInterface>,
241 phantom: PhantomData<&'a ()>,
244 impl<'a, CL: Deref<Target = ChainListener + 'a> + 'a> BlockNotifier<'a, CL> {
245 /// Constructs a new BlockNotifier without any listeners.
246 pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> BlockNotifier<'a, CL> {
248 listeners: Mutex::new(Vec::new()),
250 phantom: PhantomData,
254 /// Register the given listener to receive events.
256 pub fn register_listener(&self, listener: CL) {
257 let mut vec = self.listeners.lock().unwrap();
261 /// Notify listeners that a block was connected given a full, unfiltered block.
263 /// Handles re-scanning the block and calling block_connected again if listeners register new
264 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
265 pub fn block_connected<'b>(&self, block: &'b Block, height: u32) {
266 let mut reentered = true;
268 let (matched, matched_index) = self.chain_monitor.filter_block(block);
269 reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
273 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
274 /// block which matched the filter (probably using does_match_tx).
276 /// Returns true if notified listeners registered additional watch data (implying that the
277 /// block must be re-scanned and this function called again prior to further block_connected
278 /// calls, see ChainListener::block_connected for more info).
279 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
280 let last_seen = self.chain_monitor.reentered();
282 let listeners = self.listeners.lock().unwrap();
283 for listener in listeners.iter() {
284 listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
286 return last_seen != self.chain_monitor.reentered();
289 /// Notify listeners that a block was disconnected.
290 pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
291 let listeners = self.listeners.lock().unwrap();
292 for listener in listeners.iter() {
293 listener.block_disconnected(&header, disconnected_height);
298 /// Utility to capture some common parts of ChainWatchInterface implementors.
300 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
301 pub struct ChainWatchInterfaceUtil {
303 watched: Mutex<ChainWatchedUtil>,
304 reentered: AtomicUsize,
308 /// Register listener
309 impl ChainWatchInterface for ChainWatchInterfaceUtil {
310 fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script) {
311 let mut watched = self.watched.lock().unwrap();
312 if watched.register_tx(txid, script_pub_key) {
313 self.reentered.fetch_add(1, Ordering::Relaxed);
317 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script) {
318 let mut watched = self.watched.lock().unwrap();
319 if watched.register_outpoint(outpoint, out_script) {
320 self.reentered.fetch_add(1, Ordering::Relaxed);
324 fn watch_all_txn(&self) {
325 let mut watched = self.watched.lock().unwrap();
326 if watched.watch_all() {
327 self.reentered.fetch_add(1, Ordering::Relaxed);
331 fn get_chain_utxo(&self, genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
332 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
333 return Err(ChainError::NotWatched);
335 Err(ChainError::NotSupported)
338 fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
339 let mut matched = Vec::new();
340 let mut matched_index = Vec::new();
342 let watched = self.watched.lock().unwrap();
343 for (index, transaction) in block.txdata.iter().enumerate() {
344 if self.does_match_tx_unguarded(transaction, &watched) {
345 matched.push(transaction);
346 matched_index.push(index as u32);
350 (matched, matched_index)
353 fn reentered(&self) -> usize {
354 self.reentered.load(Ordering::Relaxed)
358 impl ChainWatchInterfaceUtil {
359 /// Creates a new ChainWatchInterfaceUtil for the given network
360 pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
361 ChainWatchInterfaceUtil {
363 watched: Mutex::new(ChainWatchedUtil::new()),
364 reentered: AtomicUsize::new(1),
369 /// Checks if a given transaction matches the current filter.
370 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
371 let watched = self.watched.lock().unwrap();
372 self.does_match_tx_unguarded (tx, &watched)
375 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
376 watched.does_match_tx(tx)