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::InitFeatures;
8 use ln::msgs::LightningError;
9 use ln::channelmonitor::HTLCUpdate;
10 use util::enforcing_trait_impls::EnforcingChannelKeys;
12 use util::logger::{Logger, Level, Record};
13 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::script::{Builder, Script};
17 use bitcoin::blockdata::block::Block;
18 use bitcoin::blockdata::opcodes;
19 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
20 use bitcoin::network::constants::Network;
22 use secp256k1::{SecretKey, PublicKey};
24 use std::time::{SystemTime, UNIX_EPOCH};
25 use std::sync::{Arc,Mutex};
27 use std::collections::HashMap;
29 pub struct TestVecWriter(pub Vec<u8>);
30 impl Writer for TestVecWriter {
31 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
32 self.0.extend_from_slice(buf);
35 fn size_hint(&mut self, size: usize) {
36 self.0.reserve_exact(size);
40 pub struct TestFeeEstimator {
43 impl chaininterface::FeeEstimator for TestFeeEstimator {
44 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u64 {
49 pub struct TestChannelMonitor<'a> {
50 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
51 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
52 pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator>,
53 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
55 impl<'a> TestChannelMonitor<'a> {
56 pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: Arc<Logger>, fee_estimator: &'a TestFeeEstimator) -> Self {
58 added_monitors: Mutex::new(Vec::new()),
59 latest_monitor_update_id: Mutex::new(HashMap::new()),
60 simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, fee_estimator),
61 update_ret: Mutex::new(Ok(())),
65 impl<'a> channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMonitor<'a> {
66 fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
67 // At every point where we get a monitor update, we should be able to send a useful monitor
68 // to a watchtower and disk...
69 let mut w = TestVecWriter(Vec::new());
70 monitor.write_for_disk(&mut w).unwrap();
71 let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
72 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1;
73 assert!(new_monitor == monitor);
75 monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
76 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
77 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
78 assert!(self.simple_monitor.add_monitor(funding_txo, new_monitor).is_ok());
79 self.update_ret.lock().unwrap().clone()
82 fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
83 // Every monitor update should survive roundtrip
84 let mut w = TestVecWriter(Vec::new());
85 update.write(&mut w).unwrap();
86 assert!(channelmonitor::ChannelMonitorUpdate::read(
87 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
89 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id));
90 assert!(self.simple_monitor.update_monitor(funding_txo, update).is_ok());
91 // At every point where we get a monitor update, we should be able to send a useful monitor
92 // to a watchtower and disk...
93 let monitors = self.simple_monitor.monitors.lock().unwrap();
94 let monitor = monitors.get(&funding_txo).unwrap();
96 monitor.write_for_disk(&mut w).unwrap();
97 let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
98 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1;
99 assert!(new_monitor == *monitor);
101 monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
102 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
103 self.update_ret.lock().unwrap().clone()
106 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
107 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
111 pub struct TestBroadcaster {
112 pub txn_broadcasted: Mutex<Vec<Transaction>>,
113 pub broadcasted_txn: Mutex<HashMap<Sha256dHash, u8>> // Temporary field while refactoring out tx duplication
115 impl chaininterface::BroadcasterInterface for TestBroadcaster {
116 fn broadcast_transaction(&self, tx: &Transaction) {
117 let mut already = false;
119 if let Some(counter) = self.broadcasted_txn.lock().unwrap().get_mut(&tx.txid()) {
121 0 => { *counter = 1; already = true }, // We still authorize at least 2 duplicata for a given TXID to account ChannelManager/ChannelMonitor broadcast
128 self.broadcasted_txn.lock().unwrap().insert(tx.txid(), 0);
130 print!("\nFRESH BROADCAST {}\n\n", tx.txid());
131 self.txn_broadcasted.lock().unwrap().push(tx.clone());
135 pub struct TestChannelMessageHandler {
136 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
139 impl TestChannelMessageHandler {
140 pub fn new() -> Self {
141 TestChannelMessageHandler {
142 pending_events: Mutex::new(Vec::new()),
147 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
148 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
149 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
150 fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
151 fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
152 fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
153 fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
154 fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
155 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
156 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
157 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
158 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
159 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
160 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
161 fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
162 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
163 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
164 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
165 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
166 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
169 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
170 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
171 let mut pending_events = self.pending_events.lock().unwrap();
172 let mut ret = Vec::new();
173 mem::swap(&mut ret, &mut *pending_events);
178 pub struct TestRoutingMessageHandler {}
180 impl TestRoutingMessageHandler {
181 pub fn new() -> Self {
182 TestRoutingMessageHandler {}
185 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
186 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
187 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
189 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
190 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
192 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
193 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
195 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
196 fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
199 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
202 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
207 pub struct TestLogger {
210 pub lines: Mutex<HashMap<(String, String), usize>>,
214 pub fn new() -> TestLogger {
215 Self::with_id("".to_owned())
217 pub fn with_id(id: String) -> TestLogger {
221 lines: Mutex::new(HashMap::new())
224 pub fn enable(&mut self, level: Level) {
227 pub fn assert_log(&self, module: String, line: String, count: usize) {
228 let log_entries = self.lines.lock().unwrap();
229 assert_eq!(log_entries.get(&(module, line)), Some(&count));
233 impl Logger for TestLogger {
234 fn log(&self, record: &Record) {
235 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
236 if self.level >= record.level {
237 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
242 pub struct TestKeysInterface {
243 backing: keysinterface::KeysManager,
244 pub override_session_priv: Mutex<Option<SecretKey>>,
245 pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
248 impl keysinterface::KeysInterface for TestKeysInterface {
249 type ChanKeySigner = EnforcingChannelKeys;
251 fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
252 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
253 fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
254 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
255 EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
258 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
259 match *self.override_session_priv.lock().unwrap() {
260 Some(key) => (key.clone(), [0; 32]),
261 None => self.backing.get_onion_rand()
265 fn get_channel_id(&self) -> [u8; 32] {
266 match *self.override_channel_id_priv.lock().unwrap() {
267 Some(key) => key.clone(),
268 None => self.backing.get_channel_id()
273 impl TestKeysInterface {
274 pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> Self {
275 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
277 backing: keysinterface::KeysManager::new(seed, network, logger, now.as_secs(), now.subsec_nanos()),
278 override_session_priv: Mutex::new(None),
279 override_channel_id_priv: Mutex::new(None),
284 pub struct TestChainWatcher {
285 pub utxo_ret: Mutex<Result<(Script, u64), ChainError>>,
288 impl TestChainWatcher {
289 pub fn new() -> Self {
290 let script = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
291 Self { utxo_ret: Mutex::new(Ok((script, u64::max_value()))) }
295 impl ChainWatchInterface for TestChainWatcher {
296 fn install_watch_tx(&self, _txid: &Sha256dHash, _script_pub_key: &Script) { }
297 fn install_watch_outpoint(&self, _outpoint: (Sha256dHash, u32), _out_script: &Script) { }
298 fn watch_all_txn(&self) { }
299 fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
300 (Vec::new(), Vec::new())
302 fn reentered(&self) -> usize { 0 }
304 fn get_chain_utxo(&self, _genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
305 self.utxo_ret.lock().unwrap().clone()