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