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