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