1 // This file is Copyright its original authors, visible in version control
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
10 use chain::chaininterface;
11 use chain::chaininterface::{ConfirmationTarget, ChainError, ChainWatchInterface};
12 use chain::transaction::OutPoint;
13 use chain::keysinterface;
14 use ln::channelmonitor;
15 use ln::features::{ChannelFeatures, InitFeatures};
17 use ln::msgs::OptionalField;
18 use ln::channelmonitor::MonitorEvent;
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
21 use util::logger::{Logger, Level, Record};
22 use util::ser::{Readable, Writer, Writeable};
24 use bitcoin::blockdata::constants::genesis_block;
25 use bitcoin::blockdata::transaction::Transaction;
26 use bitcoin::blockdata::script::{Builder, Script};
27 use bitcoin::blockdata::block::Block;
28 use bitcoin::blockdata::opcodes;
29 use bitcoin::network::constants::Network;
30 use bitcoin::hash_types::{Txid, BlockHash};
32 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
36 use std::time::Duration;
38 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
40 use std::collections::HashMap;
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);
48 fn size_hint(&mut self, size: usize) {
49 self.0.reserve_exact(size);
53 pub struct TestFeeEstimator {
56 impl chaininterface::FeeEstimator for TestFeeEstimator {
57 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
62 pub struct TestChannelMonitor<'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 simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a ChainWatchInterface>,
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
69 pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
71 impl<'a> TestChannelMonitor<'a> {
72 pub fn new(chain_monitor: &'a chaininterface::ChainWatchInterface, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator) -> Self {
74 added_monitors: Mutex::new(Vec::new()),
75 latest_monitor_update_id: Mutex::new(HashMap::new()),
76 simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, fee_estimator),
77 update_ret: Mutex::new(Ok(())),
78 next_update_ret: Mutex::new(None),
82 impl<'a> channelmonitor::ManyChannelMonitor for TestChannelMonitor<'a> {
83 type Keys = EnforcingChannelKeys;
85 fn add_monitor(&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.simple_monitor.add_monitor(funding_txo, new_monitor).is_ok());
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;
104 fn update_monitor(&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);
111 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id));
112 assert!(self.simple_monitor.update_monitor(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.simple_monitor.monitors.lock().unwrap();
116 let monitor = monitors.get(&funding_txo).unwrap();
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));
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;
131 fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
132 return self.simple_monitor.get_and_clear_pending_monitor_events();
136 pub struct TestBroadcaster {
137 pub txn_broadcasted: Mutex<Vec<Transaction>>,
139 impl chaininterface::BroadcasterInterface for TestBroadcaster {
140 fn broadcast_transaction(&self, tx: &Transaction) {
141 self.txn_broadcasted.lock().unwrap().push(tx.clone());
145 pub struct TestChannelMessageHandler {
146 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
149 impl TestChannelMessageHandler {
150 pub fn new() -> Self {
151 TestChannelMessageHandler {
152 pending_events: Mutex::new(Vec::new()),
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) {}
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);
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(),
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,
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,
226 cltv_expiry_delta: 0,
227 htlc_minimum_msat: 0,
228 htlc_maximum_msat: OptionalField::Absent,
230 fee_proportional_millionths: 0,
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,
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),
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 })
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 })
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 })
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);
275 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
278 self.chan_anns_sent.fetch_add(chan_anns.len(), Ordering::AcqRel);
282 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
286 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
287 self.request_full_sync.load(Ordering::Acquire)
291 pub struct TestLogger {
294 pub lines: Mutex<HashMap<(String, String), usize>>,
298 pub fn new() -> TestLogger {
299 Self::with_id("".to_owned())
301 pub fn with_id(id: String) -> TestLogger {
305 lines: Mutex::new(HashMap::new())
308 pub fn enable(&mut self, level: Level) {
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));
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();
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();
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);
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]>>,
356 impl keysinterface::KeysInterface for TestKeysInterface {
357 type ChanKeySigner = EnforcingChannelKeys;
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))
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!");
372 if let Some(key) = &*override_channel_id {
375 if let Some(key) = &*override_session_key {
378 self.backing.get_secure_random_bytes()
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);
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),
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))
396 pub struct TestChainWatcher {
397 pub utxo_ret: Mutex<Result<(Script, u64), ChainError>>,
400 impl TestChainWatcher {
401 pub fn new() -> Self {
402 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
403 Self { utxo_ret: Mutex::new(Ok((script, u64::max_value()))) }
407 impl ChainWatchInterface for TestChainWatcher {
408 fn install_watch_tx(&self, _txid: &Txid, _script_pub_key: &Script) { }
409 fn install_watch_outpoint(&self, _outpoint: (Txid, u32), _out_script: &Script) { }
410 fn watch_all_txn(&self) { }
411 fn filter_block<'a>(&self, _block: &'a Block) -> Vec<usize> {
414 fn reentered(&self) -> usize { 0 }
416 fn get_chain_utxo(&self, _genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
417 self.utxo_ret.lock().unwrap().clone()