f65ae3611f623af549da1f75a556463363f8e0ae
[rust-lightning] / lightning / src / chain / chaininterface.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
11 //! blockchain.
12 //!
13 //! Includes traits for monitoring and receiving notifications of new blocks and block
14 //! disconnections, transaction broadcasting, and feerate information requests.
15
16 use bitcoin::blockdata::block::BlockHeader;
17 use bitcoin::blockdata::transaction::Transaction;
18 use bitcoin::blockdata::script::Script;
19 use bitcoin::hash_types::Txid;
20
21 use std::collections::HashSet;
22
23 /// An interface to send a transaction to the Bitcoin network.
24 pub trait BroadcasterInterface: Sync + Send {
25         /// Sends a transaction out to (hopefully) be mined.
26         fn broadcast_transaction(&self, tx: &Transaction);
27 }
28
29 /// A trait indicating a desire to listen for events from the chain
30 pub trait ChainListener: Sync + Send {
31         /// Notifies a listener that a block was connected. Transactions may be filtered and are given
32         /// paired with their position within the block.
33         fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32);
34
35         /// Notifies a listener that a block was disconnected.
36         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
37         /// Height must be the one of the block which was disconnected (not new height of the best chain)
38         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
39 }
40
41 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
42 /// estimation.
43 pub enum ConfirmationTarget {
44         /// We are happy with this transaction confirming slowly when feerate drops some.
45         Background,
46         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
47         Normal,
48         /// We'd like this transaction to confirm in the next few blocks.
49         HighPriority,
50 }
51
52 /// A trait which should be implemented to provide feerate information on a number of time
53 /// horizons.
54 ///
55 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
56 /// called from inside the library in response to ChainListener events, P2P events, or timer
57 /// events).
58 pub trait FeeEstimator: Sync + Send {
59         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
60         ///
61         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
62         /// don't put us below 1 satoshi-per-byte).
63         ///
64         /// This translates to:
65         ///  * satoshis-per-byte * 250
66         ///  * ceil(satoshis-per-kbyte / 4)
67         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
68 }
69
70 /// Minimum relay fee as required by bitcoin network mempool policy.
71 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
72
73 /// Utility for tracking registered txn/outpoints and checking for matches
74 #[cfg_attr(test, derive(PartialEq))]
75 pub struct ChainWatchedUtil {
76         watch_all: bool,
77
78         // We are more conservative in matching during testing to ensure everything matches *exactly*,
79         // even though during normal runtime we take more optimized match approaches...
80         #[cfg(test)]
81         watched_txn: HashSet<(Txid, Script)>,
82         #[cfg(not(test))]
83         watched_txn: HashSet<Script>,
84
85         watched_outpoints: HashSet<(Txid, u32)>,
86 }
87
88 impl ChainWatchedUtil {
89         /// Constructs an empty (watches nothing) ChainWatchedUtil
90         pub fn new() -> Self {
91                 Self {
92                         watch_all: false,
93                         watched_txn: HashSet::new(),
94                         watched_outpoints: HashSet::new(),
95                 }
96         }
97
98         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
99         /// been watching for it.
100         pub fn register_tx(&mut self, txid: &Txid, script_pub_key: &Script) -> bool {
101                 if self.watch_all { return false; }
102                 #[cfg(test)]
103                 {
104                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
105                 }
106                 #[cfg(not(test))]
107                 {
108                         let _tx_unused = txid; // It's used in cfg(test), though
109                         self.watched_txn.insert(script_pub_key.clone())
110                 }
111         }
112
113         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
114         /// we'd already been watching for it
115         pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
116                 if self.watch_all { return false; }
117                 self.watched_outpoints.insert(outpoint)
118         }
119
120         /// Sets us to match all transactions, returning true if this is a new setting and false if
121         /// we'd already been set to match everything.
122         pub fn watch_all(&mut self) -> bool {
123                 if self.watch_all { return false; }
124                 self.watch_all = true;
125                 true
126         }
127
128         /// Checks if a given transaction matches the current filter.
129         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
130                 if self.watch_all {
131                         return true;
132                 }
133                 for out in tx.output.iter() {
134                         #[cfg(test)]
135                         for &(ref txid, ref script) in self.watched_txn.iter() {
136                                 if *script == out.script_pubkey {
137                                         if tx.txid() == *txid {
138                                                 return true;
139                                         }
140                                 }
141                         }
142                         #[cfg(not(test))]
143                         for script in self.watched_txn.iter() {
144                                 if *script == out.script_pubkey {
145                                         return true;
146                                 }
147                         }
148                 }
149                 for input in tx.input.iter() {
150                         for outpoint in self.watched_outpoints.iter() {
151                                 let &(outpoint_hash, outpoint_index) = outpoint;
152                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
153                                         return true;
154                                 }
155                         }
156                 }
157                 false
158         }
159 }