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