Merge pull request #2696 from TheBlueMatt/2023-10-no-chan-feerate-upper-bound
[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::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
15 use crate::chain::chainmonitor;
16 use crate::chain::chainmonitor::{MonitorUpdateId, UpdateOrigin};
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::MonitorEvent;
19 use crate::chain::transaction::OutPoint;
20 use crate::sign;
21 use crate::events;
22 use crate::events::bump_transaction::{WalletSource, Utxo};
23 use crate::ln::ChannelId;
24 use crate::ln::channelmanager;
25 use crate::ln::chan_utils::CommitmentTransaction;
26 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
27 use crate::ln::{msgs, wire};
28 use crate::ln::msgs::LightningError;
29 use crate::ln::script::ShutdownScript;
30 use crate::offers::invoice::UnsignedBolt12Invoice;
31 use crate::offers::invoice_request::UnsignedInvoiceRequest;
32 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
33 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
34 use crate::routing::router::{find_route, InFlightHtlcs, Path, Route, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
35 use crate::routing::scoring::{ChannelUsage, ScoreUpdate, ScoreLookUp};
36 use crate::sync::RwLock;
37 use crate::util::config::UserConfig;
38 use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
39 use crate::util::logger::{Logger, Level, Record};
40 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
41 use crate::util::persist::KVStore;
42
43 use bitcoin::EcdsaSighashType;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::blockdata::constants::genesis_block;
46 use bitcoin::blockdata::transaction::{Transaction, TxOut};
47 use bitcoin::blockdata::script::{Builder, Script};
48 use bitcoin::blockdata::opcodes;
49 use bitcoin::blockdata::block::Block;
50 use bitcoin::network::constants::Network;
51 use bitcoin::hash_types::{BlockHash, Txid};
52 use bitcoin::util::sighash::SighashCache;
53
54 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
55 use bitcoin::secp256k1::ecdh::SharedSecret;
56 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
57 use bitcoin::secp256k1::schnorr;
58
59 #[cfg(any(test, feature = "_test_utils"))]
60 use regex;
61
62 use crate::io;
63 use crate::prelude::*;
64 use core::cell::RefCell;
65 use core::time::Duration;
66 use crate::sync::{Mutex, Arc};
67 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
68 use core::mem;
69 use bitcoin::bech32::u5;
70 use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
71
72 #[cfg(feature = "std")]
73 use std::time::{SystemTime, UNIX_EPOCH};
74 use bitcoin::Sequence;
75
76 pub fn pubkey(byte: u8) -> PublicKey {
77         let secp_ctx = Secp256k1::new();
78         PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
79 }
80
81 pub fn privkey(byte: u8) -> SecretKey {
82         SecretKey::from_slice(&[byte; 32]).unwrap()
83 }
84
85 pub struct TestVecWriter(pub Vec<u8>);
86 impl Writer for TestVecWriter {
87         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
88                 self.0.extend_from_slice(buf);
89                 Ok(())
90         }
91 }
92
93 pub struct TestFeeEstimator {
94         pub sat_per_kw: Mutex<u32>,
95 }
96 impl chaininterface::FeeEstimator for TestFeeEstimator {
97         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
98                 *self.sat_per_kw.lock().unwrap()
99         }
100 }
101
102 pub struct TestRouter<'a> {
103         pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
104         pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
105         pub scorer: &'a RwLock<TestScorer>,
106 }
107
108 impl<'a> TestRouter<'a> {
109         pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a RwLock<TestScorer>) -> Self {
110                 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
111         }
112
113         pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
114                 let mut expected_routes = self.next_routes.lock().unwrap();
115                 expected_routes.push_back((query, result));
116         }
117 }
118
119 impl<'a> Router for TestRouter<'a> {
120         fn find_route(
121                 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
122                 inflight_htlcs: InFlightHtlcs
123         ) -> Result<Route, msgs::LightningError> {
124                 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
125                         assert_eq!(find_route_query, *params);
126                         if let Ok(ref route) = find_route_res {
127                                 assert_eq!(route.route_params, Some(find_route_query));
128                                 let scorer = self.scorer.read().unwrap();
129                                 let scorer = ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs);
130                                 for path in &route.paths {
131                                         let mut aggregate_msat = 0u64;
132                                         for (idx, hop) in path.hops.iter().rev().enumerate() {
133                                                 aggregate_msat += hop.fee_msat;
134                                                 let usage = ChannelUsage {
135                                                         amount_msat: aggregate_msat,
136                                                         inflight_htlc_msat: 0,
137                                                         effective_capacity: EffectiveCapacity::Unknown,
138                                                 };
139
140                                                 // Since the path is reversed, the last element in our iteration is the first
141                                                 // hop.
142                                                 if idx == path.hops.len() - 1 {
143                                                         scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &Default::default());
144                                                 } else {
145                                                         let curr_hop_path_idx = path.hops.len() - 1 - idx;
146                                                         scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path.hops[curr_hop_path_idx - 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage, &Default::default());
147                                                 }
148                                         }
149                                 }
150                         }
151                         return find_route_res;
152                 }
153                 let logger = TestLogger::new();
154                 find_route(
155                         payer, params, &self.network_graph, first_hops, &logger,
156                         &ScorerAccountingForInFlightHtlcs::new(self.scorer.read().unwrap(), &inflight_htlcs), &Default::default(),
157                         &[42; 32]
158                 )
159         }
160 }
161
162 impl<'a> Drop for TestRouter<'a> {
163         fn drop(&mut self) {
164                 #[cfg(feature = "std")] {
165                         if std::thread::panicking() {
166                                 return;
167                         }
168                 }
169                 assert!(self.next_routes.lock().unwrap().is_empty());
170         }
171 }
172
173 pub struct OnlyReadsKeysInterface {}
174
175 impl EntropySource for OnlyReadsKeysInterface {
176         fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
177
178 impl SignerProvider for OnlyReadsKeysInterface {
179         type Signer = TestChannelSigner;
180
181         fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
182
183         fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
184
185         fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
186                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
187                 let state = Arc::new(Mutex::new(EnforcementState::new()));
188
189                 Ok(TestChannelSigner::new_with_revoked(
190                         inner,
191                         state,
192                         false
193                 ))
194         }
195
196         fn get_destination_script(&self) -> Result<Script, ()> { Err(()) }
197         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
198 }
199
200 pub struct TestChainMonitor<'a> {
201         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<TestChannelSigner>)>>,
202         pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
203         pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, MonitorUpdateId)>>,
204         pub chain_monitor: chainmonitor::ChainMonitor<TestChannelSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<TestChannelSigner>>,
205         pub keys_manager: &'a TestKeysInterface,
206         /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
207         /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
208         /// boolean.
209         pub expect_channel_force_closed: Mutex<Option<(ChannelId, bool)>>,
210         /// If this is set to Some(), the next round trip serialization check will not hold after an
211         /// update_channel call (not watch_channel) for the given channel_id.
212         pub expect_monitor_round_trip_fail: Mutex<Option<ChannelId>>,
213 }
214 impl<'a> TestChainMonitor<'a> {
215         pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<TestChannelSigner>, keys_manager: &'a TestKeysInterface) -> Self {
216                 Self {
217                         added_monitors: Mutex::new(Vec::new()),
218                         monitor_updates: Mutex::new(HashMap::new()),
219                         latest_monitor_update_id: Mutex::new(HashMap::new()),
220                         chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
221                         keys_manager,
222                         expect_channel_force_closed: Mutex::new(None),
223                         expect_monitor_round_trip_fail: Mutex::new(None),
224                 }
225         }
226
227         pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) {
228                 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
229                 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
230         }
231 }
232 impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
233         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
234                 // At every point where we get a monitor update, we should be able to send a useful monitor
235                 // to a watchtower and disk...
236                 let mut w = TestVecWriter(Vec::new());
237                 monitor.write(&mut w).unwrap();
238                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
239                         &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
240                 assert!(new_monitor == monitor);
241                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
242                         (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
243                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
244                 self.chain_monitor.watch_channel(funding_txo, new_monitor)
245         }
246
247         fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
248                 // Every monitor update should survive roundtrip
249                 let mut w = TestVecWriter(Vec::new());
250                 update.write(&mut w).unwrap();
251                 assert!(channelmonitor::ChannelMonitorUpdate::read(
252                                 &mut io::Cursor::new(&w.0)).unwrap() == *update);
253
254                 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
255
256                 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
257                         assert_eq!(funding_txo.to_channel_id(), exp.0);
258                         assert_eq!(update.updates.len(), 1);
259                         if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
260                                 assert_eq!(should_broadcast, exp.1);
261                         } else { panic!(); }
262                 }
263
264                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
265                         (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
266                 let update_res = self.chain_monitor.update_channel(funding_txo, update);
267                 // At every point where we get a monitor update, we should be able to send a useful monitor
268                 // to a watchtower and disk...
269                 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
270                 w.0.clear();
271                 monitor.write(&mut w).unwrap();
272                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
273                         &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
274                 if let Some(chan_id) = self.expect_monitor_round_trip_fail.lock().unwrap().take() {
275                         assert_eq!(chan_id, funding_txo.to_channel_id());
276                         assert!(new_monitor != *monitor);
277                 } else {
278                         assert!(new_monitor == *monitor);
279                 }
280                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
281                 update_res
282         }
283
284         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
285                 return self.chain_monitor.release_pending_monitor_events();
286         }
287 }
288
289 struct JusticeTxData {
290         justice_tx: Transaction,
291         value: u64,
292         commitment_number: u64,
293 }
294
295 pub(crate) struct WatchtowerPersister {
296         persister: TestPersister,
297         /// Upon a new commitment_signed, we'll get a
298         /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
299         /// amount, and commitment number so we can build the justice tx after our counterparty
300         /// revokes it.
301         unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
302         /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
303         /// tx which would be used to provide a watchtower with the data it needs.
304         watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
305         destination_script: Script,
306 }
307
308 impl WatchtowerPersister {
309         #[cfg(test)]
310         pub(crate) fn new(destination_script: Script) -> Self {
311                 WatchtowerPersister {
312                         persister: TestPersister::new(),
313                         unsigned_justice_tx_data: Mutex::new(HashMap::new()),
314                         watchtower_state: Mutex::new(HashMap::new()),
315                         destination_script,
316                 }
317         }
318
319         #[cfg(test)]
320         pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
321         -> Option<Transaction> {
322                 self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
323         }
324
325         fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
326         -> Option<JusticeTxData> {
327                 let trusted_tx = counterparty_commitment_tx.trust();
328                 let output_idx = trusted_tx.revokeable_output_index()?;
329                 let built_tx = trusted_tx.built_transaction();
330                 let value = built_tx.transaction.output[output_idx as usize].value;
331                 let justice_tx = trusted_tx.build_to_local_justice_tx(
332                         FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
333                 let commitment_number = counterparty_commitment_tx.commitment_number();
334                 Some(JusticeTxData { justice_tx, value, commitment_number })
335         }
336 }
337
338 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
339         fn persist_new_channel(&self, funding_txo: OutPoint,
340                 data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
341         ) -> chain::ChannelMonitorUpdateStatus {
342                 let res = self.persister.persist_new_channel(funding_txo, data, id);
343
344                 assert!(self.unsigned_justice_tx_data.lock().unwrap()
345                         .insert(funding_txo, VecDeque::new()).is_none());
346                 assert!(self.watchtower_state.lock().unwrap()
347                         .insert(funding_txo, HashMap::new()).is_none());
348
349                 let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
350                         .expect("First and only call expects Some");
351                 if let Some(justice_data)
352                         = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
353                         self.unsigned_justice_tx_data.lock().unwrap()
354                                 .get_mut(&funding_txo).unwrap()
355                                 .push_back(justice_data);
356                 }
357                 res
358         }
359
360         fn update_persisted_channel(
361                 &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
362                 data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
363         ) -> chain::ChannelMonitorUpdateStatus {
364                 let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);
365
366                 if let Some(update) = update {
367                         let commitment_txs = data.counterparty_commitment_txs_from_update(update);
368                         let justice_datas = commitment_txs.into_iter()
369                                 .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
370                         let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
371                         let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
372                         channel_state.extend(justice_datas);
373
374                         while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
375                                 let input_idx = 0;
376                                 let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
377                                 match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
378                                         Ok(signed_justice_tx) => {
379                                                 let dup = self.watchtower_state.lock().unwrap()
380                                                         .get_mut(&funding_txo).unwrap()
381                                                         .insert(commitment_txid, signed_justice_tx);
382                                                 assert!(dup.is_none());
383                                                 channel_state.pop_front();
384                                         },
385                                         Err(_) => break,
386                                 }
387                         }
388                 }
389                 res
390         }
391 }
392
393 pub struct TestPersister {
394         /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
395         /// returned.
396         pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
397         /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
398         /// MonitorUpdateId here.
399         pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
400         /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
401         /// MonitorUpdateId here.
402         pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
403 }
404 impl TestPersister {
405         pub fn new() -> Self {
406                 Self {
407                         update_rets: Mutex::new(VecDeque::new()),
408                         chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
409                         offchain_monitor_updates: Mutex::new(HashMap::new()),
410                 }
411         }
412
413         /// Queue an update status to return.
414         pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
415                 self.update_rets.lock().unwrap().push_back(next_ret);
416         }
417 }
418 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
419         fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
420                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
421                         return update_ret
422                 }
423                 chain::ChannelMonitorUpdateStatus::Completed
424         }
425
426         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
427                 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
428                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
429                         ret = update_ret;
430                 }
431                 let is_chain_sync = if let UpdateOrigin::ChainSync(_) = update_id.contents { true } else { false };
432                 if is_chain_sync {
433                         self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
434                 } else {
435                         self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
436                 }
437                 ret
438         }
439 }
440
441 pub struct TestStore {
442         persisted_bytes: Mutex<HashMap<String, HashMap<String, Vec<u8>>>>,
443         read_only: bool,
444 }
445
446 impl TestStore {
447         pub fn new(read_only: bool) -> Self {
448                 let persisted_bytes = Mutex::new(HashMap::new());
449                 Self { persisted_bytes, read_only }
450         }
451 }
452
453 impl KVStore for TestStore {
454         fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result<Vec<u8>> {
455                 let persisted_lock = self.persisted_bytes.lock().unwrap();
456                 let prefixed = if secondary_namespace.is_empty() {
457                         primary_namespace.to_string()
458                 } else {
459                         format!("{}/{}", primary_namespace, secondary_namespace)
460                 };
461
462                 if let Some(outer_ref) = persisted_lock.get(&prefixed) {
463                         if let Some(inner_ref) = outer_ref.get(key) {
464                                 let bytes = inner_ref.clone();
465                                 Ok(bytes)
466                         } else {
467                                 Err(io::Error::new(io::ErrorKind::NotFound, "Key not found"))
468                         }
469                 } else {
470                         Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found"))
471                 }
472         }
473
474         fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> {
475                 if self.read_only {
476                         return Err(io::Error::new(
477                                 io::ErrorKind::PermissionDenied,
478                                 "Cannot modify read-only store",
479                         ));
480                 }
481                 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
482
483                 let prefixed = if secondary_namespace.is_empty() {
484                         primary_namespace.to_string()
485                 } else {
486                         format!("{}/{}", primary_namespace, secondary_namespace)
487                 };
488                 let outer_e = persisted_lock.entry(prefixed).or_insert(HashMap::new());
489                 let mut bytes = Vec::new();
490                 bytes.write_all(buf)?;
491                 outer_e.insert(key.to_string(), bytes);
492                 Ok(())
493         }
494
495         fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> {
496                 if self.read_only {
497                         return Err(io::Error::new(
498                                 io::ErrorKind::PermissionDenied,
499                                 "Cannot modify read-only store",
500                         ));
501                 }
502
503                 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
504
505                 let prefixed = if secondary_namespace.is_empty() {
506                         primary_namespace.to_string()
507                 } else {
508                         format!("{}/{}", primary_namespace, secondary_namespace)
509                 };
510                 if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) {
511                                 outer_ref.remove(&key.to_string());
512                 }
513
514                 Ok(())
515         }
516
517         fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> io::Result<Vec<String>> {
518                 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
519
520                 let prefixed = if secondary_namespace.is_empty() {
521                         primary_namespace.to_string()
522                 } else {
523                         format!("{}/{}", primary_namespace, secondary_namespace)
524                 };
525                 match persisted_lock.entry(prefixed) {
526                         hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()),
527                         hash_map::Entry::Vacant(_) => Ok(Vec::new()),
528                 }
529         }
530 }
531
532 pub struct TestBroadcaster {
533         pub txn_broadcasted: Mutex<Vec<Transaction>>,
534         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
535 }
536
537 impl TestBroadcaster {
538         pub fn new(network: Network) -> Self {
539                 Self {
540                         txn_broadcasted: Mutex::new(Vec::new()),
541                         blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
542                 }
543         }
544
545         pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
546                 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
547         }
548
549         pub fn txn_broadcast(&self) -> Vec<Transaction> {
550                 self.txn_broadcasted.lock().unwrap().split_off(0)
551         }
552
553         pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
554                 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
555                 let mut seen = HashSet::new();
556                 txn.retain(|tx| seen.insert(tx.txid()));
557                 txn
558         }
559 }
560
561 impl chaininterface::BroadcasterInterface for TestBroadcaster {
562         fn broadcast_transactions(&self, txs: &[&Transaction]) {
563                 for tx in txs {
564                         let lock_time = tx.lock_time.0;
565                         assert!(lock_time < 1_500_000_000);
566                         if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
567                                 for inp in tx.input.iter() {
568                                         if inp.sequence != Sequence::MAX {
569                                                 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
570                                         }
571                                 }
572                         }
573                 }
574                 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
575                 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
576         }
577 }
578
579 pub struct TestChannelMessageHandler {
580         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
581         expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
582         connected_peers: Mutex<HashSet<PublicKey>>,
583         pub message_fetch_counter: AtomicUsize,
584         chain_hash: ChainHash,
585 }
586
587 impl TestChannelMessageHandler {
588         pub fn new(chain_hash: ChainHash) -> Self {
589                 TestChannelMessageHandler {
590                         pending_events: Mutex::new(Vec::new()),
591                         expected_recv_msgs: Mutex::new(None),
592                         connected_peers: Mutex::new(HashSet::new()),
593                         message_fetch_counter: AtomicUsize::new(0),
594                         chain_hash,
595                 }
596         }
597
598         #[cfg(test)]
599         pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
600                 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
601                 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
602                 expected_msgs.as_mut().unwrap().push(ev);
603         }
604
605         fn received_msg(&self, _ev: wire::Message<()>) {
606                 let mut msgs = self.expected_recv_msgs.lock().unwrap();
607                 if msgs.is_none() { return; }
608                 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
609                 #[cfg(test)]
610                 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
611                 msgs.as_mut().unwrap().remove(0);
612         }
613 }
614
615 impl Drop for TestChannelMessageHandler {
616         fn drop(&mut self) {
617                 #[cfg(feature = "std")]
618                 {
619                         let l = self.expected_recv_msgs.lock().unwrap();
620                         if !std::thread::panicking() {
621                                 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
622                         }
623                 }
624         }
625 }
626
627 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
628         fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
629                 self.received_msg(wire::Message::OpenChannel(msg.clone()));
630         }
631         fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
632                 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
633         }
634         fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
635                 self.received_msg(wire::Message::FundingCreated(msg.clone()));
636         }
637         fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
638                 self.received_msg(wire::Message::FundingSigned(msg.clone()));
639         }
640         fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
641                 self.received_msg(wire::Message::ChannelReady(msg.clone()));
642         }
643         fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
644                 self.received_msg(wire::Message::Shutdown(msg.clone()));
645         }
646         fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
647                 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
648         }
649         fn handle_stfu(&self, _their_node_id: &PublicKey, msg: &msgs::Stfu) {
650                 self.received_msg(wire::Message::Stfu(msg.clone()));
651         }
652         fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
653                 self.received_msg(wire::Message::Splice(msg.clone()));
654         }
655         fn handle_splice_ack(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
656                 self.received_msg(wire::Message::SpliceAck(msg.clone()));
657         }
658         fn handle_splice_locked(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
659                 self.received_msg(wire::Message::SpliceLocked(msg.clone()));
660         }
661         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
662                 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
663         }
664         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
665                 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
666         }
667         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
668                 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
669         }
670         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
671                 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
672         }
673         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
674                 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
675         }
676         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
677                 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
678         }
679         fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
680                 self.received_msg(wire::Message::UpdateFee(msg.clone()));
681         }
682         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
683                 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
684         }
685         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
686                 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
687         }
688         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
689                 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
690         }
691         fn peer_disconnected(&self, their_node_id: &PublicKey) {
692                 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
693         }
694         fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
695                 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
696                 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
697                 // bother re-generating the expected Init message in all tests.
698                 Ok(())
699         }
700         fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
701                 self.received_msg(wire::Message::Error(msg.clone()));
702         }
703         fn provided_node_features(&self) -> NodeFeatures {
704                 channelmanager::provided_node_features(&UserConfig::default())
705         }
706         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
707                 channelmanager::provided_init_features(&UserConfig::default())
708         }
709
710         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
711                 Some(vec![self.chain_hash])
712         }
713
714         fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
715                 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
716         }
717
718         fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
719                 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
720         }
721
722         fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
723                 self.received_msg(wire::Message::TxAddInput(msg.clone()));
724         }
725
726         fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
727                 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
728         }
729
730         fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
731                 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
732         }
733
734         fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
735                 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
736         }
737
738         fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
739                 self.received_msg(wire::Message::TxComplete(msg.clone()));
740         }
741
742         fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
743                 self.received_msg(wire::Message::TxSignatures(msg.clone()));
744         }
745
746         fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
747                 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
748         }
749
750         fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
751                 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
752         }
753
754         fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
755                 self.received_msg(wire::Message::TxAbort(msg.clone()));
756         }
757 }
758
759 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
760         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
761                 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
762                 let mut pending_events = self.pending_events.lock().unwrap();
763                 let mut ret = Vec::new();
764                 mem::swap(&mut ret, &mut *pending_events);
765                 ret
766         }
767 }
768
769 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
770         use bitcoin::secp256k1::ffi::Signature as FFISignature;
771         let secp_ctx = Secp256k1::new();
772         let network = Network::Testnet;
773         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
774         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
775         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
776         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
777         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
778                 features: ChannelFeatures::empty(),
779                 chain_hash: ChainHash::using_genesis_block(network),
780                 short_channel_id: short_chan_id,
781                 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
782                 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
783                 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
784                 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
785                 excess_data: Vec::new(),
786         };
787
788         unsafe {
789                 msgs::ChannelAnnouncement {
790                         node_signature_1: Signature::from(FFISignature::new()),
791                         node_signature_2: Signature::from(FFISignature::new()),
792                         bitcoin_signature_1: Signature::from(FFISignature::new()),
793                         bitcoin_signature_2: Signature::from(FFISignature::new()),
794                         contents: unsigned_ann,
795                 }
796         }
797 }
798
799 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
800         use bitcoin::secp256k1::ffi::Signature as FFISignature;
801         let network = Network::Testnet;
802         msgs::ChannelUpdate {
803                 signature: Signature::from(unsafe { FFISignature::new() }),
804                 contents: msgs::UnsignedChannelUpdate {
805                         chain_hash: ChainHash::using_genesis_block(network),
806                         short_channel_id: short_chan_id,
807                         timestamp: 0,
808                         flags: 0,
809                         cltv_expiry_delta: 0,
810                         htlc_minimum_msat: 0,
811                         htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
812                         fee_base_msat: 0,
813                         fee_proportional_millionths: 0,
814                         excess_data: vec![],
815                 }
816         }
817 }
818
819 pub struct TestRoutingMessageHandler {
820         pub chan_upds_recvd: AtomicUsize,
821         pub chan_anns_recvd: AtomicUsize,
822         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
823         pub request_full_sync: AtomicBool,
824 }
825
826 impl TestRoutingMessageHandler {
827         pub fn new() -> Self {
828                 TestRoutingMessageHandler {
829                         chan_upds_recvd: AtomicUsize::new(0),
830                         chan_anns_recvd: AtomicUsize::new(0),
831                         pending_events: Mutex::new(vec![]),
832                         request_full_sync: AtomicBool::new(false),
833                 }
834         }
835 }
836 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
837         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
838                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
839         }
840         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
841                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
842                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
843         }
844         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
845                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
846                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
847         }
848         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
849                 let chan_upd_1 = get_dummy_channel_update(starting_point);
850                 let chan_upd_2 = get_dummy_channel_update(starting_point);
851                 let chan_ann = get_dummy_channel_announcement(starting_point);
852
853                 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
854         }
855
856         fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
857                 None
858         }
859
860         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
861                 if !init_msg.features.supports_gossip_queries() {
862                         return Ok(());
863                 }
864
865                 #[allow(unused_mut, unused_assignments)]
866                 let mut gossip_start_time = 0;
867                 #[cfg(feature = "std")]
868                 {
869                         gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
870                         if self.request_full_sync.load(Ordering::Acquire) {
871                                 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
872                         } else {
873                                 gossip_start_time -= 60 * 60; // an hour ago
874                         }
875                 }
876
877                 let mut pending_events = self.pending_events.lock().unwrap();
878                 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
879                         node_id: their_node_id.clone(),
880                         msg: msgs::GossipTimestampFilter {
881                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
882                                 first_timestamp: gossip_start_time as u32,
883                                 timestamp_range: u32::max_value(),
884                         },
885                 });
886                 Ok(())
887         }
888
889         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
890                 Ok(())
891         }
892
893         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
894                 Ok(())
895         }
896
897         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
898                 Ok(())
899         }
900
901         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
902                 Ok(())
903         }
904
905         fn provided_node_features(&self) -> NodeFeatures {
906                 let mut features = NodeFeatures::empty();
907                 features.set_gossip_queries_optional();
908                 features
909         }
910
911         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
912                 let mut features = InitFeatures::empty();
913                 features.set_gossip_queries_optional();
914                 features
915         }
916
917         fn processing_queue_high(&self) -> bool { false }
918 }
919
920 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
921         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
922                 let mut ret = Vec::new();
923                 let mut pending_events = self.pending_events.lock().unwrap();
924                 core::mem::swap(&mut ret, &mut pending_events);
925                 ret
926         }
927 }
928
929 pub struct TestLogger {
930         level: Level,
931         pub(crate) id: String,
932         pub lines: Mutex<HashMap<(String, String), usize>>,
933 }
934
935 impl TestLogger {
936         pub fn new() -> TestLogger {
937                 Self::with_id("".to_owned())
938         }
939         pub fn with_id(id: String) -> TestLogger {
940                 TestLogger {
941                         level: Level::Trace,
942                         id,
943                         lines: Mutex::new(HashMap::new())
944                 }
945         }
946         pub fn enable(&mut self, level: Level) {
947                 self.level = level;
948         }
949         pub fn assert_log(&self, module: String, line: String, count: usize) {
950                 let log_entries = self.lines.lock().unwrap();
951                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
952         }
953
954         /// Search for the number of occurrence of the logged lines which
955         /// 1. belongs to the specified module and
956         /// 2. contains `line` in it.
957         /// And asserts if the number of occurrences is the same with the given `count`
958         pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
959                 let log_entries = self.lines.lock().unwrap();
960                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
961                         m == module && l.contains(line)
962                 }).map(|(_, c) | { c }).sum();
963                 assert_eq!(l, count)
964         }
965
966         /// Search for the number of occurrences of logged lines which
967         /// 1. belong to the specified module and
968         /// 2. match the given regex pattern.
969         /// Assert that the number of occurrences equals the given `count`
970         #[cfg(any(test, feature = "_test_utils"))]
971         pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
972                 let log_entries = self.lines.lock().unwrap();
973                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
974                         m == module && pattern.is_match(&l)
975                 }).map(|(_, c) | { c }).sum();
976                 assert_eq!(l, count)
977         }
978 }
979
980 impl Logger for TestLogger {
981         fn log(&self, record: &Record) {
982                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
983                 if record.level >= self.level {
984                         #[cfg(all(not(ldk_bench), feature = "std"))] {
985                                 let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line);
986                                 println!("{:<55}{}", pfx, record.args);
987                         }
988                 }
989         }
990 }
991
992 pub struct TestNodeSigner {
993         node_secret: SecretKey,
994 }
995
996 impl TestNodeSigner {
997         pub fn new(node_secret: SecretKey) -> Self {
998                 Self { node_secret }
999         }
1000 }
1001
1002 impl NodeSigner for TestNodeSigner {
1003         fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
1004                 unreachable!()
1005         }
1006
1007         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1008                 let node_secret = match recipient {
1009                         Recipient::Node => Ok(&self.node_secret),
1010                         Recipient::PhantomNode => Err(())
1011                 }?;
1012                 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
1013         }
1014
1015         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
1016                 let mut node_secret = match recipient {
1017                         Recipient::Node => Ok(self.node_secret.clone()),
1018                         Recipient::PhantomNode => Err(())
1019                 }?;
1020                 if let Some(tweak) = tweak {
1021                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1022                 }
1023                 Ok(SharedSecret::new(other_key, &node_secret))
1024         }
1025
1026         fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
1027                 unreachable!()
1028         }
1029
1030         fn sign_bolt12_invoice_request(
1031                 &self, _invoice_request: &UnsignedInvoiceRequest
1032         ) -> Result<schnorr::Signature, ()> {
1033                 unreachable!()
1034         }
1035
1036         fn sign_bolt12_invoice(
1037                 &self, _invoice: &UnsignedBolt12Invoice,
1038         ) -> Result<schnorr::Signature, ()> {
1039                 unreachable!()
1040         }
1041
1042         fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1043                 unreachable!()
1044         }
1045 }
1046
1047 pub struct TestKeysInterface {
1048         pub backing: sign::PhantomKeysManager,
1049         pub override_random_bytes: Mutex<Option<[u8; 32]>>,
1050         pub disable_revocation_policy_check: bool,
1051         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
1052         expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
1053 }
1054
1055 impl EntropySource for TestKeysInterface {
1056         fn get_secure_random_bytes(&self) -> [u8; 32] {
1057                 let override_random_bytes = self.override_random_bytes.lock().unwrap();
1058                 if let Some(bytes) = &*override_random_bytes {
1059                         return *bytes;
1060                 }
1061                 self.backing.get_secure_random_bytes()
1062         }
1063 }
1064
1065 impl NodeSigner for TestKeysInterface {
1066         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1067                 self.backing.get_node_id(recipient)
1068         }
1069
1070         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1071                 self.backing.ecdh(recipient, other_key, tweak)
1072         }
1073
1074         fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
1075                 self.backing.get_inbound_payment_key_material()
1076         }
1077
1078         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1079                 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
1080         }
1081
1082         fn sign_bolt12_invoice_request(
1083                 &self, invoice_request: &UnsignedInvoiceRequest
1084         ) -> Result<schnorr::Signature, ()> {
1085                 self.backing.sign_bolt12_invoice_request(invoice_request)
1086         }
1087
1088         fn sign_bolt12_invoice(
1089                 &self, invoice: &UnsignedBolt12Invoice,
1090         ) -> Result<schnorr::Signature, ()> {
1091                 self.backing.sign_bolt12_invoice(invoice)
1092         }
1093
1094         fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1095                 self.backing.sign_gossip_message(msg)
1096         }
1097 }
1098
1099 impl SignerProvider for TestKeysInterface {
1100         type Signer = TestChannelSigner;
1101
1102         fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1103                 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1104         }
1105
1106         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner {
1107                 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
1108                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1109                 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1110         }
1111
1112         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
1113                 let mut reader = io::Cursor::new(buffer);
1114
1115                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
1116                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
1117
1118                 Ok(TestChannelSigner::new_with_revoked(
1119                         inner,
1120                         state,
1121                         self.disable_revocation_policy_check
1122                 ))
1123         }
1124
1125         fn get_destination_script(&self) -> Result<Script, ()> { self.backing.get_destination_script() }
1126
1127         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1128                 match &mut *self.expectations.lock().unwrap() {
1129                         None => self.backing.get_shutdown_scriptpubkey(),
1130                         Some(expectations) => match expectations.pop_front() {
1131                                 None => panic!("Unexpected get_shutdown_scriptpubkey"),
1132                                 Some(expectation) => Ok(expectation.returns),
1133                         },
1134                 }
1135         }
1136 }
1137
1138 impl TestKeysInterface {
1139         pub fn new(seed: &[u8; 32], network: Network) -> Self {
1140                 let now = Duration::from_secs(genesis_block(network).header.time as u64);
1141                 Self {
1142                         backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1143                         override_random_bytes: Mutex::new(None),
1144                         disable_revocation_policy_check: false,
1145                         enforcement_states: Mutex::new(HashMap::new()),
1146                         expectations: Mutex::new(None),
1147                 }
1148         }
1149
1150         /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
1151         /// called.
1152         pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
1153                 self.expectations.lock().unwrap()
1154                         .get_or_insert_with(|| VecDeque::new())
1155                         .push_back(expectation);
1156                 self
1157         }
1158
1159         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner {
1160                 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
1161                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1162                 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1163         }
1164
1165         fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
1166                 let mut states = self.enforcement_states.lock().unwrap();
1167                 if !states.contains_key(&commitment_seed) {
1168                         let state = EnforcementState::new();
1169                         states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1170                 }
1171                 let cell = states.get(&commitment_seed).unwrap();
1172                 Arc::clone(cell)
1173         }
1174 }
1175
1176 pub(crate) fn panicking() -> bool {
1177         #[cfg(feature = "std")]
1178         let panicking = ::std::thread::panicking();
1179         #[cfg(not(feature = "std"))]
1180         let panicking = false;
1181         return panicking;
1182 }
1183
1184 impl Drop for TestKeysInterface {
1185         fn drop(&mut self) {
1186                 if panicking() {
1187                         return;
1188                 }
1189
1190                 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1191                         if !expectations.is_empty() {
1192                                 panic!("Unsatisfied expectations: {:?}", expectations);
1193                         }
1194                 }
1195         }
1196 }
1197
1198 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1199 /// returns a [`ShutdownScript`].
1200 pub struct OnGetShutdownScriptpubkey {
1201         /// A shutdown script used to close a channel.
1202         pub returns: ShutdownScript,
1203 }
1204
1205 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1206         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1207                 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1208         }
1209 }
1210
1211 pub struct TestChainSource {
1212         pub chain_hash: ChainHash,
1213         pub utxo_ret: Mutex<UtxoResult>,
1214         pub get_utxo_call_count: AtomicUsize,
1215         pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
1216         pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
1217 }
1218
1219 impl TestChainSource {
1220         pub fn new(network: Network) -> Self {
1221                 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1222                 Self {
1223                         chain_hash: ChainHash::using_genesis_block(network),
1224                         utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1225                         get_utxo_call_count: AtomicUsize::new(0),
1226                         watched_txn: Mutex::new(HashSet::new()),
1227                         watched_outputs: Mutex::new(HashSet::new()),
1228                 }
1229         }
1230 }
1231
1232 impl UtxoLookup for TestChainSource {
1233         fn get_utxo(&self, chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
1234                 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1235                 if self.chain_hash != *chain_hash {
1236                         return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1237                 }
1238
1239                 self.utxo_ret.lock().unwrap().clone()
1240         }
1241 }
1242
1243 impl chain::Filter for TestChainSource {
1244         fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1245                 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
1246         }
1247
1248         fn register_output(&self, output: WatchedOutput) {
1249                 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1250         }
1251 }
1252
1253 impl Drop for TestChainSource {
1254         fn drop(&mut self) {
1255                 if panicking() {
1256                         return;
1257                 }
1258         }
1259 }
1260
1261 pub struct TestScorer {
1262         /// Stores a tuple of (scid, ChannelUsage)
1263         scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1264 }
1265
1266 impl TestScorer {
1267         pub fn new() -> Self {
1268                 Self {
1269                         scorer_expectations: RefCell::new(None),
1270                 }
1271         }
1272
1273         pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1274                 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1275         }
1276 }
1277
1278 #[cfg(c_bindings)]
1279 impl crate::util::ser::Writeable for TestScorer {
1280         fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1281 }
1282
1283 impl ScoreLookUp for TestScorer {
1284         type ScoreParams = ();
1285         fn channel_penalty_msat(
1286                 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams
1287         ) -> u64 {
1288                 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1289                         match scorer_expectations.pop_front() {
1290                                 Some((scid, expectation)) => {
1291                                         assert_eq!(expectation, usage);
1292                                         assert_eq!(scid, short_channel_id);
1293                                 },
1294                                 None => {},
1295                         }
1296                 }
1297                 0
1298         }
1299 }
1300
1301 impl ScoreUpdate for TestScorer {
1302         fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {}
1303
1304         fn payment_path_successful(&mut self, _actual_path: &Path) {}
1305
1306         fn probe_failed(&mut self, _actual_path: &Path, _: u64) {}
1307
1308         fn probe_successful(&mut self, _actual_path: &Path) {}
1309 }
1310
1311 impl Drop for TestScorer {
1312         fn drop(&mut self) {
1313                 #[cfg(feature = "std")] {
1314                         if std::thread::panicking() {
1315                                 return;
1316                         }
1317                 }
1318
1319                 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1320                         if !scorer_expectations.is_empty() {
1321                                 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1322                         }
1323                 }
1324         }
1325 }
1326
1327 pub struct TestWalletSource {
1328         secret_key: SecretKey,
1329         utxos: RefCell<Vec<Utxo>>,
1330         secp: Secp256k1<bitcoin::secp256k1::All>,
1331 }
1332
1333 impl TestWalletSource {
1334         pub fn new(secret_key: SecretKey) -> Self {
1335                 Self {
1336                         secret_key,
1337                         utxos: RefCell::new(Vec::new()),
1338                         secp: Secp256k1::new(),
1339                 }
1340         }
1341
1342         pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1343                 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1344                 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1345                 self.utxos.borrow_mut().push(utxo.clone());
1346                 utxo.output
1347         }
1348
1349         pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1350                 let output = utxo.output.clone();
1351                 self.utxos.borrow_mut().push(utxo);
1352                 output
1353         }
1354
1355         pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1356                 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1357         }
1358 }
1359
1360 impl WalletSource for TestWalletSource {
1361         fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1362                 Ok(self.utxos.borrow().clone())
1363         }
1364
1365         fn get_change_script(&self) -> Result<Script, ()> {
1366                 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1367                 Ok(Script::new_p2pkh(&public_key.pubkey_hash()))
1368         }
1369
1370         fn sign_tx(&self, mut tx: Transaction) -> Result<Transaction, ()> {
1371                 let utxos = self.utxos.borrow();
1372                 for i in 0..tx.input.len() {
1373                         if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1374                                 let sighash = SighashCache::new(&tx)
1375                                         .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1376                                         .map_err(|_| ())?;
1377                                 let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key);
1378                                 let bitcoin_sig = bitcoin::EcdsaSig { sig, hash_ty: EcdsaSighashType::All }.to_vec();
1379                                 tx.input[i].script_sig = Builder::new()
1380                                         .push_slice(&bitcoin_sig)
1381                                         .push_slice(&self.secret_key.public_key(&self.secp).serialize())
1382                                         .into_script();
1383                         }
1384                 }
1385                 Ok(tx)
1386         }
1387 }