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