Give ManyChannelMonitor a logger and trace add_update events
[rust-lightning] / src / util / test_utils.rs
1 use chain::chaininterface;
2 use chain::chaininterface::ConfirmationTarget;
3 use chain::transaction::OutPoint;
4 use ln::channelmonitor;
5 use ln::msgs;
6 use ln::msgs::{HandleError};
7 use util::events;
8 use util::logger::{Logger, Level, Record};
9 use util::ser::{ReadableArgs, Writer};
10
11 use bitcoin::blockdata::transaction::Transaction;
12 use bitcoin::util::hash::Sha256dHash;
13
14 use secp256k1::PublicKey;
15
16 use std::sync::{Arc,Mutex};
17 use std::{mem};
18
19 struct VecWriter(Vec<u8>);
20 impl Writer for VecWriter {
21         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
22                 self.0.extend_from_slice(buf);
23                 Ok(())
24         }
25         fn size_hint(&mut self, size: usize) {
26                 self.0.reserve_exact(size);
27         }
28 }
29
30 pub struct TestFeeEstimator {
31         pub sat_per_kw: u64,
32 }
33 impl chaininterface::FeeEstimator for TestFeeEstimator {
34         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u64 {
35                 self.sat_per_kw
36         }
37 }
38
39 pub struct TestChannelMonitor {
40         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor)>>,
41         pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
42         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
43 }
44 impl TestChannelMonitor {
45         pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: Arc<chaininterface::BroadcasterInterface>, logger: Arc<Logger>) -> Self {
46                 Self {
47                         added_monitors: Mutex::new(Vec::new()),
48                         simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger),
49                         update_ret: Mutex::new(Ok(())),
50                 }
51         }
52 }
53 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
54         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
55                 // At every point where we get a monitor update, we should be able to send a useful monitor
56                 // to a watchtower and disk...
57                 let mut w = VecWriter(Vec::new());
58                 monitor.write_for_disk(&mut w).unwrap();
59                 assert!(<(Sha256dHash, channelmonitor::ChannelMonitor)>::read(
60                                 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1 == monitor);
61                 w.0.clear();
62                 monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
63                 self.added_monitors.lock().unwrap().push((funding_txo, monitor.clone()));
64                 assert!(self.simple_monitor.add_update_monitor(funding_txo, monitor).is_ok());
65                 self.update_ret.lock().unwrap().clone()
66         }
67 }
68
69 pub struct TestBroadcaster {
70         pub txn_broadcasted: Mutex<Vec<Transaction>>,
71 }
72 impl chaininterface::BroadcasterInterface for TestBroadcaster {
73         fn broadcast_transaction(&self, tx: &Transaction) {
74                 self.txn_broadcasted.lock().unwrap().push(tx.clone());
75         }
76 }
77
78 pub struct TestChannelMessageHandler {
79         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
80 }
81
82 impl TestChannelMessageHandler {
83         pub fn new() -> Self {
84                 TestChannelMessageHandler {
85                         pending_events: Mutex::new(Vec::new()),
86                 }
87         }
88 }
89
90 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
91         fn handle_open_channel(&self, _their_node_id: &PublicKey, _msg: &msgs::OpenChannel) -> Result<(), HandleError> {
92                 Err(HandleError { err: "", action: None })
93         }
94         fn handle_accept_channel(&self, _their_node_id: &PublicKey, _msg: &msgs::AcceptChannel) -> Result<(), HandleError> {
95                 Err(HandleError { err: "", action: None })
96         }
97         fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) -> Result<(), HandleError> {
98                 Err(HandleError { err: "", action: None })
99         }
100         fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) -> Result<(), HandleError> {
101                 Err(HandleError { err: "", action: None })
102         }
103         fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) -> Result<(), HandleError> {
104                 Err(HandleError { err: "", action: None })
105         }
106         fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) -> Result<(), HandleError> {
107                 Err(HandleError { err: "", action: None })
108         }
109         fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) -> Result<(), HandleError> {
110                 Err(HandleError { err: "", action: None })
111         }
112         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) -> Result<(), HandleError> {
113                 Err(HandleError { err: "", action: None })
114         }
115         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) -> Result<(), HandleError> {
116                 Err(HandleError { err: "", action: None })
117         }
118         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) -> Result<(), HandleError> {
119                 Err(HandleError { err: "", action: None })
120         }
121         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), HandleError> {
122                 Err(HandleError { err: "", action: None })
123         }
124         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) -> Result<(), HandleError> {
125                 Err(HandleError { err: "", action: None })
126         }
127         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) -> Result<(), HandleError> {
128                 Err(HandleError { err: "", action: None })
129         }
130         fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) -> Result<(), HandleError> {
131                 Err(HandleError { err: "", action: None })
132         }
133         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) -> Result<(), HandleError> {
134                 Err(HandleError { err: "", action: None })
135         }
136         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) -> Result<(), HandleError> {
137                 Err(HandleError { err: "", action: None })
138         }
139         fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
140         fn peer_connected(&self, _their_node_id: &PublicKey) {}
141         fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
142 }
143
144 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
145         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
146                 let mut pending_events = self.pending_events.lock().unwrap();
147                 let mut ret = Vec::new();
148                 mem::swap(&mut ret, &mut *pending_events);
149                 ret
150         }
151 }
152
153 pub struct TestRoutingMessageHandler {}
154
155 impl TestRoutingMessageHandler {
156         pub fn new() -> Self {
157                 TestRoutingMessageHandler {}
158         }
159 }
160
161 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
162         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, HandleError> {
163                 Err(HandleError { err: "", action: None })
164         }
165         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, HandleError> {
166                 Err(HandleError { err: "", action: None })
167         }
168         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, HandleError> {
169                 Err(HandleError { err: "", action: None })
170         }
171         fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
172 }
173
174 pub struct TestLogger {
175         level: Level,
176 }
177
178 impl TestLogger {
179         pub fn new() -> TestLogger {
180                 TestLogger {
181                         level: Level::Trace,
182                 }
183         }
184         pub fn enable(&mut self, level: Level) {
185                 self.level = level;
186         }
187 }
188
189 impl Logger for TestLogger {
190         fn log(&self, record: &Record) {
191                 if self.level >= record.level {
192                         println!("{:<5} [{} : {}, {}] {}", record.level.to_string(), record.module_path, record.file, record.line, record.args);
193                 }
194         }
195 }