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