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