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