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