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