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