9af8d5cf2f3d92db21ab81a775ae4b1b03ad8860
[rust-lightning] / lightning / src / util / test_utils.rs
1 use chain::chaininterface;
2 use chain::chaininterface::ConfirmationTarget;
3 use chain::transaction::OutPoint;
4 use chain::keysinterface;
5 use ln::channelmonitor;
6 use ln::features::InitFeatures;
7 use ln::msgs;
8 use ln::msgs::LightningError;
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, ReadableArgs, Writer, Writeable};
14
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::script::Script;
17 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
18 use bitcoin::network::constants::Network;
19
20 use secp256k1::{SecretKey, PublicKey};
21
22 use std::time::{SystemTime, UNIX_EPOCH};
23 use std::sync::{Arc,Mutex};
24 use std::{mem};
25 use std::collections::{HashMap, HashSet};
26
27 pub struct TestVecWriter(pub Vec<u8>);
28 impl Writer for TestVecWriter {
29         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
30                 self.0.extend_from_slice(buf);
31                 Ok(())
32         }
33         fn size_hint(&mut self, size: usize) {
34                 self.0.reserve_exact(size);
35         }
36 }
37
38 pub struct TestFeeEstimator {
39         pub sat_per_kw: u64,
40 }
41 impl chaininterface::FeeEstimator for TestFeeEstimator {
42         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u64 {
43                 self.sat_per_kw
44         }
45 }
46
47 pub struct TestChannelMonitor<'a> {
48         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
49         pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64)>>,
50         pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator>,
51         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
52 }
53 impl<'a> TestChannelMonitor<'a> {
54         pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: Arc<Logger>, fee_estimator: &'a TestFeeEstimator) -> Self {
55                 Self {
56                         added_monitors: Mutex::new(Vec::new()),
57                         latest_monitor_update_id: Mutex::new(HashMap::new()),
58                         simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, fee_estimator),
59                         update_ret: Mutex::new(Ok(())),
60                 }
61         }
62 }
63 impl<'a> channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMonitor<'a> {
64         fn add_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
65                 // At every point where we get a monitor update, we should be able to send a useful monitor
66                 // to a watchtower and disk...
67                 let mut w = TestVecWriter(Vec::new());
68                 monitor.write_for_disk(&mut w).unwrap();
69                 let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
70                                 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1;
71                 assert!(new_monitor == monitor);
72                 w.0.clear();
73                 monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
74                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, monitor.get_latest_update_id()));
75                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
76                 assert!(self.simple_monitor.add_monitor(funding_txo, new_monitor).is_ok());
77                 self.update_ret.lock().unwrap().clone()
78         }
79
80         fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
81                 // Every monitor update should survive roundtrip
82                 let mut w = TestVecWriter(Vec::new());
83                 update.write(&mut w).unwrap();
84                 assert!(channelmonitor::ChannelMonitorUpdate::read(
85                                 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
86
87                 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), (funding_txo, update.update_id));
88                 assert!(self.simple_monitor.update_monitor(funding_txo, update).is_ok());
89                 // At every point where we get a monitor update, we should be able to send a useful monitor
90                 // to a watchtower and disk...
91                 let monitors = self.simple_monitor.monitors.lock().unwrap();
92                 let monitor = monitors.get(&funding_txo).unwrap();
93                 w.0.clear();
94                 monitor.write_for_disk(&mut w).unwrap();
95                 let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
96                                 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1;
97                 assert!(new_monitor == *monitor);
98                 w.0.clear();
99                 monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
100                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
101                 self.update_ret.lock().unwrap().clone()
102         }
103
104         fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
105                 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
106         }
107 }
108
109 pub struct TestBroadcaster {
110         pub txn_broadcasted: Mutex<Vec<Transaction>>,
111         pub broadcasted_txn: Mutex<HashSet<Sha256dHash>> // Temporary field while refactoring out tx duplication
112 }
113 impl chaininterface::BroadcasterInterface for TestBroadcaster {
114         fn broadcast_transaction(&self, tx: &Transaction) {
115                 {
116                         if let Some(_) = self.broadcasted_txn.lock().unwrap().get(&tx.txid()) {
117                                 // If commitment tx, HTLC-timeout or HTLC-Success, duplicate broadcast are still ok
118                                 if tx.input[0].sequence == 0xfffffffd {
119                                         return;
120                                 }
121                         }
122                 }
123                 self.broadcasted_txn.lock().unwrap().insert(tx.txid());
124                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
125         }
126 }
127
128 pub struct TestChannelMessageHandler {
129         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
130 }
131
132 impl TestChannelMessageHandler {
133         pub fn new() -> Self {
134                 TestChannelMessageHandler {
135                         pending_events: Mutex::new(Vec::new()),
136                 }
137         }
138 }
139
140 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
141         fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
142         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
143         fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
144         fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
145         fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
146         fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
147         fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
148         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
149         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
150         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
151         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
152         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
153         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
154         fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
155         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
156         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
157         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
158         fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
159         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
160 }
161
162 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
163         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
164                 let mut pending_events = self.pending_events.lock().unwrap();
165                 let mut ret = Vec::new();
166                 mem::swap(&mut ret, &mut *pending_events);
167                 ret
168         }
169 }
170
171 pub struct TestRoutingMessageHandler {}
172
173 impl TestRoutingMessageHandler {
174         pub fn new() -> Self {
175                 TestRoutingMessageHandler {}
176         }
177 }
178 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
179         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
180                 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
181         }
182         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
183                 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
184         }
185         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
186                 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
187         }
188         fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
189         fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
190                 Vec::new()
191         }
192         fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
193                 Vec::new()
194         }
195         fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
196                 true
197         }
198 }
199
200 pub struct TestLogger {
201         level: Level,
202         id: String,
203         pub lines: Mutex<HashMap<(String, String), usize>>,
204 }
205
206 impl TestLogger {
207         pub fn new() -> TestLogger {
208                 Self::with_id("".to_owned())
209         }
210         pub fn with_id(id: String) -> TestLogger {
211                 TestLogger {
212                         level: Level::Trace,
213                         id,
214                         lines: Mutex::new(HashMap::new())
215                 }
216         }
217         pub fn enable(&mut self, level: Level) {
218                 self.level = level;
219         }
220         pub fn assert_log(&self, module: String, line: String, count: usize) {
221                 let log_entries = self.lines.lock().unwrap();
222                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
223         }
224 }
225
226 impl Logger for TestLogger {
227         fn log(&self, record: &Record) {
228                 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
229                 if self.level >= record.level {
230                         println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
231                 }
232         }
233 }
234
235 pub struct TestKeysInterface {
236         backing: keysinterface::KeysManager,
237         pub override_session_priv: Mutex<Option<SecretKey>>,
238         pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
239 }
240
241 impl keysinterface::KeysInterface for TestKeysInterface {
242         type ChanKeySigner = EnforcingChannelKeys;
243
244         fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
245         fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
246         fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
247         fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
248                 EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
249         }
250
251         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
252                 match *self.override_session_priv.lock().unwrap() {
253                         Some(key) => (key.clone(), [0; 32]),
254                         None => self.backing.get_onion_rand()
255                 }
256         }
257
258         fn get_channel_id(&self) -> [u8; 32] {
259                 match *self.override_channel_id_priv.lock().unwrap() {
260                         Some(key) => key.clone(),
261                         None => self.backing.get_channel_id()
262                 }
263         }
264 }
265
266 impl TestKeysInterface {
267         pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> Self {
268                 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
269                 Self {
270                         backing: keysinterface::KeysManager::new(seed, network, logger, now.as_secs(), now.subsec_nanos()),
271                         override_session_priv: Mutex::new(None),
272                         override_channel_id_priv: Mutex::new(None),
273                 }
274         }
275 }