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