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