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;
8 use ln::msgs::LightningError;
9 use ln::channelmonitor::HTLCUpdate;
10 use util::enforcing_trait_impls::EnforcingChannelKeys;
12 use util::logger::{Logger, Level, Record};
13 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
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;
20 use secp256k1::{SecretKey, PublicKey};
22 use std::time::{SystemTime, UNIX_EPOCH};
23 use std::sync::{Arc,Mutex};
25 use std::collections::{HashMap, HashSet};
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);
33 fn size_hint(&mut self, size: usize) {
34 self.0.reserve_exact(size);
38 pub struct TestFeeEstimator {
41 impl chaininterface::FeeEstimator for TestFeeEstimator {
42 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u64 {
47 pub struct TestChannelMonitor<'a> {
48 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>>,
49 pub simple_monitor: channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, &'a chaininterface::BroadcasterInterface>,
50 pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
52 impl<'a> TestChannelMonitor<'a> {
53 pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: Arc<Logger>, fee_estimator: Arc<chaininterface::FeeEstimator>) -> 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(())),
61 impl<'a> channelmonitor::ManyChannelMonitor<EnforcingChannelKeys> for TestChannelMonitor<'a> {
62 fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingChannelKeys>) -> 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<EnforcingChannelKeys>)>::read(
68 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1 == monitor);
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()
76 fn update_monitor(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
77 // Every monitor update should survive roundtrip
78 let mut w = TestVecWriter(Vec::new());
79 update.write(&mut w).unwrap();
80 assert!(channelmonitor::ChannelMonitorUpdate::read(
81 &mut ::std::io::Cursor::new(&w.0)).unwrap() == update);
83 assert!(self.simple_monitor.update_monitor(funding_txo, update).is_ok());
84 // At every point where we get a monitor update, we should be able to send a useful monitor
85 // to a watchtower and disk...
86 let monitors = self.simple_monitor.monitors.lock().unwrap();
87 let monitor = monitors.get(&funding_txo).unwrap();
89 monitor.write_for_disk(&mut w).unwrap();
90 assert!(<(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
91 &mut ::std::io::Cursor::new(&w.0), Arc::new(TestLogger::new())).unwrap().1 == *monitor);
93 monitor.write_for_watchtower(&mut w).unwrap(); // This at least shouldn't crash...
94 self.added_monitors.lock().unwrap().push((funding_txo, monitor.clone()));
95 self.update_ret.lock().unwrap().clone()
98 fn get_and_clear_pending_htlcs_updated(&self) -> Vec<HTLCUpdate> {
99 return self.simple_monitor.get_and_clear_pending_htlcs_updated();
103 pub struct TestBroadcaster {
104 pub txn_broadcasted: Mutex<Vec<Transaction>>,
105 pub broadcasted_txn: Mutex<HashSet<Sha256dHash>> // Temporary field while refactoring out tx duplication
107 impl chaininterface::BroadcasterInterface for TestBroadcaster {
108 fn broadcast_transaction(&self, tx: &Transaction) {
110 if let Some(_) = self.broadcasted_txn.lock().unwrap().get(&tx.txid()) {
111 // If commitment tx, HTLC-timeout or HTLC-Success, duplicate broadcast are still ok
112 if tx.input[0].sequence == 0xfffffffd {
117 self.broadcasted_txn.lock().unwrap().insert(tx.txid());
118 self.txn_broadcasted.lock().unwrap().push(tx.clone());
122 pub struct TestChannelMessageHandler {
123 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
126 impl TestChannelMessageHandler {
127 pub fn new() -> Self {
128 TestChannelMessageHandler {
129 pending_events: Mutex::new(Vec::new()),
134 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
135 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::OpenChannel) {}
136 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, _msg: &msgs::AcceptChannel) {}
137 fn handle_funding_created(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingCreated) {}
138 fn handle_funding_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingSigned) {}
139 fn handle_funding_locked(&self, _their_node_id: &PublicKey, _msg: &msgs::FundingLocked) {}
140 fn handle_shutdown(&self, _their_node_id: &PublicKey, _msg: &msgs::Shutdown) {}
141 fn handle_closing_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::ClosingSigned) {}
142 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateAddHTLC) {}
143 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFulfillHTLC) {}
144 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailHTLC) {}
145 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFailMalformedHTLC) {}
146 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, _msg: &msgs::CommitmentSigned) {}
147 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, _msg: &msgs::RevokeAndACK) {}
148 fn handle_update_fee(&self, _their_node_id: &PublicKey, _msg: &msgs::UpdateFee) {}
149 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, _msg: &msgs::AnnouncementSignatures) {}
150 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelReestablish) {}
151 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
152 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
153 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
156 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
157 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
158 let mut pending_events = self.pending_events.lock().unwrap();
159 let mut ret = Vec::new();
160 mem::swap(&mut ret, &mut *pending_events);
165 pub struct TestRoutingMessageHandler {}
167 impl TestRoutingMessageHandler {
168 pub fn new() -> Self {
169 TestRoutingMessageHandler {}
172 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
173 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> {
174 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
176 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> {
177 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
179 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> {
180 Err(LightningError { err: "", action: msgs::ErrorAction::IgnoreError })
182 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
183 fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, msgs::ChannelUpdate,msgs::ChannelUpdate)> {
186 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
189 fn should_request_full_sync(&self, _node_id: &PublicKey) -> bool {
194 pub struct TestLogger {
197 pub lines: Mutex<HashMap<(String, String), usize>>,
201 pub fn new() -> TestLogger {
202 Self::with_id("".to_owned())
204 pub fn with_id(id: String) -> TestLogger {
208 lines: Mutex::new(HashMap::new())
211 pub fn enable(&mut self, level: Level) {
214 pub fn assert_log(&self, module: String, line: String, count: usize) {
215 let log_entries = self.lines.lock().unwrap();
216 assert_eq!(log_entries.get(&(module, line)), Some(&count));
220 impl Logger for TestLogger {
221 fn log(&self, record: &Record) {
222 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
223 if self.level >= record.level {
224 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
229 pub struct TestKeysInterface {
230 backing: keysinterface::KeysManager,
231 pub override_session_priv: Mutex<Option<SecretKey>>,
232 pub override_channel_id_priv: Mutex<Option<[u8; 32]>>,
235 impl keysinterface::KeysInterface for TestKeysInterface {
236 type ChanKeySigner = EnforcingChannelKeys;
238 fn get_node_secret(&self) -> SecretKey { self.backing.get_node_secret() }
239 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
240 fn get_shutdown_pubkey(&self) -> PublicKey { self.backing.get_shutdown_pubkey() }
241 fn get_channel_keys(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingChannelKeys {
242 EnforcingChannelKeys::new(self.backing.get_channel_keys(inbound, channel_value_satoshis))
245 fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
246 match *self.override_session_priv.lock().unwrap() {
247 Some(key) => (key.clone(), [0; 32]),
248 None => self.backing.get_onion_rand()
252 fn get_channel_id(&self) -> [u8; 32] {
253 match *self.override_channel_id_priv.lock().unwrap() {
254 Some(key) => key.clone(),
255 None => self.backing.get_channel_id()
260 impl TestKeysInterface {
261 pub fn new(seed: &[u8; 32], network: Network, logger: Arc<Logger>) -> Self {
262 let now = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards");
264 backing: keysinterface::KeysManager::new(seed, network, logger, now.as_secs(), now.subsec_nanos()),
265 override_session_priv: Mutex::new(None),
266 override_channel_id_priv: Mutex::new(None),