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