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