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