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