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