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