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