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