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