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