Merge pull request #644 from joemphilips/improve_error_message
[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::{ChannelFeatures, InitFeatures};
7 use ln::msgs;
8 use ln::channelmonitor::HTLCUpdate;
9 use util::enforcing_trait_impls::EnforcingChannelKeys;
10 use util::events;
11 use util::logger::{Logger, Level, Record};
12 use util::ser::{Readable, Writer, Writeable};
13
14 use bitcoin::BitcoinHash;
15 use bitcoin::blockdata::constants::genesis_block;
16 use bitcoin::blockdata::transaction::Transaction;
17 use bitcoin::blockdata::script::{Builder, Script};
18 use bitcoin::blockdata::block::Block;
19 use bitcoin::blockdata::opcodes;
20 use bitcoin::network::constants::Network;
21 use bitcoin::hash_types::{Txid, BlockHash};
22
23 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
24
25 use regex;
26
27 use std::time::Duration;
28 use std::sync::Mutex;
29 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
30 use std::{cmp, mem};
31 use std::collections::HashMap;
32
33 pub struct TestVecWriter(pub Vec<u8>);
34 impl Writer for TestVecWriter {
35         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
36                 self.0.extend_from_slice(buf);
37                 Ok(())
38         }
39         fn size_hint(&mut self, size: usize) {
40                 self.0.reserve_exact(size);
41         }
42 }
43
44 pub struct TestFeeEstimator {
45         pub sat_per_kw: u32,
46 }
47 impl chaininterface::FeeEstimator for TestFeeEstimator {
48         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
49                 self.sat_per_kw
50         }
51 }
52
53 pub struct TestChannelMonitor<'a> {
54         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
55         pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
56         pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a ChainWatchInterface>,
57         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
58         // If this is set to Some(), after the next return, we'll always return this until update_ret
59         // is changed:
60         pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
61 }
62 impl<'a> TestChannelMonitor<'a> {
63         pub fn new(chain_monitor: &'a chaininterface::ChainWatchInterface, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator) -> Self {
64                 Self {
65                         added_monitors: Mutex::new(Vec::new()),
66                         latest_monitor_update_id: Mutex::new(HashMap::new()),
67                         simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, fee_estimator),
68                         update_ret: Mutex::new(Ok(())),
69                         next_update_ret: Mutex::new(None),
70                 }
71         }
72 }
73 impl<'a> channelmonitor::ManyChannelMonitor for TestChannelMonitor<'a> {
74         type Keys = EnforcingChannelKeys;
75
76         fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
77                 // At every point where we get a monitor update, we should be able to send a useful monitor
78                 // to a watchtower and disk...
79                 let mut w = TestVecWriter(Vec::new());
80                 monitor.write_for_disk(&mut w).unwrap();
81                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
82                         &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
83                 assert!(new_monitor == monitor);
84                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
85                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
86                 assert!(self.simple_monitor.add_monitor(funding_txo, new_monitor).is_ok());
87
88                 let ret = self.update_ret.lock().unwrap().clone();
89                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
90                         *self.update_ret.lock().unwrap() = next_ret;
91                 }
92                 ret
93         }
94
95         fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
96                 // Every monitor update should survive roundtrip
97                 let mut w = TestVecWriter(Vec::new());
98                 update.write(&mut w).unwrap();
99                 assert!(channelmonitor::ChannelMonitorUpdate::read(
100                                 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
101
102                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id));
103                 assert!(self.simple_monitor.update_monitor(funding_txo, update).is_ok());
104                 // At every point where we get a monitor update, we should be able to send a useful monitor
105                 // to a watchtower and disk...
106                 let monitors = self.simple_monitor.monitors.lock().unwrap();
107                 let monitor = monitors.get(&funding_txo).unwrap();
108                 w.0.clear();
109                 monitor.write_for_disk(&mut w).unwrap();
110                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
111                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
112                 assert!(new_monitor == *monitor);
113                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
114
115                 let ret = self.update_ret.lock().unwrap().clone();
116                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
117                         *self.update_ret.lock().unwrap() = next_ret;
118                 }
119                 ret
120         }
121
122         fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
123                 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
124         }
125 }
126
127 pub struct TestBroadcaster {
128         pub txn_broadcasted: Mutex<Vec<Transaction>>,
129 }
130 impl chaininterface::BroadcasterInterface for TestBroadcaster {
131         fn broadcast_transaction(&self, tx: &Transaction) {
132                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
133         }
134 }
135
136 pub struct TestChannelMessageHandler {
137         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
138 }
139
140 impl TestChannelMessageHandler {
141         pub fn new() -> Self {
142                 TestChannelMessageHandler {
143                         pending_events: Mutex::new(Vec::new()),
144                 }
145         }
146 }
147
148 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
149         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
150         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
151         fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
152         fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
153         fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
154         fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
155         fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
156         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
157         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
158         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
159         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
160         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
161         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
162         fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
163         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
164         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
165         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
166         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
167         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
168 }
169
170 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
171         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
172                 let mut pending_events = self.pending_events.lock().unwrap();
173                 let mut ret = Vec::new();
174                 mem::swap(&mut ret, &mut *pending_events);
175                 ret
176         }
177 }
178
179 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
180         use bitcoin::secp256k1::ffi::Signature as FFISignature;
181         let secp_ctx = Secp256k1::new();
182         let network = Network::Testnet;
183         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
184         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
185         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
186         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
187         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
188                 features: ChannelFeatures::known(),
189                 chain_hash: genesis_block(network).header.bitcoin_hash(),
190                 short_channel_id: short_chan_id,
191                 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
192                 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
193                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
194                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
195                 excess_data: Vec::new(),
196         };
197
198         msgs::ChannelAnnouncement {
199                 node_signature_1: Signature::from(FFISignature::new()),
200                 node_signature_2: Signature::from(FFISignature::new()),
201                 bitcoin_signature_1: Signature::from(FFISignature::new()),
202                 bitcoin_signature_2: Signature::from(FFISignature::new()),
203                 contents: unsigned_ann,
204         }
205 }
206
207 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
208         use bitcoin::secp256k1::ffi::Signature as FFISignature;
209         let network = Network::Testnet;
210         msgs::ChannelUpdate {
211                 signature: Signature::from(FFISignature::new()),
212                 contents: msgs::UnsignedChannelUpdate {
213                         chain_hash: genesis_block(network).header.bitcoin_hash(),
214                         short_channel_id: short_chan_id,
215                         timestamp: 0,
216                         flags: 0,
217                         cltv_expiry_delta: 0,
218                         htlc_minimum_msat: 0,
219                         fee_base_msat: 0,
220                         fee_proportional_millionths: 0,
221                         excess_data: vec![],
222                 }
223         }
224 }
225
226 pub struct TestRoutingMessageHandler {
227         pub chan_upds_recvd: AtomicUsize,
228         pub chan_anns_recvd: AtomicUsize,
229         pub chan_anns_sent: AtomicUsize,
230         pub request_full_sync: AtomicBool,
231 }
232
233 impl TestRoutingMessageHandler {
234         pub fn new() -> Self {
235                 TestRoutingMessageHandler {
236                         chan_upds_recvd: AtomicUsize::new(0),
237                         chan_anns_recvd: AtomicUsize::new(0),
238                         chan_anns_sent: AtomicUsize::new(0),
239                         request_full_sync: AtomicBool::new(false),
240                 }
241         }
242 }
243 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
244         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
245                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
246         }
247         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
248                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
249                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
250         }
251         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
252                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
253                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
254         }
255         fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
256         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
257                 let mut chan_anns = Vec::new();
258                 const TOTAL_UPDS: u64 = 100;
259                 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS - self.chan_anns_sent.load(Ordering::Acquire) as u64);
260                 for i in starting_point..end {
261                         let chan_upd_1 = get_dummy_channel_update(i);
262                         let chan_upd_2 = get_dummy_channel_update(i);
263                         let chan_ann = get_dummy_channel_announcement(i);
264
265                         chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
266                 }
267
268                 self.chan_anns_sent.fetch_add(chan_anns.len(), Ordering::AcqRel);
269                 chan_anns
270         }
271
272         fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
273                 Vec::new()
274         }
275
276         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
277                 self.request_full_sync.load(Ordering::Acquire)
278         }
279 }
280
281 pub struct TestLogger {
282         level: Level,
283         id: String,
284         pub lines: Mutex<HashMap<(String, String), usize>>,
285 }
286
287 impl TestLogger {
288         pub fn new() -> TestLogger {
289                 Self::with_id("".to_owned())
290         }
291         pub fn with_id(id: String) -> TestLogger {
292                 TestLogger {
293                         level: Level::Trace,
294                         id,
295                         lines: Mutex::new(HashMap::new())
296                 }
297         }
298         pub fn enable(&mut self, level: Level) {
299                 self.level = level;
300         }
301         pub fn assert_log(&self, module: String, line: String, count: usize) {
302                 let log_entries = self.lines.lock().unwrap();
303                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
304         }
305
306         /// Search for the number of occurrence of the logged lines which
307         /// 1. belongs to the specified module and
308         /// 2. contains `line` in it.
309         /// And asserts if the number of occurrences is the same with the given `count`
310         pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
311                 let log_entries = self.lines.lock().unwrap();
312                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
313                         m == &module && l.contains(line.as_str())
314                 }).map(|(_, c) | { c }).sum();
315                 assert_eq!(l, count)
316         }
317
318     /// Search for the number of occurrences of logged lines which
319     /// 1. belong to the specified module and
320     /// 2. match the given regex pattern.
321     /// Assert that the number of occurrences equals the given `count`
322         pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
323                 let log_entries = self.lines.lock().unwrap();
324                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
325                         m == &module && pattern.is_match(&l)
326                 }).map(|(_, c) | { c }).sum();
327                 assert_eq!(l, count)
328         }
329 }
330
331 impl Logger for TestLogger {
332         fn log(&self, record: &Record) {
333                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
334                 if self.level >= record.level {
335                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
336                 }
337         }
338 }
339
340 pub struct TestKeysInterface {
341         backing: keysinterface::KeysManager,
342         pub override_session_priv: Mutex<Option<SecretKey>>,
343         pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
344 }
345
346 impl keysinterface::KeysInterface for TestKeysInterface {
347         type ChanKeySigner = EnforcingChannelKeys;
348
349         fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
350         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
351         fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
352         fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
353                 EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
354         }
355
356         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
357                 match *self.override_session_priv.lock().unwrap() {
358                         Some(key) => (key.clone(), [0; 32]),
359                         None => self.backing.get_onion_rand()
360                 }
361         }
362
363         fn get_channel_id(&self) -> [u8; 32] {
364                 match *self.override_channel_id_priv.lock().unwrap() {
365                         Some(key) => key.clone(),
366                         None => self.backing.get_channel_id()
367                 }
368         }
369 }
370
371 impl TestKeysInterface {
372         pub fn new(seed: &[u8; 32], network: Network) -> Self {
373                 let now = Duration::from_secs(genesis_block(network).header.time as u64);
374                 Self {
375                         backing: keysinterface::KeysManager::new(seed, network, now.as_secs(), now.subsec_nanos()),
376                         override_session_priv: Mutex::new(None),
377                         override_channel_id_priv: Mutex::new(None),
378                 }
379         }
380         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, user_id_1: u64, user_id_2: u64) -> EnforcingChannelKeys {
381                 EnforcingChannelKeys::new(self.backing.derive_channel_keys(channel_value_satoshis, user_id_1, user_id_2))
382         }
383 }
384
385 pub struct TestChainWatcher {
386         pub utxo_ret: Mutex<Result<(Script, u64), ChainError>>,
387 }
388
389 impl TestChainWatcher {
390         pub fn new() -> Self {
391                 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
392                 Self { utxo_ret: Mutex::new(Ok((script, u64::max_value()))) }
393         }
394 }
395
396 impl ChainWatchInterface for TestChainWatcher {
397         fn install_watch_tx(&self, _txid: &Txid, _script_pub_key: &Script) { }
398         fn install_watch_outpoint(&self, _outpoint: (Txid, u32), _out_script: &Script) { }
399         fn watch_all_txn(&self) { }
400         fn filter_block<'a>(&self, _block: &'a Block) -> Vec<usize> {
401                 Vec::new()
402         }
403         fn reentered(&self) -> usize { 0 }
404
405         fn get_chain_utxo(&self, _genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
406                 self.utxo_ret.lock().unwrap().clone()
407         }
408 }