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