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