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