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