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