Merge pull request #460 from lightning-signer/channel-value
[rust-lightning] / lightning / src / chain / chaininterface.rs
1 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
2 //! blockchain.
3 //!
4 //! Includes traits for monitoring and receiving notifications of new blocks and block
5 //! disconnections, transaction broadcasting, and feerate information requests.
6
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;
14
15 use util::logger::Logger;
16
17 use std::sync::{Mutex, MutexGuard, Arc};
18 use std::sync::atomic::{AtomicUsize, Ordering};
19 use std::collections::HashSet;
20 use std::ops::Deref;
21 use std::marker::PhantomData;
22
23 /// Used to give chain error details upstream
24 pub enum ChainError {
25         /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
26         NotSupported,
27         /// Chain isn't the one watched
28         NotWatched,
29         /// Tx doesn't exist or is unconfirmed
30         UnknownTx,
31 }
32
33 /// An interface to request notification of certain scripts as they appear the
34 /// chain.
35 ///
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
38 /// events).
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);
42
43         /// Provides an outpoint which must be watched for, providing any transactions which spend the
44         /// given outpoint.
45         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
46
47         /// Indicates that a listener needs to see all transactions.
48         fn watch_all_txn(&self);
49
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>;
55
56         /// Gets the list of transactions and transaction indices that the ChainWatchInterface is
57         /// watching for.
58         fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>);
59
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;
64 }
65
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);
70 }
71
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.
75         /// Note that if a new transaction/outpoint is watched during a block_connected call, the block
76         /// *must* be re-scanned with the new transaction/outpoints and block_connected should be
77         /// called again with the same header and (at least) the new transactions.
78         ///
79         /// Note that if non-new transaction/outpoints may be registered during a call, a second call
80         /// *must not* happen.
81         ///
82         /// This also means those counting confirmations using block_connected callbacks should watch
83         /// for duplicate headers and not count them towards confirmations!
84         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
85         /// Notifies a listener that a block was disconnected.
86         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
87         /// Height must be the one of the block which was disconnected (not new height of the best chain)
88         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
89 }
90
91 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
92 /// estimation.
93 pub enum ConfirmationTarget {
94         /// We are happy with this transaction confirming slowly when feerate drops some.
95         Background,
96         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
97         Normal,
98         /// We'd like this transaction to confirm in the next few blocks.
99         HighPriority,
100 }
101
102 /// A trait which should be implemented to provide feerate information on a number of time
103 /// horizons.
104 ///
105 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
106 /// called from inside the library in response to ChainListener events, P2P events, or timer
107 /// events).
108 pub trait FeeEstimator: Sync + Send {
109         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
110         ///
111         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
112         /// don't put us below 1 satoshi-per-byte).
113         ///
114         /// This translates to:
115         ///  * satoshis-per-byte * 250
116         ///  * ceil(satoshis-per-kbyte / 4)
117         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
118 }
119
120 /// Minimum relay fee as required by bitcoin network mempool policy.
121 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
122
123 /// Utility for tracking registered txn/outpoints and checking for matches
124 pub struct ChainWatchedUtil {
125         watch_all: bool,
126
127         // We are more conservative in matching during testing to ensure everything matches *exactly*,
128         // even though during normal runtime we take more optimized match approaches...
129         #[cfg(test)]
130         watched_txn: HashSet<(Sha256dHash, Script)>,
131         #[cfg(not(test))]
132         watched_txn: HashSet<Script>,
133
134         watched_outpoints: HashSet<(Sha256dHash, u32)>,
135 }
136
137 impl ChainWatchedUtil {
138         /// Constructs an empty (watches nothing) ChainWatchedUtil
139         pub fn new() -> Self {
140                 Self {
141                         watch_all: false,
142                         watched_txn: HashSet::new(),
143                         watched_outpoints: HashSet::new(),
144                 }
145         }
146
147         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
148         /// been watching for it.
149         pub fn register_tx(&mut self, txid: &Sha256dHash, script_pub_key: &Script) -> bool {
150                 if self.watch_all { return false; }
151                 #[cfg(test)]
152                 {
153                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
154                 }
155                 #[cfg(not(test))]
156                 {
157                         let _tx_unused = txid; // It's used in cfg(test), though
158                         self.watched_txn.insert(script_pub_key.clone())
159                 }
160         }
161
162         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
163         /// we'd already been watching for it
164         pub fn register_outpoint(&mut self, outpoint: (Sha256dHash, u32), _script_pub_key: &Script) -> bool {
165                 if self.watch_all { return false; }
166                 self.watched_outpoints.insert(outpoint)
167         }
168
169         /// Sets us to match all transactions, returning true if this is a new setting and false if
170         /// we'd already been set to match everything.
171         pub fn watch_all(&mut self) -> bool {
172                 if self.watch_all { return false; }
173                 self.watch_all = true;
174                 true
175         }
176
177         /// Checks if a given transaction matches the current filter.
178         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
179                 if self.watch_all {
180                         return true;
181                 }
182                 for out in tx.output.iter() {
183                         #[cfg(test)]
184                         for &(ref txid, ref script) in self.watched_txn.iter() {
185                                 if *script == out.script_pubkey {
186                                         if tx.txid() == *txid {
187                                                 return true;
188                                         }
189                                 }
190                         }
191                         #[cfg(not(test))]
192                         for script in self.watched_txn.iter() {
193                                 if *script == out.script_pubkey {
194                                         return true;
195                                 }
196                         }
197                 }
198                 for input in tx.input.iter() {
199                         for outpoint in self.watched_outpoints.iter() {
200                                 let &(outpoint_hash, outpoint_index) = outpoint;
201                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
202                                         return true;
203                                 }
204                         }
205                 }
206                 false
207         }
208 }
209
210 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
211 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
212 /// parameters with static lifetimes). Other times you can afford a reference, which is more
213 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
214 /// aliases prevents issues such as overly long function definitions.
215 pub type BlockNotifierArc = Arc<BlockNotifier<'static, Arc<ChainListener>>>;
216
217 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
218 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
219 /// lifetimes are more efficient but less flexible, and should be used by default unless static
220 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
221 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
222 /// appropriate type. Defining these type aliases for common usages prevents issues such as
223 /// overly long function definitions.
224 pub type BlockNotifierRef<'a> = BlockNotifier<'a, &'a ChainListener>;
225
226 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
227 /// data is registered.
228 ///
229 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
230 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
231 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
232 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
233 pub struct BlockNotifier<'a, CL: Deref<Target = ChainListener + 'a> + 'a> {
234         listeners: Mutex<Vec<CL>>,
235         chain_monitor: Arc<ChainWatchInterface>,
236         phantom: PhantomData<&'a ()>,
237 }
238
239 impl<'a, CL: Deref<Target = ChainListener + 'a> + 'a> BlockNotifier<'a, CL> {
240         /// Constructs a new BlockNotifier without any listeners.
241         pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> BlockNotifier<'a, CL> {
242                 BlockNotifier {
243                         listeners: Mutex::new(Vec::new()),
244                         chain_monitor,
245                         phantom: PhantomData,
246                 }
247         }
248
249         /// Register the given listener to receive events.
250         // TODO: unregister
251         pub fn register_listener(&self, listener: CL) {
252                 let mut vec = self.listeners.lock().unwrap();
253                 vec.push(listener);
254         }
255
256         /// Notify listeners that a block was connected given a full, unfiltered block.
257         ///
258         /// Handles re-scanning the block and calling block_connected again if listeners register new
259         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
260         pub fn block_connected<'b>(&self, block: &'b Block, height: u32) {
261                 let mut reentered = true;
262                 while reentered {
263                         let (matched, matched_index) = self.chain_monitor.filter_block(block);
264                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
265                 }
266         }
267
268         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
269         /// block which matched the filter (probably using does_match_tx).
270         ///
271         /// Returns true if notified listeners registered additional watch data (implying that the
272         /// block must be re-scanned and this function called again prior to further block_connected
273         /// calls, see ChainListener::block_connected for more info).
274         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
275                 let last_seen = self.chain_monitor.reentered();
276
277                 let listeners = self.listeners.lock().unwrap();
278                 for listener in listeners.iter() {
279                         listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
280                 }
281                 return last_seen != self.chain_monitor.reentered();
282         }
283
284
285         /// Notify listeners that a block was disconnected.
286         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
287                 let listeners = self.listeners.lock().unwrap();
288                 for listener in listeners.iter() {
289                         listener.block_disconnected(&header, disconnected_height);
290                 }
291         }
292
293 }
294
295 /// Utility to capture some common parts of ChainWatchInterface implementors.
296 ///
297 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
298 pub struct ChainWatchInterfaceUtil {
299         network: Network,
300         watched: Mutex<ChainWatchedUtil>,
301         reentered: AtomicUsize,
302         logger: Arc<Logger>,
303 }
304
305 /// Register listener
306 impl ChainWatchInterface for ChainWatchInterfaceUtil {
307         fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script) {
308                 let mut watched = self.watched.lock().unwrap();
309                 if watched.register_tx(txid, script_pub_key) {
310                         self.reentered.fetch_add(1, Ordering::Relaxed);
311                 }
312         }
313
314         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script) {
315                 let mut watched = self.watched.lock().unwrap();
316                 if watched.register_outpoint(outpoint, out_script) {
317                         self.reentered.fetch_add(1, Ordering::Relaxed);
318                 }
319         }
320
321         fn watch_all_txn(&self) {
322                 let mut watched = self.watched.lock().unwrap();
323                 if watched.watch_all() {
324                         self.reentered.fetch_add(1, Ordering::Relaxed);
325                 }
326         }
327
328         fn get_chain_utxo(&self, genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
329                 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
330                         return Err(ChainError::NotWatched);
331                 }
332                 Err(ChainError::NotSupported)
333         }
334
335         fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
336                 let mut matched = Vec::new();
337                 let mut matched_index = Vec::new();
338                 {
339                         let watched = self.watched.lock().unwrap();
340                         for (index, transaction) in block.txdata.iter().enumerate() {
341                                 if self.does_match_tx_unguarded(transaction, &watched) {
342                                         matched.push(transaction);
343                                         matched_index.push(index as u32);
344                                 }
345                         }
346                 }
347                 (matched, matched_index)
348         }
349
350         fn reentered(&self) -> usize {
351                 self.reentered.load(Ordering::Relaxed)
352         }
353 }
354
355 impl ChainWatchInterfaceUtil {
356         /// Creates a new ChainWatchInterfaceUtil for the given network
357         pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
358                 ChainWatchInterfaceUtil {
359                         network: network,
360                         watched: Mutex::new(ChainWatchedUtil::new()),
361                         reentered: AtomicUsize::new(1),
362                         logger: logger,
363                 }
364         }
365
366
367         /// Checks if a given transaction matches the current filter.
368         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
369                 let watched = self.watched.lock().unwrap();
370                 self.does_match_tx_unguarded (tx, &watched)
371         }
372
373         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
374                 watched.does_match_tx(tx)
375         }
376 }