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