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