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