Merge pull request #1347 from jkczyz/2022-03-log-approximation
[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::FixedPenaltyScorer;
25 use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
26 use util::events;
27 use util::logger::{Logger, Level, Record};
28 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
29
30 use bitcoin::blockdata::constants::genesis_block;
31 use bitcoin::blockdata::transaction::{Transaction, TxOut};
32 use bitcoin::blockdata::script::{Builder, Script};
33 use bitcoin::blockdata::opcodes;
34 use bitcoin::blockdata::block::BlockHeader;
35 use bitcoin::network::constants::Network;
36 use bitcoin::hash_types::{BlockHash, Txid};
37
38 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
39 use bitcoin::secp256k1::recovery::RecoverableSignature;
40
41 use regex;
42
43 use io;
44 use prelude::*;
45 use core::time::Duration;
46 use sync::{Mutex, Arc};
47 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
48 use core::{cmp, mem};
49 use bitcoin::bech32::u5;
50 use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial};
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, _recipient: Recipient) -> Result<SecretKey, ()> { unreachable!(); }
74         fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
75         fn get_destination_script(&self) -> Script { unreachable!(); }
76         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
77         fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
78         fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
79
80         fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
81                 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
82                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
83                 let state = Arc::new(Mutex::new(EnforcementState::new()));
84
85                 Ok(EnforcingSigner::new_with_revoked(
86                         inner,
87                         state,
88                         false
89                 ))
90         }
91         fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> { unreachable!(); }
92 }
93
94 pub struct TestChainMonitor<'a> {
95         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
96         pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
97         pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
98         pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
99         pub keys_manager: &'a TestKeysInterface,
100         /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
101         /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
102         /// boolean.
103         pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
104 }
105 impl<'a> TestChainMonitor<'a> {
106         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 {
107                 Self {
108                         added_monitors: Mutex::new(Vec::new()),
109                         monitor_updates: Mutex::new(HashMap::new()),
110                         latest_monitor_update_id: Mutex::new(HashMap::new()),
111                         chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
112                         keys_manager,
113                         expect_channel_force_closed: Mutex::new(None),
114                 }
115         }
116 }
117 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
118         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
119                 // At every point where we get a monitor update, we should be able to send a useful monitor
120                 // to a watchtower and disk...
121                 let mut w = TestVecWriter(Vec::new());
122                 monitor.write(&mut w).unwrap();
123                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
124                         &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
125                 assert!(new_monitor == monitor);
126                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
127                         (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
128                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
129                 self.chain_monitor.watch_channel(funding_txo, new_monitor)
130         }
131
132         fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
133                 // Every monitor update should survive roundtrip
134                 let mut w = TestVecWriter(Vec::new());
135                 update.write(&mut w).unwrap();
136                 assert!(channelmonitor::ChannelMonitorUpdate::read(
137                                 &mut io::Cursor::new(&w.0)).unwrap() == update);
138
139                 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
140
141                 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
142                         assert_eq!(funding_txo.to_channel_id(), exp.0);
143                         assert_eq!(update.updates.len(), 1);
144                         if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
145                                 assert_eq!(should_broadcast, exp.1);
146                         } else { panic!(); }
147                 }
148
149                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
150                         (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
151                 let update_res = self.chain_monitor.update_channel(funding_txo, update);
152                 // At every point where we get a monitor update, we should be able to send a useful monitor
153                 // to a watchtower and disk...
154                 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
155                 w.0.clear();
156                 monitor.write(&mut w).unwrap();
157                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
158                         &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
159                 assert!(new_monitor == *monitor);
160                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
161                 update_res
162         }
163
164         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
165                 return self.chain_monitor.release_pending_monitor_events();
166         }
167 }
168
169 pub struct TestPersister {
170         pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
171         /// If this is set to Some(), after the next return, we'll always return this until update_ret
172         /// is changed:
173         pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
174         /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
175         /// MonitorUpdateId here.
176         pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
177         /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
178         /// MonitorUpdateId here.
179         pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
180 }
181 impl TestPersister {
182         pub fn new() -> Self {
183                 Self {
184                         update_ret: Mutex::new(Ok(())),
185                         next_update_ret: Mutex::new(None),
186                         chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
187                         offchain_monitor_updates: Mutex::new(HashMap::new()),
188                 }
189         }
190
191         pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
192                 *self.update_ret.lock().unwrap() = ret;
193         }
194
195         pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
196                 *self.next_update_ret.lock().unwrap() = next_ret;
197         }
198 }
199 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
200         fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
201                 let ret = self.update_ret.lock().unwrap().clone();
202                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
203                         *self.update_ret.lock().unwrap() = next_ret;
204                 }
205                 ret
206         }
207
208         fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
209                 let ret = self.update_ret.lock().unwrap().clone();
210                 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
211                         *self.update_ret.lock().unwrap() = next_ret;
212                 }
213                 if update.is_none() {
214                         self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
215                 } else {
216                         self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
217                 }
218                 ret
219         }
220 }
221
222 pub struct TestBroadcaster {
223         pub txn_broadcasted: Mutex<Vec<Transaction>>,
224         pub blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>,
225 }
226
227 impl TestBroadcaster {
228         pub fn new(blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>) -> TestBroadcaster {
229                 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
230         }
231 }
232
233 impl chaininterface::BroadcasterInterface for TestBroadcaster {
234         fn broadcast_transaction(&self, tx: &Transaction) {
235                 assert!(tx.lock_time < 1_500_000_000);
236                 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
237                         for inp in tx.input.iter() {
238                                 if inp.sequence != 0xffffffff {
239                                         panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
240                                 }
241                         }
242                 }
243                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
244         }
245 }
246
247 pub struct TestChannelMessageHandler {
248         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
249 }
250
251 impl TestChannelMessageHandler {
252         pub fn new() -> Self {
253                 TestChannelMessageHandler {
254                         pending_events: Mutex::new(Vec::new()),
255                 }
256         }
257 }
258
259 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
260         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
261         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
262         fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
263         fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
264         fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
265         fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, _msg: &msgs::Shutdown) {}
266         fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
267         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
268         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
269         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
270         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
271         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
272         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
273         fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
274         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
275         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
276         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
277         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
278         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
279         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
280 }
281
282 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
283         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
284                 let mut pending_events = self.pending_events.lock().unwrap();
285                 let mut ret = Vec::new();
286                 mem::swap(&mut ret, &mut *pending_events);
287                 ret
288         }
289 }
290
291 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
292         use bitcoin::secp256k1::ffi::Signature as FFISignature;
293         let secp_ctx = Secp256k1::new();
294         let network = Network::Testnet;
295         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
296         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
297         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
298         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
299         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
300                 features: ChannelFeatures::known(),
301                 chain_hash: genesis_block(network).header.block_hash(),
302                 short_channel_id: short_chan_id,
303                 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
304                 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
305                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
306                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
307                 excess_data: Vec::new(),
308         };
309
310         unsafe {
311                 msgs::ChannelAnnouncement {
312                         node_signature_1: Signature::from(FFISignature::new()),
313                         node_signature_2: Signature::from(FFISignature::new()),
314                         bitcoin_signature_1: Signature::from(FFISignature::new()),
315                         bitcoin_signature_2: Signature::from(FFISignature::new()),
316                         contents: unsigned_ann,
317                 }
318         }
319 }
320
321 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
322         use bitcoin::secp256k1::ffi::Signature as FFISignature;
323         let network = Network::Testnet;
324         msgs::ChannelUpdate {
325                 signature: Signature::from(unsafe { FFISignature::new() }),
326                 contents: msgs::UnsignedChannelUpdate {
327                         chain_hash: genesis_block(network).header.block_hash(),
328                         short_channel_id: short_chan_id,
329                         timestamp: 0,
330                         flags: 0,
331                         cltv_expiry_delta: 0,
332                         htlc_minimum_msat: 0,
333                         htlc_maximum_msat: OptionalField::Absent,
334                         fee_base_msat: 0,
335                         fee_proportional_millionths: 0,
336                         excess_data: vec![],
337                 }
338         }
339 }
340
341 pub struct TestRoutingMessageHandler {
342         pub chan_upds_recvd: AtomicUsize,
343         pub chan_anns_recvd: AtomicUsize,
344         pub request_full_sync: AtomicBool,
345 }
346
347 impl TestRoutingMessageHandler {
348         pub fn new() -> Self {
349                 TestRoutingMessageHandler {
350                         chan_upds_recvd: AtomicUsize::new(0),
351                         chan_anns_recvd: AtomicUsize::new(0),
352                         request_full_sync: AtomicBool::new(false),
353                 }
354         }
355 }
356 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
357         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
358                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
359         }
360         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
361                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
362                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
363         }
364         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
365                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
366                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
367         }
368         fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
369                 let mut chan_anns = Vec::new();
370                 const TOTAL_UPDS: u64 = 50;
371                 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS);
372                 for i in starting_point..end {
373                         let chan_upd_1 = get_dummy_channel_update(i);
374                         let chan_upd_2 = get_dummy_channel_update(i);
375                         let chan_ann = get_dummy_channel_announcement(i);
376
377                         chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
378                 }
379
380                 chan_anns
381         }
382
383         fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
384                 Vec::new()
385         }
386
387         fn sync_routing_table(&self, _their_node_id: &PublicKey, _init_msg: &msgs::Init) {}
388
389         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
390                 Ok(())
391         }
392
393         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
394                 Ok(())
395         }
396
397         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
398                 Ok(())
399         }
400
401         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
402                 Ok(())
403         }
404 }
405
406 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
407         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
408                 vec![]
409         }
410 }
411
412 pub struct TestLogger {
413         level: Level,
414         #[cfg(feature = "std")]
415         id: String,
416         #[cfg(not(feature = "std"))]
417         _id: String,
418         pub lines: Mutex<HashMap<(String, String), usize>>,
419 }
420
421 impl TestLogger {
422         pub fn new() -> TestLogger {
423                 Self::with_id("".to_owned())
424         }
425         pub fn with_id(id: String) -> TestLogger {
426                 TestLogger {
427                         level: Level::Trace,
428                         #[cfg(feature = "std")]
429                         id,
430                         #[cfg(not(feature = "std"))]
431                         _id: id,
432                         lines: Mutex::new(HashMap::new())
433                 }
434         }
435         pub fn enable(&mut self, level: Level) {
436                 self.level = level;
437         }
438         pub fn assert_log(&self, module: String, line: String, count: usize) {
439                 let log_entries = self.lines.lock().unwrap();
440                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
441         }
442
443         /// Search for the number of occurrence of the logged lines which
444         /// 1. belongs to the specified module and
445         /// 2. contains `line` in it.
446         /// And asserts if the number of occurrences is the same with the given `count`
447         pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
448                 let log_entries = self.lines.lock().unwrap();
449                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
450                         m == &module && l.contains(line.as_str())
451                 }).map(|(_, c) | { c }).sum();
452                 assert_eq!(l, count)
453         }
454
455     /// Search for the number of occurrences of logged lines which
456     /// 1. belong to the specified module and
457     /// 2. match the given regex pattern.
458     /// Assert that the number of occurrences equals the given `count`
459         pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
460                 let log_entries = self.lines.lock().unwrap();
461                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
462                         m == &module && pattern.is_match(&l)
463                 }).map(|(_, c) | { c }).sum();
464                 assert_eq!(l, count)
465         }
466 }
467
468 impl Logger for TestLogger {
469         fn log(&self, record: &Record) {
470                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
471                 if record.level >= self.level {
472                         #[cfg(feature = "std")]
473                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
474                 }
475         }
476 }
477
478 pub struct TestKeysInterface {
479         pub backing: keysinterface::PhantomKeysManager,
480         pub override_random_bytes: Mutex<Option<[u8; 32]>>,
481         pub disable_revocation_policy_check: bool,
482         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
483         expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
484 }
485
486 impl keysinterface::KeysInterface for TestKeysInterface {
487         type Signer = EnforcingSigner;
488
489         fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
490                 self.backing.get_node_secret(recipient)
491         }
492         fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
493                 self.backing.get_inbound_payment_key_material()
494         }
495         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
496
497         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
498                 match &mut *self.expectations.lock().unwrap() {
499                         None => self.backing.get_shutdown_scriptpubkey(),
500                         Some(expectations) => match expectations.pop_front() {
501                                 None => panic!("Unexpected get_shutdown_scriptpubkey"),
502                                 Some(expectation) => expectation.returns,
503                         },
504                 }
505         }
506
507         fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
508                 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
509                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
510                 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
511         }
512
513         fn get_secure_random_bytes(&self) -> [u8; 32] {
514                 let override_random_bytes = self.override_random_bytes.lock().unwrap();
515                 if let Some(bytes) = &*override_random_bytes {
516                         return *bytes;
517                 }
518                 self.backing.get_secure_random_bytes()
519         }
520
521         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
522                 let mut reader = io::Cursor::new(buffer);
523
524                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
525                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
526
527                 Ok(EnforcingSigner::new_with_revoked(
528                         inner,
529                         state,
530                         self.disable_revocation_policy_check
531                 ))
532         }
533
534         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
535                 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
536         }
537 }
538
539 impl TestKeysInterface {
540         pub fn new(seed: &[u8; 32], network: Network) -> Self {
541                 let now = Duration::from_secs(genesis_block(network).header.time as u64);
542                 Self {
543                         backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
544                         override_random_bytes: 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 = FixedPenaltyScorer;