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