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