Remove KeysInterface 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::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 pub struct TestChainMonitor<'a> {
144         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
145         pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
146         pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
147         pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
148         pub keys_manager: &'a TestKeysInterface,
149         /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
150         /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
151         /// boolean.
152         pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
153 }
154 impl<'a> TestChainMonitor<'a> {
155         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 {
156                 Self {
157                         added_monitors: Mutex::new(Vec::new()),
158                         monitor_updates: Mutex::new(HashMap::new()),
159                         latest_monitor_update_id: Mutex::new(HashMap::new()),
160                         chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
161                         keys_manager,
162                         expect_channel_force_closed: Mutex::new(None),
163                 }
164         }
165
166         pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
167                 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
168                 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
169         }
170 }
171 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
172         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
173                 // At every point where we get a monitor update, we should be able to send a useful monitor
174                 // to a watchtower and disk...
175                 let mut w = TestVecWriter(Vec::new());
176                 monitor.write(&mut w).unwrap();
177                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
178                         &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
179                 assert!(new_monitor == monitor);
180                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
181                         (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
182                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
183                 self.chain_monitor.watch_channel(funding_txo, new_monitor)
184         }
185
186         fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
187                 // Every monitor update should survive roundtrip
188                 let mut w = TestVecWriter(Vec::new());
189                 update.write(&mut w).unwrap();
190                 assert!(channelmonitor::ChannelMonitorUpdate::read(
191                                 &mut io::Cursor::new(&w.0)).unwrap() == update);
192
193                 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
194
195                 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
196                         assert_eq!(funding_txo.to_channel_id(), exp.0);
197                         assert_eq!(update.updates.len(), 1);
198                         if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
199                                 assert_eq!(should_broadcast, exp.1);
200                         } else { panic!(); }
201                 }
202
203                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
204                         (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
205                 let update_res = self.chain_monitor.update_channel(funding_txo, update);
206                 // At every point where we get a monitor update, we should be able to send a useful monitor
207                 // to a watchtower and disk...
208                 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
209                 w.0.clear();
210                 monitor.write(&mut w).unwrap();
211                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
212                         &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
213                 assert!(new_monitor == *monitor);
214                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
215                 update_res
216         }
217
218         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
219                 return self.chain_monitor.release_pending_monitor_events();
220         }
221 }
222
223 pub struct TestPersister {
224         /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
225         /// returned.
226         pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
227         /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
228         /// MonitorUpdateId here.
229         pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
230         /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
231         /// MonitorUpdateId here.
232         pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
233 }
234 impl TestPersister {
235         pub fn new() -> Self {
236                 Self {
237                         update_rets: Mutex::new(VecDeque::new()),
238                         chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
239                         offchain_monitor_updates: Mutex::new(HashMap::new()),
240                 }
241         }
242
243         /// Queue an update status to return.
244         pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
245                 self.update_rets.lock().unwrap().push_back(next_ret);
246         }
247 }
248 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
249         fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
250                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
251                         return update_ret
252                 }
253                 chain::ChannelMonitorUpdateStatus::Completed
254         }
255
256         fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
257                 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
258                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
259                         ret = update_ret;
260                 }
261                 if update.is_none() {
262                         self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
263                 } else {
264                         self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
265                 }
266                 ret
267         }
268 }
269
270 pub struct TestBroadcaster {
271         pub txn_broadcasted: Mutex<Vec<Transaction>>,
272         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
273 }
274
275 impl TestBroadcaster {
276         pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
277                 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
278         }
279 }
280
281 impl chaininterface::BroadcasterInterface for TestBroadcaster {
282         fn broadcast_transaction(&self, tx: &Transaction) {
283                 let lock_time = tx.lock_time.0;
284                 assert!(lock_time < 1_500_000_000);
285                 if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 {
286                         for inp in tx.input.iter() {
287                                 if inp.sequence != Sequence::MAX {
288                                         panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
289                                 }
290                         }
291                 }
292                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
293         }
294 }
295
296 pub struct TestChannelMessageHandler {
297         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
298         expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
299 }
300
301 impl TestChannelMessageHandler {
302         pub fn new() -> Self {
303                 TestChannelMessageHandler {
304                         pending_events: Mutex::new(Vec::new()),
305                         expected_recv_msgs: Mutex::new(None),
306                 }
307         }
308
309         #[cfg(test)]
310         pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
311                 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
312                 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
313                 expected_msgs.as_mut().unwrap().push(ev);
314         }
315
316         fn received_msg(&self, _ev: wire::Message<()>) {
317                 let mut msgs = self.expected_recv_msgs.lock().unwrap();
318                 if msgs.is_none() { return; }
319                 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
320                 #[cfg(test)]
321                 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
322                 msgs.as_mut().unwrap().remove(0);
323         }
324 }
325
326 impl Drop for TestChannelMessageHandler {
327         fn drop(&mut self) {
328                 #[cfg(feature = "std")]
329                 {
330                         let l = self.expected_recv_msgs.lock().unwrap();
331                         if !std::thread::panicking() {
332                                 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
333                         }
334                 }
335         }
336 }
337
338 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
339         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
340                 self.received_msg(wire::Message::OpenChannel(msg.clone()));
341         }
342         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
343                 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
344         }
345         fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
346                 self.received_msg(wire::Message::FundingCreated(msg.clone()));
347         }
348         fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
349                 self.received_msg(wire::Message::FundingSigned(msg.clone()));
350         }
351         fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
352                 self.received_msg(wire::Message::ChannelReady(msg.clone()));
353         }
354         fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
355                 self.received_msg(wire::Message::Shutdown(msg.clone()));
356         }
357         fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
358                 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
359         }
360         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
361                 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
362         }
363         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
364                 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
365         }
366         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
367                 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
368         }
369         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
370                 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
371         }
372         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
373                 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
374         }
375         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
376                 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
377         }
378         fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
379                 self.received_msg(wire::Message::UpdateFee(msg.clone()));
380         }
381         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
382                 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
383         }
384         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
385                 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
386         }
387         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
388                 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
389         }
390         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
391         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> {
392                 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
393                 // bother re-generating the expected Init message in all tests.
394                 Ok(())
395         }
396         fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
397                 self.received_msg(wire::Message::Error(msg.clone()));
398         }
399         fn provided_node_features(&self) -> NodeFeatures {
400                 channelmanager::provided_node_features()
401         }
402         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
403                 channelmanager::provided_init_features()
404         }
405 }
406
407 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
408         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
409                 let mut pending_events = self.pending_events.lock().unwrap();
410                 let mut ret = Vec::new();
411                 mem::swap(&mut ret, &mut *pending_events);
412                 ret
413         }
414 }
415
416 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
417         use bitcoin::secp256k1::ffi::Signature as FFISignature;
418         let secp_ctx = Secp256k1::new();
419         let network = Network::Testnet;
420         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
421         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
422         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
423         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
424         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
425                 features: ChannelFeatures::empty(),
426                 chain_hash: genesis_block(network).header.block_hash(),
427                 short_channel_id: short_chan_id,
428                 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
429                 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
430                 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
431                 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
432                 excess_data: Vec::new(),
433         };
434
435         unsafe {
436                 msgs::ChannelAnnouncement {
437                         node_signature_1: Signature::from(FFISignature::new()),
438                         node_signature_2: Signature::from(FFISignature::new()),
439                         bitcoin_signature_1: Signature::from(FFISignature::new()),
440                         bitcoin_signature_2: Signature::from(FFISignature::new()),
441                         contents: unsigned_ann,
442                 }
443         }
444 }
445
446 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
447         use bitcoin::secp256k1::ffi::Signature as FFISignature;
448         let network = Network::Testnet;
449         msgs::ChannelUpdate {
450                 signature: Signature::from(unsafe { FFISignature::new() }),
451                 contents: msgs::UnsignedChannelUpdate {
452                         chain_hash: genesis_block(network).header.block_hash(),
453                         short_channel_id: short_chan_id,
454                         timestamp: 0,
455                         flags: 0,
456                         cltv_expiry_delta: 0,
457                         htlc_minimum_msat: 0,
458                         htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
459                         fee_base_msat: 0,
460                         fee_proportional_millionths: 0,
461                         excess_data: vec![],
462                 }
463         }
464 }
465
466 pub struct TestRoutingMessageHandler {
467         pub chan_upds_recvd: AtomicUsize,
468         pub chan_anns_recvd: AtomicUsize,
469         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
470         pub request_full_sync: AtomicBool,
471 }
472
473 impl TestRoutingMessageHandler {
474         pub fn new() -> Self {
475                 TestRoutingMessageHandler {
476                         chan_upds_recvd: AtomicUsize::new(0),
477                         chan_anns_recvd: AtomicUsize::new(0),
478                         pending_events: Mutex::new(vec![]),
479                         request_full_sync: AtomicBool::new(false),
480                 }
481         }
482 }
483 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
484         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
485                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
486         }
487         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
488                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
489                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
490         }
491         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
492                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
493                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
494         }
495         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
496                 let chan_upd_1 = get_dummy_channel_update(starting_point);
497                 let chan_upd_2 = get_dummy_channel_update(starting_point);
498                 let chan_ann = get_dummy_channel_announcement(starting_point);
499
500                 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
501         }
502
503         fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> {
504                 None
505         }
506
507         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
508                 if !init_msg.features.supports_gossip_queries() {
509                         return Ok(());
510                 }
511
512                 #[allow(unused_mut, unused_assignments)]
513                 let mut gossip_start_time = 0;
514                 #[cfg(feature = "std")]
515                 {
516                         gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
517                         if self.request_full_sync.load(Ordering::Acquire) {
518                                 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
519                         } else {
520                                 gossip_start_time -= 60 * 60; // an hour ago
521                         }
522                 }
523
524                 let mut pending_events = self.pending_events.lock().unwrap();
525                 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
526                         node_id: their_node_id.clone(),
527                         msg: msgs::GossipTimestampFilter {
528                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
529                                 first_timestamp: gossip_start_time as u32,
530                                 timestamp_range: u32::max_value(),
531                         },
532                 });
533                 Ok(())
534         }
535
536         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
537                 Ok(())
538         }
539
540         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
541                 Ok(())
542         }
543
544         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
545                 Ok(())
546         }
547
548         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
549                 Ok(())
550         }
551
552         fn provided_node_features(&self) -> NodeFeatures {
553                 let mut features = NodeFeatures::empty();
554                 features.set_gossip_queries_optional();
555                 features
556         }
557
558         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
559                 let mut features = InitFeatures::empty();
560                 features.set_gossip_queries_optional();
561                 features
562         }
563 }
564
565 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
566         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
567                 let mut ret = Vec::new();
568                 let mut pending_events = self.pending_events.lock().unwrap();
569                 core::mem::swap(&mut ret, &mut pending_events);
570                 ret
571         }
572 }
573
574 pub struct TestLogger {
575         level: Level,
576         pub(crate) id: String,
577         pub lines: Mutex<HashMap<(String, String), usize>>,
578 }
579
580 impl TestLogger {
581         pub fn new() -> TestLogger {
582                 Self::with_id("".to_owned())
583         }
584         pub fn with_id(id: String) -> TestLogger {
585                 TestLogger {
586                         level: Level::Trace,
587                         id,
588                         lines: Mutex::new(HashMap::new())
589                 }
590         }
591         pub fn enable(&mut self, level: Level) {
592                 self.level = level;
593         }
594         pub fn assert_log(&self, module: String, line: String, count: usize) {
595                 let log_entries = self.lines.lock().unwrap();
596                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
597         }
598
599         /// Search for the number of occurrence of the logged lines which
600         /// 1. belongs to the specified module and
601         /// 2. contains `line` in it.
602         /// And asserts if the number of occurrences is the same with the given `count`
603         pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
604                 let log_entries = self.lines.lock().unwrap();
605                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
606                         m == &module && l.contains(line.as_str())
607                 }).map(|(_, c) | { c }).sum();
608                 assert_eq!(l, count)
609         }
610
611         /// Search for the number of occurrences of logged lines which
612         /// 1. belong to the specified module and
613         /// 2. match the given regex pattern.
614         /// Assert that the number of occurrences equals the given `count`
615         pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
616                 let log_entries = self.lines.lock().unwrap();
617                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
618                         m == &module && pattern.is_match(&l)
619                 }).map(|(_, c) | { c }).sum();
620                 assert_eq!(l, count)
621         }
622 }
623
624 impl Logger for TestLogger {
625         fn log(&self, record: &Record) {
626                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
627                 if record.level >= self.level {
628                         #[cfg(feature = "std")]
629                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
630                 }
631         }
632 }
633
634 pub struct TestKeysInterface {
635         pub backing: keysinterface::PhantomKeysManager,
636         pub override_random_bytes: Mutex<Option<[u8; 32]>>,
637         pub disable_revocation_policy_check: bool,
638         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
639         expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
640 }
641
642 impl EntropySource for TestKeysInterface {
643         fn get_secure_random_bytes(&self) -> [u8; 32] {
644                 let override_random_bytes = self.override_random_bytes.lock().unwrap();
645                 if let Some(bytes) = &*override_random_bytes {
646                         return *bytes;
647                 }
648                 self.backing.get_secure_random_bytes()
649         }
650 }
651
652 impl NodeSigner for TestKeysInterface {
653         fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
654                 self.backing.get_node_secret(recipient)
655         }
656
657         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
658                 self.backing.get_node_id(recipient)
659         }
660
661         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
662                 self.backing.ecdh(recipient, other_key, tweak)
663         }
664
665         fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
666                 self.backing.get_inbound_payment_key_material()
667         }
668
669         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
670                 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
671         }
672 }
673
674 impl SignerProvider for TestKeysInterface {
675         type Signer = EnforcingSigner;
676
677         fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
678                 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
679         }
680
681         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
682                 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
683                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
684                 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
685         }
686
687         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
688                 let mut reader = io::Cursor::new(buffer);
689
690                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
691                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
692
693                 Ok(EnforcingSigner::new_with_revoked(
694                         inner,
695                         state,
696                         self.disable_revocation_policy_check
697                 ))
698         }
699
700         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
701
702         fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
703                 match &mut *self.expectations.lock().unwrap() {
704                         None => self.backing.get_shutdown_scriptpubkey(),
705                         Some(expectations) => match expectations.pop_front() {
706                                 None => panic!("Unexpected get_shutdown_scriptpubkey"),
707                                 Some(expectation) => expectation.returns,
708                         },
709                 }
710         }
711 }
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;