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