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