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