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