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