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