Test utils: allow queueing >2 persistence update results
[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         /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
228         /// returned.
229         pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
230         /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
231         /// MonitorUpdateId here.
232         pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
233         /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
234         /// MonitorUpdateId here.
235         pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
236 }
237 impl TestPersister {
238         pub fn new() -> Self {
239                 Self {
240                         update_rets: Mutex::new(VecDeque::new()),
241                         chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
242                         offchain_monitor_updates: Mutex::new(HashMap::new()),
243                 }
244         }
245
246         /// Queue an update status to return.
247         pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
248                 self.update_rets.lock().unwrap().push_back(next_ret);
249         }
250 }
251 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
252         fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
253                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
254                         return update_ret
255                 }
256                 chain::ChannelMonitorUpdateStatus::Completed
257         }
258
259         fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
260                 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
261                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
262                         ret = update_ret;
263                 }
264                 if update.is_none() {
265                         self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
266                 } else {
267                         self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
268                 }
269                 ret
270         }
271 }
272
273 pub struct TestBroadcaster {
274         pub txn_broadcasted: Mutex<Vec<Transaction>>,
275         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
276 }
277
278 impl TestBroadcaster {
279         pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
280                 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
281         }
282 }
283
284 impl chaininterface::BroadcasterInterface for TestBroadcaster {
285         fn broadcast_transaction(&self, tx: &Transaction) {
286                 let lock_time = tx.lock_time.0;
287                 assert!(lock_time < 1_500_000_000);
288                 if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 {
289                         for inp in tx.input.iter() {
290                                 if inp.sequence != Sequence::MAX {
291                                         panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
292                                 }
293                         }
294                 }
295                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
296         }
297 }
298
299 pub struct TestChannelMessageHandler {
300         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
301         expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
302 }
303
304 impl TestChannelMessageHandler {
305         pub fn new() -> Self {
306                 TestChannelMessageHandler {
307                         pending_events: Mutex::new(Vec::new()),
308                         expected_recv_msgs: Mutex::new(None),
309                 }
310         }
311
312         #[cfg(test)]
313         pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
314                 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
315                 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
316                 expected_msgs.as_mut().unwrap().push(ev);
317         }
318
319         fn received_msg(&self, _ev: wire::Message<()>) {
320                 let mut msgs = self.expected_recv_msgs.lock().unwrap();
321                 if msgs.is_none() { return; }
322                 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
323                 #[cfg(test)]
324                 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
325                 msgs.as_mut().unwrap().remove(0);
326         }
327 }
328
329 impl Drop for TestChannelMessageHandler {
330         fn drop(&mut self) {
331                 #[cfg(feature = "std")]
332                 {
333                         let l = self.expected_recv_msgs.lock().unwrap();
334                         if !std::thread::panicking() {
335                                 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
336                         }
337                 }
338         }
339 }
340
341 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
342         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
343                 self.received_msg(wire::Message::OpenChannel(msg.clone()));
344         }
345         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
346                 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
347         }
348         fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
349                 self.received_msg(wire::Message::FundingCreated(msg.clone()));
350         }
351         fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
352                 self.received_msg(wire::Message::FundingSigned(msg.clone()));
353         }
354         fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
355                 self.received_msg(wire::Message::ChannelReady(msg.clone()));
356         }
357         fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
358                 self.received_msg(wire::Message::Shutdown(msg.clone()));
359         }
360         fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
361                 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
362         }
363         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
364                 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
365         }
366         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
367                 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
368         }
369         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
370                 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
371         }
372         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
373                 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
374         }
375         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
376                 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
377         }
378         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
379                 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
380         }
381         fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
382                 self.received_msg(wire::Message::UpdateFee(msg.clone()));
383         }
384         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
385                 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
386         }
387         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
388                 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
389         }
390         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
391                 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
392         }
393         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
394         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> {
395                 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
396                 // bother re-generating the expected Init message in all tests.
397                 Ok(())
398         }
399         fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
400                 self.received_msg(wire::Message::Error(msg.clone()));
401         }
402         fn provided_node_features(&self) -> NodeFeatures {
403                 channelmanager::provided_node_features()
404         }
405         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
406                 channelmanager::provided_init_features()
407         }
408 }
409
410 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
411         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
412                 let mut pending_events = self.pending_events.lock().unwrap();
413                 let mut ret = Vec::new();
414                 mem::swap(&mut ret, &mut *pending_events);
415                 ret
416         }
417 }
418
419 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
420         use bitcoin::secp256k1::ffi::Signature as FFISignature;
421         let secp_ctx = Secp256k1::new();
422         let network = Network::Testnet;
423         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
424         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
425         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
426         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
427         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
428                 features: ChannelFeatures::empty(),
429                 chain_hash: genesis_block(network).header.block_hash(),
430                 short_channel_id: short_chan_id,
431                 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
432                 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
433                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
434                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
435                 excess_data: Vec::new(),
436         };
437
438         unsafe {
439                 msgs::ChannelAnnouncement {
440                         node_signature_1: Signature::from(FFISignature::new()),
441                         node_signature_2: Signature::from(FFISignature::new()),
442                         bitcoin_signature_1: Signature::from(FFISignature::new()),
443                         bitcoin_signature_2: Signature::from(FFISignature::new()),
444                         contents: unsigned_ann,
445                 }
446         }
447 }
448
449 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
450         use bitcoin::secp256k1::ffi::Signature as FFISignature;
451         let network = Network::Testnet;
452         msgs::ChannelUpdate {
453                 signature: Signature::from(unsafe { FFISignature::new() }),
454                 contents: msgs::UnsignedChannelUpdate {
455                         chain_hash: genesis_block(network).header.block_hash(),
456                         short_channel_id: short_chan_id,
457                         timestamp: 0,
458                         flags: 0,
459                         cltv_expiry_delta: 0,
460                         htlc_minimum_msat: 0,
461                         htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
462                         fee_base_msat: 0,
463                         fee_proportional_millionths: 0,
464                         excess_data: vec![],
465                 }
466         }
467 }
468
469 pub struct TestRoutingMessageHandler {
470         pub chan_upds_recvd: AtomicUsize,
471         pub chan_anns_recvd: AtomicUsize,
472         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
473         pub request_full_sync: AtomicBool,
474 }
475
476 impl TestRoutingMessageHandler {
477         pub fn new() -> Self {
478                 TestRoutingMessageHandler {
479                         chan_upds_recvd: AtomicUsize::new(0),
480                         chan_anns_recvd: AtomicUsize::new(0),
481                         pending_events: Mutex::new(vec![]),
482                         request_full_sync: AtomicBool::new(false),
483                 }
484         }
485 }
486 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
487         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
488                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
489         }
490         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
491                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
492                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
493         }
494         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
495                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
496                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
497         }
498         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
499                 let chan_upd_1 = get_dummy_channel_update(starting_point);
500                 let chan_upd_2 = get_dummy_channel_update(starting_point);
501                 let chan_ann = get_dummy_channel_announcement(starting_point);
502
503                 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
504         }
505
506         fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> {
507                 None
508         }
509
510         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
511                 if !init_msg.features.supports_gossip_queries() {
512                         return Ok(());
513                 }
514
515                 #[allow(unused_mut, unused_assignments)]
516                 let mut gossip_start_time = 0;
517                 #[cfg(feature = "std")]
518                 {
519                         gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
520                         if self.request_full_sync.load(Ordering::Acquire) {
521                                 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
522                         } else {
523                                 gossip_start_time -= 60 * 60; // an hour ago
524                         }
525                 }
526
527                 let mut pending_events = self.pending_events.lock().unwrap();
528                 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
529                         node_id: their_node_id.clone(),
530                         msg: msgs::GossipTimestampFilter {
531                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
532                                 first_timestamp: gossip_start_time as u32,
533                                 timestamp_range: u32::max_value(),
534                         },
535                 });
536                 Ok(())
537         }
538
539         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
540                 Ok(())
541         }
542
543         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
544                 Ok(())
545         }
546
547         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
548                 Ok(())
549         }
550
551         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
552                 Ok(())
553         }
554
555         fn provided_node_features(&self) -> NodeFeatures {
556                 let mut features = NodeFeatures::empty();
557                 features.set_gossip_queries_optional();
558                 features
559         }
560
561         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
562                 let mut features = InitFeatures::empty();
563                 features.set_gossip_queries_optional();
564                 features
565         }
566 }
567
568 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
569         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
570                 let mut ret = Vec::new();
571                 let mut pending_events = self.pending_events.lock().unwrap();
572                 core::mem::swap(&mut ret, &mut pending_events);
573                 ret
574         }
575 }
576
577 pub struct TestLogger {
578         level: Level,
579         pub(crate) id: String,
580         pub lines: Mutex<HashMap<(String, String), usize>>,
581 }
582
583 impl TestLogger {
584         pub fn new() -> TestLogger {
585                 Self::with_id("".to_owned())
586         }
587         pub fn with_id(id: String) -> TestLogger {
588                 TestLogger {
589                         level: Level::Trace,
590                         id,
591                         lines: Mutex::new(HashMap::new())
592                 }
593         }
594         pub fn enable(&mut self, level: Level) {
595                 self.level = level;
596         }
597         pub fn assert_log(&self, module: String, line: String, count: usize) {
598                 let log_entries = self.lines.lock().unwrap();
599                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
600         }
601
602         /// Search for the number of occurrence of the logged lines which
603         /// 1. belongs to the specified module and
604         /// 2. contains `line` in it.
605         /// And asserts if the number of occurrences is the same with the given `count`
606         pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
607                 let log_entries = self.lines.lock().unwrap();
608                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
609                         m == &module && l.contains(line.as_str())
610                 }).map(|(_, c) | { c }).sum();
611                 assert_eq!(l, count)
612         }
613
614         /// Search for the number of occurrences of logged lines which
615         /// 1. belong to the specified module and
616         /// 2. match the given regex pattern.
617         /// Assert that the number of occurrences equals the given `count`
618         pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
619                 let log_entries = self.lines.lock().unwrap();
620                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
621                         m == &module && pattern.is_match(&l)
622                 }).map(|(_, c) | { c }).sum();
623                 assert_eq!(l, count)
624         }
625 }
626
627 impl Logger for TestLogger {
628         fn log(&self, record: &Record) {
629                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
630                 if record.level >= self.level {
631                         #[cfg(feature = "std")]
632                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
633                 }
634         }
635 }
636
637 pub struct TestKeysInterface {
638         pub backing: keysinterface::PhantomKeysManager,
639         pub override_random_bytes: Mutex<Option<[u8; 32]>>,
640         pub disable_revocation_policy_check: bool,
641         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
642         expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
643 }
644
645 impl EntropySource for TestKeysInterface {
646         fn get_secure_random_bytes(&self) -> [u8; 32] {
647                 let override_random_bytes = self.override_random_bytes.lock().unwrap();
648                 if let Some(bytes) = &*override_random_bytes {
649                         return *bytes;
650                 }
651                 self.backing.get_secure_random_bytes()
652         }
653 }
654
655 impl NodeSigner for TestKeysInterface {
656         fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
657                 self.backing.get_node_secret(recipient)
658         }
659
660         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
661                 self.backing.get_node_id(recipient)
662         }
663
664         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
665                 self.backing.ecdh(recipient, other_key, tweak)
666         }
667
668         fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
669                 self.backing.get_inbound_payment_key_material()
670         }
671
672         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
673                 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
674         }
675 }
676
677 impl SignerProvider for TestKeysInterface {
678         type Signer = EnforcingSigner;
679
680         fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
681                 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
682         }
683
684         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
685                 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
686                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
687                 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
688         }
689
690         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
691                 let mut reader = io::Cursor::new(buffer);
692
693                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
694                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
695
696                 Ok(EnforcingSigner::new_with_revoked(
697                         inner,
698                         state,
699                         self.disable_revocation_policy_check
700                 ))
701         }
702
703         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
704
705         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
706                 match &mut *self.expectations.lock().unwrap() {
707                         None => self.backing.get_shutdown_scriptpubkey(),
708                         Some(expectations) => match expectations.pop_front() {
709                                 None => panic!("Unexpected get_shutdown_scriptpubkey"),
710                                 Some(expectation) => expectation.returns,
711                         },
712                 }
713         }
714 }
715
716 impl keysinterface::KeysInterface for TestKeysInterface {}
717
718 impl TestKeysInterface {
719         pub fn new(seed: &[u8; 32], network: Network) -> Self {
720                 let now = Duration::from_secs(genesis_block(network).header.time as u64);
721                 Self {
722                         backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
723                         override_random_bytes: Mutex::new(None),
724                         disable_revocation_policy_check: false,
725                         enforcement_states: Mutex::new(HashMap::new()),
726                         expectations: Mutex::new(None),
727                 }
728         }
729
730         /// Sets an expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] is
731         /// called.
732         pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
733                 self.expectations.lock().unwrap()
734                         .get_or_insert_with(|| VecDeque::new())
735                         .push_back(expectation);
736                 self
737         }
738
739         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
740                 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
741                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
742                 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
743         }
744
745         fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
746                 let mut states = self.enforcement_states.lock().unwrap();
747                 if !states.contains_key(&commitment_seed) {
748                         let state = EnforcementState::new();
749                         states.insert(commitment_seed, Arc::new(Mutex::new(state)));
750                 }
751                 let cell = states.get(&commitment_seed).unwrap();
752                 Arc::clone(cell)
753         }
754 }
755
756 pub(crate) fn panicking() -> bool {
757         #[cfg(feature = "std")]
758         let panicking = ::std::thread::panicking();
759         #[cfg(not(feature = "std"))]
760         let panicking = false;
761         return panicking;
762 }
763
764 impl Drop for TestKeysInterface {
765         fn drop(&mut self) {
766                 if panicking() {
767                         return;
768                 }
769
770                 if let Some(expectations) = &*self.expectations.lock().unwrap() {
771                         if !expectations.is_empty() {
772                                 panic!("Unsatisfied expectations: {:?}", expectations);
773                         }
774                 }
775         }
776 }
777
778 /// An expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] was called and
779 /// returns a [`ShutdownScript`].
780 pub struct OnGetShutdownScriptpubkey {
781         /// A shutdown script used to close a channel.
782         pub returns: ShutdownScript,
783 }
784
785 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
786         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
787                 f.debug_struct("OnGetShutdownScriptpubkey").finish()
788         }
789 }
790
791 pub struct TestChainSource {
792         pub genesis_hash: BlockHash,
793         pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
794         pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
795         pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
796 }
797
798 impl TestChainSource {
799         pub fn new(network: Network) -> Self {
800                 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
801                 Self {
802                         genesis_hash: genesis_block(network).block_hash(),
803                         utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
804                         watched_txn: Mutex::new(HashSet::new()),
805                         watched_outputs: Mutex::new(HashSet::new()),
806                 }
807         }
808 }
809
810 impl chain::Access for TestChainSource {
811         fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
812                 if self.genesis_hash != *genesis_hash {
813                         return Err(chain::AccessError::UnknownChain);
814                 }
815
816                 self.utxo_ret.lock().unwrap().clone()
817         }
818 }
819
820 impl chain::Filter for TestChainSource {
821         fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
822                 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
823         }
824
825         fn register_output(&self, output: WatchedOutput) {
826                 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
827         }
828 }
829
830 impl Drop for TestChainSource {
831         fn drop(&mut self) {
832                 if panicking() {
833                         return;
834                 }
835         }
836 }
837
838 /// A scorer useful in testing, when the passage of time isn't a concern.
839 pub type TestScorer = FixedPenaltyScorer;