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