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