b7b6f0422bd4866ba583ef95677651bac6aa5e01
[rust-lightning] / lightning / src / util / test_utils.rs
1 use chain::chaininterface;
2 use chain::chaininterface::{ConfirmationTarget, ChainError, ChainWatchInterface};
3 use chain::transaction::OutPoint;
4 use chain::keysinterface;
5 use ln::channelmonitor;
6 use ln::features::InitFeatures;
7 use ln::msgs;
8 use ln::msgs::LightningError;
9 use ln::channelmonitor::HTLCUpdate;
10 use util::enforcing_trait_impls::EnforcingChannelKeys;
11 use util::events;
12 use util::logger::{Logger, Level, Record};
13 use util::ser::{Readable, Writer, Writeable};
14
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::script::{Builder, Script};
17 use bitcoin::blockdata::block::Block;
18 use bitcoin::blockdata::opcodes;
19 use bitcoin::network::constants::Network;
20 use bitcoin::hash_types::{Txid, BlockHash};
21
22 use bitcoin::secp256k1::{SecretKey, PublicKey};
23
24 use std::time::{SystemTime, UNIX_EPOCH};
25 use std::sync::Mutex;
26 use std::mem;
27 use std::collections::HashMap;
28
29 pub struct TestVecWriter(pub Vec<u8>);
30 impl Writer for TestVecWriter {
31         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
32                 self.0.extend_from_slice(buf);
33                 Ok(())
34         }
35         fn size_hint(&mut self, size: usize) {
36                 self.0.reserve_exact(size);
37         }
38 }
39
40 pub struct TestFeeEstimator {
41         pub sat_per_kw: u64,
42 }
43 impl chaininterface::FeeEstimator for TestFeeEstimator {
44         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u64 {
45                 self.sat_per_kw
46         }
47 }
48
49 pub struct TestChannelMonitor<'a> {
50         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
51         pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
52         pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a ChainWatchInterface>,
53         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
54         // If this is set to Some(), after the next return, we'll always return this until update_ret
55         // is changed:
56         pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
57 }
58 impl<'a> TestChannelMonitor<'a> {
59         pub fn new(chain_monitor: &'a chaininterface::ChainWatchInterface, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator) -> Self {
60                 Self {
61                         added_monitors: Mutex::new(Vec::new()),
62                         latest_monitor_update_id: Mutex::new(HashMap::new()),
63                         simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, fee_estimator),
64                         update_ret: Mutex::new(Ok(())),
65                         next_update_ret: Mutex::new(None),
66                 }
67         }
68 }
69 impl<'a> channelmonitor::ManyChannelMonitor for TestChannelMonitor<'a> {
70         type Keys = EnforcingChannelKeys;
71
72         fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
73                 // At every point where we get a monitor update, we should be able to send a useful monitor
74                 // to a watchtower and disk...
75                 let mut w = TestVecWriter(Vec::new());
76                 monitor.write_for_disk(&mut w).unwrap();
77                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
78                         &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
79                 assert!(new_monitor == monitor);
80                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
81                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
82                 assert!(self.simple_monitor.add_monitor(funding_txo, new_monitor).is_ok());
83
84                 let ret = self.update_ret.lock().unwrap().clone();
85                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
86                         *self.update_ret.lock().unwrap() = next_ret;
87                 }
88                 ret
89         }
90
91         fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
92                 // Every monitor update should survive roundtrip
93                 let mut w = TestVecWriter(Vec::new());
94                 update.write(&mut w).unwrap();
95                 assert!(channelmonitor::ChannelMonitorUpdate::read(
96                                 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
97
98                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id));
99                 assert!(self.simple_monitor.update_monitor(funding_txo, update).is_ok());
100                 // At every point where we get a monitor update, we should be able to send a useful monitor
101                 // to a watchtower and disk...
102                 let monitors = self.simple_monitor.monitors.lock().unwrap();
103                 let monitor = monitors.get(&funding_txo).unwrap();
104                 w.0.clear();
105                 monitor.write_for_disk(&mut w).unwrap();
106                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
107                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
108                 assert!(new_monitor == *monitor);
109                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
110
111                 let ret = self.update_ret.lock().unwrap().clone();
112                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
113                         *self.update_ret.lock().unwrap() = next_ret;
114                 }
115                 ret
116         }
117
118         fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
119                 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
120         }
121 }
122
123 pub struct TestBroadcaster {
124         pub txn_broadcasted: Mutex<Vec<Transaction>>,
125 }
126 impl chaininterface::BroadcasterInterface for TestBroadcaster {
127         fn broadcast_transaction(&self, tx: &Transaction) {
128                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
129         }
130 }
131
132 pub struct TestChannelMessageHandler {
133         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
134 }
135
136 impl TestChannelMessageHandler {
137         pub fn new() -> Self {
138                 TestChannelMessageHandler {
139                         pending_events: Mutex::new(Vec::new()),
140                 }
141         }
142 }
143
144 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
145         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
146         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
147         fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
148         fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
149         fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
150         fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
151         fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
152         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
153         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
154         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
155         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
156         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
157         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
158         fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
159         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
160         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
161         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
162         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
163         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
164 }
165
166 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
167         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
168                 let mut pending_events = self.pending_events.lock().unwrap();
169                 let mut ret = Vec::new();
170                 mem::swap(&mut ret, &mut *pending_events);
171                 ret
172         }
173 }
174
175 pub struct TestRoutingMessageHandler {
176         request_full_sync: bool,
177 }
178
179 impl TestRoutingMessageHandler {
180         pub fn new() -> Self {
181                 TestRoutingMessageHandler {
182                         request_full_sync: false,
183                 }
184         }
185
186         pub fn set_request_full_sync(mut self) -> Self {
187                 self.request_full_sync = true;
188                 self
189         }
190 }
191 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
192         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
193                 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
194         }
195         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
196                 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
197         }
198         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
199                 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
200         }
201         fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
202         fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
203                 Vec::new()
204         }
205         fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
206                 Vec::new()
207         }
208         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
209                 self.request_full_sync
210         }
211 }
212
213 pub struct TestLogger {
214         level: Level,
215         id: String,
216         pub lines: Mutex<HashMap<(String, String), usize>>,
217 }
218
219 impl TestLogger {
220         pub fn new() -> TestLogger {
221                 Self::with_id("".to_owned())
222         }
223         pub fn with_id(id: String) -> TestLogger {
224                 TestLogger {
225                         level: Level::Trace,
226                         id,
227                         lines: Mutex::new(HashMap::new())
228                 }
229         }
230         pub fn enable(&mut self, level: Level) {
231                 self.level = level;
232         }
233         pub fn assert_log(&self, module: String, line: String, count: usize) {
234                 let log_entries = self.lines.lock().unwrap();
235                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
236         }
237 }
238
239 impl Logger for TestLogger {
240         fn log(&self, record: &Record) {
241                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
242                 if self.level >= record.level {
243                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
244                 }
245         }
246 }
247
248 pub struct TestKeysInterface {
249         backing: keysinterface::KeysManager,
250         pub override_session_priv: Mutex<Option<SecretKey>>,
251         pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
252 }
253
254 impl keysinterface::KeysInterface for TestKeysInterface {
255         type ChanKeySigner = EnforcingChannelKeys;
256
257         fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
258         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
259         fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
260         fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
261                 EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
262         }
263
264         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
265                 match *self.override_session_priv.lock().unwrap() {
266                         Some(key) => (key.clone(), [0; 32]),
267                         None => self.backing.get_onion_rand()
268                 }
269         }
270
271         fn get_channel_id(&self) -> [u8; 32] {
272                 match *self.override_channel_id_priv.lock().unwrap() {
273                         Some(key) => key.clone(),
274                         None => self.backing.get_channel_id()
275                 }
276         }
277 }
278
279 impl TestKeysInterface {
280         pub fn new(seed: &[u8; 32], network: Network) -> Self {
281                 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
282                 Self {
283                         backing: keysinterface::KeysManager::new(seed, network, now.as_secs(), now.subsec_nanos()),
284                         override_session_priv: Mutex::new(None),
285                         override_channel_id_priv: Mutex::new(None),
286                 }
287         }
288 }
289
290 pub struct TestChainWatcher {
291         pub utxo_ret: Mutex<Result<(Script, u64), ChainError>>,
292 }
293
294 impl TestChainWatcher {
295         pub fn new() -> Self {
296                 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
297                 Self { utxo_ret: Mutex::new(Ok((script, u64::max_value()))) }
298         }
299 }
300
301 impl ChainWatchInterface for TestChainWatcher {
302         fn install_watch_tx(&self, _txid: &Txid, _script_pub_key: &Script) { }
303         fn install_watch_outpoint(&self, _outpoint: (Txid, u32), _out_script: &Script) { }
304         fn watch_all_txn(&self) { }
305         fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
306                 (Vec::new(), Vec::new())
307         }
308         fn reentered(&self) -> usize { 0 }
309
310         fn get_chain_utxo(&self, _genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
311                 self.utxo_ret.lock().unwrap().clone()
312         }
313 }