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