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