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