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