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