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