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::HTLCUpdate;
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
21 use util::logger::{Logger, Level, Record};
22 use util::ser::{Readable, Writer, Writeable};
24 use bitcoin::BitcoinHash;
25 use bitcoin::blockdata::constants::genesis_block;
26 use bitcoin::blockdata::transaction::Transaction;
27 use bitcoin::blockdata::script::{Builder, Script};
28 use bitcoin::blockdata::block::Block;
29 use bitcoin::blockdata::opcodes;
30 use bitcoin::network::constants::Network;
31 use bitcoin::hash_types::{Txid, BlockHash};
33 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, Signature};
37 use std::time::Duration;
39 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
41 use std::collections::HashMap;
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);
49 fn size_hint(&mut self, size: usize) {
50 self.0.reserve_exact(size);
54 pub struct TestFeeEstimator {
57 impl chaininterface::FeeEstimator for TestFeeEstimator {
58 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
63 pub struct TestChannelMonitor<'a> {
64 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
65 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
66 pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a ChainWatchInterface>,
67 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
68 // If this is set to Some(), after the next return, we'll always return this until update_ret
70 pub next_update_ret: Mutex<Option<Result<(), channelmonitor::ChannelMonitorUpdateErr>>>,
72 impl<'a> TestChannelMonitor<'a> {
73 pub fn new(chain_monitor: &'a chaininterface::ChainWatchInterface, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator) -> Self {
75 added_monitors: Mutex::new(Vec::new()),
76 latest_monitor_update_id: Mutex::new(HashMap::new()),
77 simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, fee_estimator),
78 update_ret: Mutex::new(Ok(())),
79 next_update_ret: Mutex::new(None),
83 impl<'a> channelmonitor::ManyChannelMonitor for TestChannelMonitor<'a> {
84 type Keys = EnforcingChannelKeys;
86 fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
87 // At every point where we get a monitor update, we should be able to send a useful monitor
88 // to a watchtower and disk...
89 let mut w = TestVecWriter(Vec::new());
90 monitor.write_for_disk(&mut w).unwrap();
91 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
92 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
93 assert!(new_monitor == monitor);
94 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
95 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
96 assert!(self.simple_monitor.add_monitor(funding_txo, new_monitor).is_ok());
98 let ret = self.update_ret.lock().unwrap().clone();
99 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
100 *self.update_ret.lock().unwrap() = next_ret;
105 fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
106 // Every monitor update should survive roundtrip
107 let mut w = TestVecWriter(Vec::new());
108 update.write(&mut w).unwrap();
109 assert!(channelmonitor::ChannelMonitorUpdate::read(
110 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
112 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id));
113 assert!(self.simple_monitor.update_monitor(funding_txo, update).is_ok());
114 // At every point where we get a monitor update, we should be able to send a useful monitor
115 // to a watchtower and disk...
116 let monitors = self.simple_monitor.monitors.lock().unwrap();
117 let monitor = monitors.get(&funding_txo).unwrap();
119 monitor.write_for_disk(&mut w).unwrap();
120 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
121 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
122 assert!(new_monitor == *monitor);
123 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
125 let ret = self.update_ret.lock().unwrap().clone();
126 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
127 *self.update_ret.lock().unwrap() = next_ret;
132 fn get_monitor_would_broadcast(&self, funding_txo: &OutPoint, height: u32) -> bool {
133 self.simple_monitor.get_monitor_would_broadcast(funding_txo, height)
136 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
137 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
141 pub struct TestBroadcaster {
142 pub txn_broadcasted: Mutex<Vec<Transaction>>,
144 impl chaininterface::BroadcasterInterface for TestBroadcaster {
145 fn broadcast_transaction(&self, tx: &Transaction) {
146 self.txn_broadcasted.lock().unwrap().push(tx.clone());
150 pub struct TestChannelMessageHandler {
151 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
154 impl TestChannelMessageHandler {
155 pub fn new() -> Self {
156 TestChannelMessageHandler {
157 pending_events: Mutex::new(Vec::new()),
162 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
163 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
164 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
165 fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
166 fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
167 fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
168 fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
169 fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
170 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
171 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
172 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
173 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
174 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
175 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
176 fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
177 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
178 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
179 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
180 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
181 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
184 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
185 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
186 let mut pending_events = self.pending_events.lock().unwrap();
187 let mut ret = Vec::new();
188 mem::swap(&mut ret, &mut *pending_events);
193 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
194 use bitcoin::secp256k1::ffi::Signature as FFISignature;
195 let secp_ctx = Secp256k1::new();
196 let network = Network::Testnet;
197 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
198 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
199 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
200 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
201 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
202 features: ChannelFeatures::known(),
203 chain_hash: genesis_block(network).header.bitcoin_hash(),
204 short_channel_id: short_chan_id,
205 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
206 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
207 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
208 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
209 excess_data: Vec::new(),
212 msgs::ChannelAnnouncement {
213 node_signature_1: Signature::from(FFISignature::new()),
214 node_signature_2: Signature::from(FFISignature::new()),
215 bitcoin_signature_1: Signature::from(FFISignature::new()),
216 bitcoin_signature_2: Signature::from(FFISignature::new()),
217 contents: unsigned_ann,
221 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
222 use bitcoin::secp256k1::ffi::Signature as FFISignature;
223 let network = Network::Testnet;
224 msgs::ChannelUpdate {
225 signature: Signature::from(FFISignature::new()),
226 contents: msgs::UnsignedChannelUpdate {
227 chain_hash: genesis_block(network).header.bitcoin_hash(),
228 short_channel_id: short_chan_id,
231 cltv_expiry_delta: 0,
232 htlc_minimum_msat: 0,
233 htlc_maximum_msat: OptionalField::Absent,
235 fee_proportional_millionths: 0,
241 pub struct TestRoutingMessageHandler {
242 pub chan_upds_recvd: AtomicUsize,
243 pub chan_anns_recvd: AtomicUsize,
244 pub chan_anns_sent: AtomicUsize,
245 pub request_full_sync: AtomicBool,
248 impl TestRoutingMessageHandler {
249 pub fn new() -> Self {
250 TestRoutingMessageHandler {
251 chan_upds_recvd: AtomicUsize::new(0),
252 chan_anns_recvd: AtomicUsize::new(0),
253 chan_anns_sent: AtomicUsize::new(0),
254 request_full_sync: AtomicBool::new(false),
258 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
259 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
260 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
262 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
263 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
264 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
266 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
267 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
268 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
270 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
271 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
272 let mut chan_anns = Vec::new();
273 const TOTAL_UPDS: u64 = 100;
274 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS - self.chan_anns_sent.load(Ordering::Acquire) as u64);
275 for i in starting_point..end {
276 let chan_upd_1 = get_dummy_channel_update(i);
277 let chan_upd_2 = get_dummy_channel_update(i);
278 let chan_ann = get_dummy_channel_announcement(i);
280 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
283 self.chan_anns_sent.fetch_add(chan_anns.len(), Ordering::AcqRel);
287 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
291 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
292 self.request_full_sync.load(Ordering::Acquire)
296 pub struct TestLogger {
299 pub lines: Mutex<HashMap<(String, String), usize>>,
303 pub fn new() -> TestLogger {
304 Self::with_id("".to_owned())
306 pub fn with_id(id: String) -> TestLogger {
310 lines: Mutex::new(HashMap::new())
313 pub fn enable(&mut self, level: Level) {
316 pub fn assert_log(&self, module: String, line: String, count: usize) {
317 let log_entries = self.lines.lock().unwrap();
318 assert_eq!(log_entries.get(&(module, line)), Some(&count));
321 /// Search for the number of occurrence of the logged lines which
322 /// 1. belongs to the specified module and
323 /// 2. contains `line` in it.
324 /// And asserts if the number of occurrences is the same with the given `count`
325 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
326 let log_entries = self.lines.lock().unwrap();
327 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
328 m == &module && l.contains(line.as_str())
329 }).map(|(_, c) | { c }).sum();
333 /// Search for the number of occurrences of logged lines which
334 /// 1. belong to the specified module and
335 /// 2. match the given regex pattern.
336 /// Assert that the number of occurrences equals the given `count`
337 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
338 let log_entries = self.lines.lock().unwrap();
339 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
340 m == &module && pattern.is_match(&l)
341 }).map(|(_, c) | { c }).sum();
346 impl Logger for TestLogger {
347 fn log(&self, record: &Record) {
348 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
349 if self.level >= record.level {
350 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
355 pub struct TestKeysInterface {
356 backing: keysinterface::KeysManager,
357 pub override_session_priv: Mutex<Option<SecretKey>>,
358 pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
361 impl keysinterface::KeysInterface for TestKeysInterface {
362 type ChanKeySigner = EnforcingChannelKeys;
364 fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
365 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
366 fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
367 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
368 EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
371 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
372 match *self.override_session_priv.lock().unwrap() {
373 Some(key) => (key.clone(), [0; 32]),
374 None => self.backing.get_onion_rand()
378 fn get_channel_id(&self) -> [u8; 32] {
379 match *self.override_channel_id_priv.lock().unwrap() {
380 Some(key) => key.clone(),
381 None => self.backing.get_channel_id()
386 impl TestKeysInterface {
387 pub fn new(seed: &[u8; 32], network: Network) -> Self {
388 let now = Duration::from_secs(genesis_block(network).header.time as u64);
390 backing: keysinterface::KeysManager::new(seed, network, now.as_secs(), now.subsec_nanos()),
391 override_session_priv: Mutex::new(None),
392 override_channel_id_priv: Mutex::new(None),
395 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, user_id_1: u64, user_id_2: u64) -> EnforcingChannelKeys {
396 EnforcingChannelKeys::new(self.backing.derive_channel_keys(channel_value_satoshis, user_id_1, user_id_2))
400 pub struct TestChainWatcher {
401 pub utxo_ret: Mutex<Result<(Script, u64), ChainError>>,
404 impl TestChainWatcher {
405 pub fn new() -> Self {
406 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
407 Self { utxo_ret: Mutex::new(Ok((script, u64::max_value()))) }
411 impl ChainWatchInterface for TestChainWatcher {
412 fn install_watch_tx(&self, _txid: &Txid, _script_pub_key: &Script) { }
413 fn install_watch_outpoint(&self, _outpoint: (Txid, u32), _out_script: &Script) { }
414 fn watch_all_txn(&self) { }
415 fn filter_block<'a>(&self, _block: &'a Block) -> Vec<usize> {
418 fn reentered(&self) -> usize { 0 }
420 fn get_chain_utxo(&self, _genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
421 self.utxo_ret.lock().unwrap().clone()