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