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