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