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