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