dee6907832ea1c974a8209571dfd186b8fa2e557
[rust-lightning] / lightning / src / util / test_utils.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 use chain;
11 use chain::WatchedOutput;
12 use chain::chaininterface;
13 use chain::chaininterface::ConfirmationTarget;
14 use chain::chainmonitor;
15 use chain::chainmonitor::MonitorUpdateId;
16 use chain::channelmonitor;
17 use chain::channelmonitor::MonitorEvent;
18 use chain::transaction::OutPoint;
19 use chain::keysinterface;
20 use ln::features::{ChannelFeatures, InitFeatures};
21 use ln::msgs;
22 use ln::msgs::OptionalField;
23 use ln::script::ShutdownScript;
24 use routing::scoring::ScorerUsingTime;
25 use routing::scoring::time::Eternity;
26 use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
27 use util::events;
28 use util::logger::{Logger, Level, Record};
29 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
30
31 use bitcoin::blockdata::constants::genesis_block;
32 use bitcoin::blockdata::transaction::{Transaction, TxOut};
33 use bitcoin::blockdata::script::{Builder, Script};
34 use bitcoin::blockdata::opcodes;
35 use bitcoin::blockdata::block::BlockHeader;
36 use bitcoin::network::constants::Network;
37 use bitcoin::hash_types::{BlockHash, Txid};
38
39 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
40 use bitcoin::secp256k1::recovery::RecoverableSignature;
41
42 use regex;
43
44 use io;
45 use prelude::*;
46 use core::time::Duration;
47 use sync::{Mutex, Arc};
48 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
49 use core::{cmp, mem};
50 use bitcoin::bech32::u5;
51 use chain::keysinterface::{InMemorySigner, KeyMaterial};
52
53 pub struct TestVecWriter(pub Vec<u8>);
54 impl Writer for TestVecWriter {
55         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
56                 self.0.extend_from_slice(buf);
57                 Ok(())
58         }
59 }
60
61 pub struct TestFeeEstimator {
62         pub sat_per_kw: Mutex<u32>,
63 }
64 impl chaininterface::FeeEstimator for TestFeeEstimator {
65         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
66                 *self.sat_per_kw.lock().unwrap()
67         }
68 }
69
70 pub struct OnlyReadsKeysInterface {}
71 impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
72         type Signer = EnforcingSigner;
73
74         fn get_node_secret(&self) -> SecretKey { unreachable!(); }
75         fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
76         fn get_destination_script(&self) -> Script { unreachable!(); }
77         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
78         fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
79         fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
80
81         fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
82                 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
83                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
84                 let state = Arc::new(Mutex::new(EnforcementState::new()));
85
86                 Ok(EnforcingSigner::new_with_revoked(
87                         inner,
88                         state,
89                         false
90                 ))
91         }
92         fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5]) -> Result<RecoverableSignature, ()> { unreachable!(); }
93 }
94
95 pub struct TestChainMonitor<'a> {
96         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
97         pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
98         pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
99         pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
100         pub keys_manager: &'a TestKeysInterface,
101         /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
102         /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
103         /// boolean.
104         pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
105 }
106 impl<'a> TestChainMonitor<'a> {
107         pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
108                 Self {
109                         added_monitors: Mutex::new(Vec::new()),
110                         monitor_updates: Mutex::new(HashMap::new()),
111                         latest_monitor_update_id: Mutex::new(HashMap::new()),
112                         chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
113                         keys_manager,
114                         expect_channel_force_closed: Mutex::new(None),
115                 }
116         }
117 }
118 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
119         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
120                 // At every point where we get a monitor update, we should be able to send a useful monitor
121                 // to a watchtower and disk...
122                 let mut w = TestVecWriter(Vec::new());
123                 monitor.write(&mut w).unwrap();
124                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
125                         &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
126                 assert!(new_monitor == monitor);
127                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
128                         (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
129                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
130                 self.chain_monitor.watch_channel(funding_txo, new_monitor)
131         }
132
133         fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
134                 // Every monitor update should survive roundtrip
135                 let mut w = TestVecWriter(Vec::new());
136                 update.write(&mut w).unwrap();
137                 assert!(channelmonitor::ChannelMonitorUpdate::read(
138                                 &mut io::Cursor::new(&w.0)).unwrap() == update);
139
140                 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
141
142                 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
143                         assert_eq!(funding_txo.to_channel_id(), exp.0);
144                         assert_eq!(update.updates.len(), 1);
145                         if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
146                                 assert_eq!(should_broadcast, exp.1);
147                         } else { panic!(); }
148                 }
149
150                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
151                         (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
152                 let update_res = self.chain_monitor.update_channel(funding_txo, update);
153                 // At every point where we get a monitor update, we should be able to send a useful monitor
154                 // to a watchtower and disk...
155                 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
156                 w.0.clear();
157                 monitor.write(&mut w).unwrap();
158                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
159                         &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
160                 assert!(new_monitor == *monitor);
161                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
162                 update_res
163         }
164
165         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
166                 return self.chain_monitor.release_pending_monitor_events();
167         }
168 }
169
170 pub struct TestPersister {
171         pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
172         /// If this is set to Some(), after the next return, we'll always return this until update_ret
173         /// is changed:
174         pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
175         /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
176         /// MonitorUpdateId here.
177         pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
178         /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
179         /// MonitorUpdateId here.
180         pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
181 }
182 impl TestPersister {
183         pub fn new() -> Self {
184                 Self {
185                         update_ret: Mutex::new(Ok(())),
186                         next_update_ret: Mutex::new(None),
187                         chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
188                         offchain_monitor_updates: Mutex::new(HashMap::new()),
189                 }
190         }
191
192         pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
193                 *self.update_ret.lock().unwrap() = ret;
194         }
195
196         pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
197                 *self.next_update_ret.lock().unwrap() = next_ret;
198         }
199 }
200 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
201         fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
202                 let ret = self.update_ret.lock().unwrap().clone();
203                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
204                         *self.update_ret.lock().unwrap() = next_ret;
205                 }
206                 ret
207         }
208
209         fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
210                 let ret = self.update_ret.lock().unwrap().clone();
211                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
212                         *self.update_ret.lock().unwrap() = next_ret;
213                 }
214                 if update.is_none() {
215                         self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
216                 } else {
217                         self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
218                 }
219                 ret
220         }
221 }
222
223 pub struct TestBroadcaster {
224         pub txn_broadcasted: Mutex<Vec<Transaction>>,
225         pub blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>,
226 }
227
228 impl TestBroadcaster {
229         pub fn new(blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>) -> TestBroadcaster {
230                 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
231         }
232 }
233
234 impl chaininterface::BroadcasterInterface for TestBroadcaster {
235         fn broadcast_transaction(&self, tx: &Transaction) {
236                 assert!(tx.lock_time < 1_500_000_000);
237                 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
238                         for inp in tx.input.iter() {
239                                 if inp.sequence != 0xffffffff {
240                                         panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
241                                 }
242                         }
243                 }
244                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
245         }
246 }
247
248 pub struct TestChannelMessageHandler {
249         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
250 }
251
252 impl TestChannelMessageHandler {
253         pub fn new() -> Self {
254                 TestChannelMessageHandler {
255                         pending_events: Mutex::new(Vec::new()),
256                 }
257         }
258 }
259
260 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
261         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
262         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
263         fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
264         fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
265         fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
266         fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &msgs::Shutdown) {}
267         fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
268         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
269         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
270         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
271         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
272         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
273         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
274         fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
275         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
276         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
277         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
278         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
279         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
280         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
281 }
282
283 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
284         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
285                 let mut pending_events = self.pending_events.lock().unwrap();
286                 let mut ret = Vec::new();
287                 mem::swap(&mut ret, &mut *pending_events);
288                 ret
289         }
290 }
291
292 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
293         use bitcoin::secp256k1::ffi::Signature as FFISignature;
294         let secp_ctx = Secp256k1::new();
295         let network = Network::Testnet;
296         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
297         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
298         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
299         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
300         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
301                 features: ChannelFeatures::known(),
302                 chain_hash: genesis_block(network).header.block_hash(),
303                 short_channel_id: short_chan_id,
304                 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
305                 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
306                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
307                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
308                 excess_data: Vec::new(),
309         };
310
311         unsafe {
312                 msgs::ChannelAnnouncement {
313                         node_signature_1: Signature::from(FFISignature::new()),
314                         node_signature_2: Signature::from(FFISignature::new()),
315                         bitcoin_signature_1: Signature::from(FFISignature::new()),
316                         bitcoin_signature_2: Signature::from(FFISignature::new()),
317                         contents: unsigned_ann,
318                 }
319         }
320 }
321
322 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
323         use bitcoin::secp256k1::ffi::Signature as FFISignature;
324         let network = Network::Testnet;
325         msgs::ChannelUpdate {
326                 signature: Signature::from(unsafe { FFISignature::new() }),
327                 contents: msgs::UnsignedChannelUpdate {
328                         chain_hash: genesis_block(network).header.block_hash(),
329                         short_channel_id: short_chan_id,
330                         timestamp: 0,
331                         flags: 0,
332                         cltv_expiry_delta: 0,
333                         htlc_minimum_msat: 0,
334                         htlc_maximum_msat: OptionalField::Absent,
335                         fee_base_msat: 0,
336                         fee_proportional_millionths: 0,
337                         excess_data: vec![],
338                 }
339         }
340 }
341
342 pub struct TestRoutingMessageHandler {
343         pub chan_upds_recvd: AtomicUsize,
344         pub chan_anns_recvd: AtomicUsize,
345         pub request_full_sync: AtomicBool,
346 }
347
348 impl TestRoutingMessageHandler {
349         pub fn new() -> Self {
350                 TestRoutingMessageHandler {
351                         chan_upds_recvd: AtomicUsize::new(0),
352                         chan_anns_recvd: AtomicUsize::new(0),
353                         request_full_sync: AtomicBool::new(false),
354                 }
355         }
356 }
357 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
358         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
359                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
360         }
361         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
362                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
363                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
364         }
365         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
366                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
367                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
368         }
369         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
370                 let mut chan_anns = Vec::new();
371                 const TOTAL_UPDS: u64 = 50;
372                 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS);
373                 for i in starting_point..end {
374                         let chan_upd_1 = get_dummy_channel_update(i);
375                         let chan_upd_2 = get_dummy_channel_update(i);
376                         let chan_ann = get_dummy_channel_announcement(i);
377
378                         chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
379                 }
380
381                 chan_anns
382         }
383
384         fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
385                 Vec::new()
386         }
387
388         fn sync_routing_table(&self, _their_node_id: &PublicKey, _init_msg: &msgs::Init) {}
389
390         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
391                 Ok(())
392         }
393
394         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
395                 Ok(())
396         }
397
398         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
399                 Ok(())
400         }
401
402         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
403                 Ok(())
404         }
405 }
406
407 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
408         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
409                 vec![]
410         }
411 }
412
413 pub struct TestLogger {
414         level: Level,
415         id: String,
416         pub lines: Mutex<HashMap<(String, String), usize>>,
417 }
418
419 impl TestLogger {
420         pub fn new() -> TestLogger {
421                 Self::with_id("".to_owned())
422         }
423         pub fn with_id(id: String) -> TestLogger {
424                 TestLogger {
425                         level: Level::Trace,
426                         id,
427                         lines: Mutex::new(HashMap::new())
428                 }
429         }
430         pub fn enable(&mut self, level: Level) {
431                 self.level = level;
432         }
433         pub fn assert_log(&self, module: String, line: String, count: usize) {
434                 let log_entries = self.lines.lock().unwrap();
435                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
436         }
437
438         /// Search for the number of occurrence of the logged lines which
439         /// 1. belongs to the specified module and
440         /// 2. contains `line` in it.
441         /// And asserts if the number of occurrences is the same with the given `count`
442         pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
443                 let log_entries = self.lines.lock().unwrap();
444                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
445                         m == &module && l.contains(line.as_str())
446                 }).map(|(_, c) | { c }).sum();
447                 assert_eq!(l, count)
448         }
449
450     /// Search for the number of occurrences of logged lines which
451     /// 1. belong to the specified module and
452     /// 2. match the given regex pattern.
453     /// Assert that the number of occurrences equals the given `count`
454         pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
455                 let log_entries = self.lines.lock().unwrap();
456                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
457                         m == &module && pattern.is_match(&l)
458                 }).map(|(_, c) | { c }).sum();
459                 assert_eq!(l, count)
460         }
461 }
462
463 impl Logger for TestLogger {
464         fn log(&self, record: &Record) {
465                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
466                 if record.level >= self.level {
467                         #[cfg(feature = "std")]
468                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
469                 }
470         }
471 }
472
473 pub struct TestKeysInterface {
474         pub backing: keysinterface::KeysManager,
475         pub override_session_priv: Mutex<Option<[u8; 32]>>,
476         pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
477         pub disable_revocation_policy_check: bool,
478         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
479         expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
480 }
481
482 impl keysinterface::KeysInterface for TestKeysInterface {
483         type Signer = EnforcingSigner;
484
485         fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
486         fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial { self.backing.get_inbound_payment_key_material() }
487         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
488
489         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
490                 match &mut *self.expectations.lock().unwrap() {
491                         None => self.backing.get_shutdown_scriptpubkey(),
492                         Some(expectations) => match expectations.pop_front() {
493                                 None => panic!("Unexpected get_shutdown_scriptpubkey"),
494                                 Some(expectation) => expectation.returns,
495                         },
496                 }
497         }
498
499         fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
500                 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
501                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
502                 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
503         }
504
505         fn get_secure_random_bytes(&self) -> [u8; 32] {
506                 let override_channel_id = self.override_channel_id_priv.lock().unwrap();
507                 let override_session_key = self.override_session_priv.lock().unwrap();
508                 if override_channel_id.is_some() && override_session_key.is_some() {
509                         panic!("We don't know which override key to use!");
510                 }
511                 if let Some(key) = &*override_channel_id {
512                         return *key;
513                 }
514                 if let Some(key) = &*override_session_key {
515                         return *key;
516                 }
517                 self.backing.get_secure_random_bytes()
518         }
519
520         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
521                 let mut reader = io::Cursor::new(buffer);
522
523                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret())?;
524                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
525
526                 Ok(EnforcingSigner::new_with_revoked(
527                         inner,
528                         state,
529                         self.disable_revocation_policy_check
530                 ))
531         }
532
533         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5]) -> Result<RecoverableSignature, ()> {
534                 self.backing.sign_invoice(hrp_bytes, invoice_data)
535         }
536 }
537
538 impl TestKeysInterface {
539         pub fn new(seed: &[u8; 32], network: Network) -> Self {
540                 let now = Duration::from_secs(genesis_block(network).header.time as u64);
541                 Self {
542                         backing: keysinterface::KeysManager::new(seed, now.as_secs(), now.subsec_nanos()),
543                         override_session_priv: Mutex::new(None),
544                         override_channel_id_priv: Mutex::new(None),
545                         disable_revocation_policy_check: false,
546                         enforcement_states: Mutex::new(HashMap::new()),
547                         expectations: Mutex::new(None),
548                 }
549         }
550
551         /// Sets an expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] is
552         /// called.
553         pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
554                 self.expectations.lock().unwrap()
555                         .get_or_insert_with(|| VecDeque::new())
556                         .push_back(expectation);
557                 self
558         }
559
560         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
561                 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
562                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
563                 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
564         }
565
566         fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
567                 let mut states = self.enforcement_states.lock().unwrap();
568                 if !states.contains_key(&commitment_seed) {
569                         let state = EnforcementState::new();
570                         states.insert(commitment_seed, Arc::new(Mutex::new(state)));
571                 }
572                 let cell = states.get(&commitment_seed).unwrap();
573                 Arc::clone(cell)
574         }
575 }
576
577 pub(crate) fn panicking() -> bool {
578         #[cfg(feature = "std")]
579         let panicking = ::std::thread::panicking();
580         #[cfg(not(feature = "std"))]
581         let panicking = false;
582         return panicking;
583 }
584
585 impl Drop for TestKeysInterface {
586         fn drop(&mut self) {
587                 if panicking() {
588                         return;
589                 }
590
591                 if let Some(expectations) = &*self.expectations.lock().unwrap() {
592                         if !expectations.is_empty() {
593                                 panic!("Unsatisfied expectations: {:?}", expectations);
594                         }
595                 }
596         }
597 }
598
599 /// An expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] was called and
600 /// returns a [`ShutdownScript`].
601 pub struct OnGetShutdownScriptpubkey {
602         /// A shutdown script used to close a channel.
603         pub returns: ShutdownScript,
604 }
605
606 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
607         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
608                 f.debug_struct("OnGetShutdownScriptpubkey").finish()
609         }
610 }
611
612 pub struct TestChainSource {
613         pub genesis_hash: BlockHash,
614         pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
615         pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
616         pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
617         expectations: Mutex<Option<VecDeque<OnRegisterOutput>>>,
618 }
619
620 impl TestChainSource {
621         pub fn new(network: Network) -> Self {
622                 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
623                 Self {
624                         genesis_hash: genesis_block(network).block_hash(),
625                         utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
626                         watched_txn: Mutex::new(HashSet::new()),
627                         watched_outputs: Mutex::new(HashSet::new()),
628                         expectations: Mutex::new(None),
629                 }
630         }
631
632         /// Sets an expectation that [`chain::Filter::register_output`] is called.
633         pub fn expect(&self, expectation: OnRegisterOutput) -> &Self {
634                 self.expectations.lock().unwrap()
635                         .get_or_insert_with(|| VecDeque::new())
636                         .push_back(expectation);
637                 self
638         }
639 }
640
641 impl chain::Access for TestChainSource {
642         fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
643                 if self.genesis_hash != *genesis_hash {
644                         return Err(chain::AccessError::UnknownChain);
645                 }
646
647                 self.utxo_ret.lock().unwrap().clone()
648         }
649 }
650
651 impl chain::Filter for TestChainSource {
652         fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
653                 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
654         }
655
656         fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)> {
657                 let dependent_tx = match &mut *self.expectations.lock().unwrap() {
658                         None => None,
659                         Some(expectations) => match expectations.pop_front() {
660                                 None => {
661                                         panic!("Unexpected register_output: {:?}",
662                                                 (output.outpoint, output.script_pubkey));
663                                 },
664                                 Some(expectation) => {
665                                         assert_eq!(output.outpoint, expectation.outpoint());
666                                         assert_eq!(&output.script_pubkey, expectation.script_pubkey());
667                                         expectation.returns
668                                 },
669                         },
670                 };
671
672                 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
673                 dependent_tx
674         }
675 }
676
677 impl Drop for TestChainSource {
678         fn drop(&mut self) {
679                 if panicking() {
680                         return;
681                 }
682
683                 if let Some(expectations) = &*self.expectations.lock().unwrap() {
684                         if !expectations.is_empty() {
685                                 panic!("Unsatisfied expectations: {:?}", expectations);
686                         }
687                 }
688         }
689 }
690
691 /// An expectation that [`chain::Filter::register_output`] was called with a transaction output and
692 /// returns an optional dependent transaction that spends the output in the same block.
693 pub struct OnRegisterOutput {
694         /// The transaction output to register.
695         pub with: TxOutReference,
696
697         /// A dependent transaction spending the output along with its position in the block.
698         pub returns: Option<(usize, Transaction)>,
699 }
700
701 /// A transaction output as identified by an index into a transaction's output list.
702 pub struct TxOutReference(pub Transaction, pub usize);
703
704 impl OnRegisterOutput {
705         fn outpoint(&self) -> OutPoint {
706                 let txid = self.with.0.txid();
707                 let index = self.with.1 as u16;
708                 OutPoint { txid, index }
709         }
710
711         fn script_pubkey(&self) -> &Script {
712                 let index = self.with.1;
713                 &self.with.0.output[index].script_pubkey
714         }
715 }
716
717 impl core::fmt::Debug for OnRegisterOutput {
718         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
719                 f.debug_struct("OnRegisterOutput")
720                         .field("outpoint", &self.outpoint())
721                         .field("script_pubkey", self.script_pubkey())
722                         .finish()
723         }
724 }
725
726 /// A scorer useful in testing, when the passage of time isn't a concern.
727 pub type TestScorer = ScorerUsingTime<Eternity>;