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