1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
11 use chain::WatchedOutput;
12 use chain::chaininterface;
13 use chain::chaininterface::ConfirmationTarget;
14 use chain::chainmonitor;
15 use chain::chainmonitor::MonitorUpdateId;
16 use chain::channelmonitor;
17 use chain::channelmonitor::MonitorEvent;
18 use chain::transaction::OutPoint;
19 use chain::keysinterface;
20 use ln::features::{ChannelFeatures, InitFeatures};
22 use ln::script::ShutdownScript;
23 use routing::scoring::FixedPenaltyScorer;
24 use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
26 use util::logger::{Logger, Level, Record};
27 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
29 use bitcoin::blockdata::constants::genesis_block;
30 use bitcoin::blockdata::transaction::{Transaction, TxOut};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::block::Block;
34 use bitcoin::network::constants::Network;
35 use bitcoin::hash_types::{BlockHash, Txid};
37 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature};
38 use bitcoin::secp256k1::ecdh::SharedSecret;
39 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
45 use core::time::Duration;
46 use sync::{Mutex, Arc};
47 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
49 use bitcoin::bech32::u5;
50 use chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial};
52 #[cfg(feature = "std")]
53 use std::time::{SystemTime, UNIX_EPOCH};
55 pub struct TestVecWriter(pub Vec<u8>);
56 impl Writer for TestVecWriter {
57 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
58 self.0.extend_from_slice(buf);
63 pub struct TestFeeEstimator {
64 pub sat_per_kw: Mutex<u32>,
66 impl chaininterface::FeeEstimator for TestFeeEstimator {
67 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
68 *self.sat_per_kw.lock().unwrap()
72 pub struct OnlyReadsKeysInterface {}
73 impl keysinterface::KeysInterface for OnlyReadsKeysInterface {
74 type Signer = EnforcingSigner;
76 fn get_node_secret(&self, _recipient: Recipient) -> Result<SecretKey, ()> { unreachable!(); }
77 fn ecdh(&self, _recipient: Recipient, _other_key: &PublicKey, _tweak: Option<&[u8; 32]>) -> Result<SharedSecret, ()> { unreachable!(); }
78 fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
79 fn get_destination_script(&self) -> Script { unreachable!(); }
80 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
81 fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
82 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
84 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
85 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
86 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
87 let state = Arc::new(Mutex::new(EnforcementState::new()));
89 Ok(EnforcingSigner::new_with_revoked(
95 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> { unreachable!(); }
98 pub struct TestChainMonitor<'a> {
99 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
100 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
101 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
102 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
103 pub keys_manager: &'a TestKeysInterface,
104 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
105 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
107 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
109 impl<'a> TestChainMonitor<'a> {
110 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
112 added_monitors: Mutex::new(Vec::new()),
113 monitor_updates: Mutex::new(HashMap::new()),
114 latest_monitor_update_id: Mutex::new(HashMap::new()),
115 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
117 expect_channel_force_closed: Mutex::new(None),
121 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
122 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
123 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
126 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
127 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
128 // At every point where we get a monitor update, we should be able to send a useful monitor
129 // to a watchtower and disk...
130 let mut w = TestVecWriter(Vec::new());
131 monitor.write(&mut w).unwrap();
132 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
133 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
134 assert!(new_monitor == monitor);
135 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
136 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
137 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
138 self.chain_monitor.watch_channel(funding_txo, new_monitor)
141 fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
142 // Every monitor update should survive roundtrip
143 let mut w = TestVecWriter(Vec::new());
144 update.write(&mut w).unwrap();
145 assert!(channelmonitor::ChannelMonitorUpdate::read(
146 &mut io::Cursor::new(&w.0)).unwrap() == update);
148 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
150 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
151 assert_eq!(funding_txo.to_channel_id(), exp.0);
152 assert_eq!(update.updates.len(), 1);
153 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
154 assert_eq!(should_broadcast, exp.1);
158 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
159 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
160 let update_res = self.chain_monitor.update_channel(funding_txo, update);
161 // At every point where we get a monitor update, we should be able to send a useful monitor
162 // to a watchtower and disk...
163 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
165 monitor.write(&mut w).unwrap();
166 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
167 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
168 assert!(new_monitor == *monitor);
169 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
173 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
174 return self.chain_monitor.release_pending_monitor_events();
178 pub struct TestPersister {
179 pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
180 /// If this is set to Some(), after the next return, we'll always return this until update_ret
182 pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
183 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
184 /// MonitorUpdateId here.
185 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
186 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
187 /// MonitorUpdateId here.
188 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
191 pub fn new() -> Self {
193 update_ret: Mutex::new(Ok(())),
194 next_update_ret: Mutex::new(None),
195 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
196 offchain_monitor_updates: Mutex::new(HashMap::new()),
200 pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
201 *self.update_ret.lock().unwrap() = ret;
204 pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
205 *self.next_update_ret.lock().unwrap() = next_ret;
208 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
209 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
210 let ret = self.update_ret.lock().unwrap().clone();
211 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
212 *self.update_ret.lock().unwrap() = next_ret;
217 fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
218 let ret = self.update_ret.lock().unwrap().clone();
219 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
220 *self.update_ret.lock().unwrap() = next_ret;
222 if update.is_none() {
223 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
225 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
231 pub struct TestBroadcaster {
232 pub txn_broadcasted: Mutex<Vec<Transaction>>,
233 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
236 impl TestBroadcaster {
237 pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
238 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
242 impl chaininterface::BroadcasterInterface for TestBroadcaster {
243 fn broadcast_transaction(&self, tx: &Transaction) {
244 assert!(tx.lock_time < 1_500_000_000);
245 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
246 for inp in tx.input.iter() {
247 if inp.sequence != 0xffffffff {
248 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
252 self.txn_broadcasted.lock().unwrap().push(tx.clone());
256 pub struct TestChannelMessageHandler {
257 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
258 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
261 impl TestChannelMessageHandler {
262 pub fn new() -> Self {
263 TestChannelMessageHandler {
264 pending_events: Mutex::new(Vec::new()),
265 expected_recv_msgs: Mutex::new(None),
270 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
271 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
272 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
273 expected_msgs.as_mut().unwrap().push(ev);
276 fn received_msg(&self, _ev: wire::Message<()>) {
277 let mut msgs = self.expected_recv_msgs.lock().unwrap();
278 if msgs.is_none() { return; }
279 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
281 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
282 msgs.as_mut().unwrap().remove(0);
286 impl Drop for TestChannelMessageHandler {
288 let l = self.expected_recv_msgs.lock().unwrap();
289 #[cfg(feature = "std")]
291 if !std::thread::panicking() {
292 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
298 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
299 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
300 self.received_msg(wire::Message::OpenChannel(msg.clone()));
302 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
303 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
305 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
306 self.received_msg(wire::Message::FundingCreated(msg.clone()));
308 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
309 self.received_msg(wire::Message::FundingSigned(msg.clone()));
311 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
312 self.received_msg(wire::Message::ChannelReady(msg.clone()));
314 fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
315 self.received_msg(wire::Message::Shutdown(msg.clone()));
317 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
318 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
320 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
321 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
323 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
324 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
326 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
327 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
329 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
330 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
332 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
333 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
335 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
336 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
338 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
339 self.received_msg(wire::Message::UpdateFee(msg.clone()));
341 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
342 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
344 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
345 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
347 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
348 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
350 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
351 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {
352 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
353 // bother re-generating the expected Init message in all tests.
355 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
356 self.received_msg(wire::Message::Error(msg.clone()));
360 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
361 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
362 let mut pending_events = self.pending_events.lock().unwrap();
363 let mut ret = Vec::new();
364 mem::swap(&mut ret, &mut *pending_events);
369 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
370 use bitcoin::secp256k1::ffi::Signature as FFISignature;
371 let secp_ctx = Secp256k1::new();
372 let network = Network::Testnet;
373 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
374 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
375 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
376 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
377 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
378 features: ChannelFeatures::known(),
379 chain_hash: genesis_block(network).header.block_hash(),
380 short_channel_id: short_chan_id,
381 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
382 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
383 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
384 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
385 excess_data: Vec::new(),
389 msgs::ChannelAnnouncement {
390 node_signature_1: Signature::from(FFISignature::new()),
391 node_signature_2: Signature::from(FFISignature::new()),
392 bitcoin_signature_1: Signature::from(FFISignature::new()),
393 bitcoin_signature_2: Signature::from(FFISignature::new()),
394 contents: unsigned_ann,
399 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
400 use bitcoin::secp256k1::ffi::Signature as FFISignature;
401 let network = Network::Testnet;
402 msgs::ChannelUpdate {
403 signature: Signature::from(unsafe { FFISignature::new() }),
404 contents: msgs::UnsignedChannelUpdate {
405 chain_hash: genesis_block(network).header.block_hash(),
406 short_channel_id: short_chan_id,
409 cltv_expiry_delta: 0,
410 htlc_minimum_msat: 0,
411 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
413 fee_proportional_millionths: 0,
419 pub struct TestRoutingMessageHandler {
420 pub chan_upds_recvd: AtomicUsize,
421 pub chan_anns_recvd: AtomicUsize,
422 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
423 pub request_full_sync: AtomicBool,
426 impl TestRoutingMessageHandler {
427 pub fn new() -> Self {
428 TestRoutingMessageHandler {
429 chan_upds_recvd: AtomicUsize::new(0),
430 chan_anns_recvd: AtomicUsize::new(0),
431 pending_events: Mutex::new(vec![]),
432 request_full_sync: AtomicBool::new(false),
436 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
437 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
438 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
440 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
441 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
442 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
444 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
445 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
446 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
448 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
449 let mut chan_anns = Vec::new();
450 const TOTAL_UPDS: u64 = 50;
451 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS);
452 for i in starting_point..end {
453 let chan_upd_1 = get_dummy_channel_update(i);
454 let chan_upd_2 = get_dummy_channel_update(i);
455 let chan_ann = get_dummy_channel_announcement(i);
457 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
463 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
467 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) {
468 if !init_msg.features.supports_gossip_queries() {
472 let should_request_full_sync = self.request_full_sync.load(Ordering::Acquire);
474 #[allow(unused_mut, unused_assignments)]
475 let mut gossip_start_time = 0;
476 #[cfg(feature = "std")]
478 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
479 if should_request_full_sync {
480 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
482 gossip_start_time -= 60 * 60; // an hour ago
486 let mut pending_events = self.pending_events.lock().unwrap();
487 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
488 node_id: their_node_id.clone(),
489 msg: msgs::GossipTimestampFilter {
490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
491 first_timestamp: gossip_start_time as u32,
492 timestamp_range: u32::max_value(),
497 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
501 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
505 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
509 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
514 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
515 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
516 let mut ret = Vec::new();
517 let mut pending_events = self.pending_events.lock().unwrap();
518 core::mem::swap(&mut ret, &mut pending_events);
523 pub struct TestLogger {
525 #[cfg(feature = "std")]
527 #[cfg(not(feature = "std"))]
529 pub lines: Mutex<HashMap<(String, String), usize>>,
533 pub fn new() -> TestLogger {
534 Self::with_id("".to_owned())
536 pub fn with_id(id: String) -> TestLogger {
539 #[cfg(feature = "std")]
541 #[cfg(not(feature = "std"))]
543 lines: Mutex::new(HashMap::new())
546 pub fn enable(&mut self, level: Level) {
549 pub fn assert_log(&self, module: String, line: String, count: usize) {
550 let log_entries = self.lines.lock().unwrap();
551 assert_eq!(log_entries.get(&(module, line)), Some(&count));
554 /// Search for the number of occurrence of the logged lines which
555 /// 1. belongs to the specified module and
556 /// 2. contains `line` in it.
557 /// And asserts if the number of occurrences is the same with the given `count`
558 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
559 let log_entries = self.lines.lock().unwrap();
560 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
561 m == &module && l.contains(line.as_str())
562 }).map(|(_, c) | { c }).sum();
566 /// Search for the number of occurrences of logged lines which
567 /// 1. belong to the specified module and
568 /// 2. match the given regex pattern.
569 /// Assert that the number of occurrences equals the given `count`
570 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
571 let log_entries = self.lines.lock().unwrap();
572 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
573 m == &module && pattern.is_match(&l)
574 }).map(|(_, c) | { c }).sum();
579 impl Logger for TestLogger {
580 fn log(&self, record: &Record) {
581 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
582 if record.level >= self.level {
583 #[cfg(feature = "std")]
584 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
589 pub struct TestKeysInterface {
590 pub backing: keysinterface::PhantomKeysManager,
591 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
592 pub disable_revocation_policy_check: bool,
593 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
594 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
597 impl keysinterface::KeysInterface for TestKeysInterface {
598 type Signer = EnforcingSigner;
600 fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
601 self.backing.get_node_secret(recipient)
603 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&[u8; 32]>) -> Result<SharedSecret, ()> {
604 self.backing.ecdh(recipient, other_key, tweak)
606 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
607 self.backing.get_inbound_payment_key_material()
609 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
611 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
612 match &mut *self.expectations.lock().unwrap() {
613 None => self.backing.get_shutdown_scriptpubkey(),
614 Some(expectations) => match expectations.pop_front() {
615 None => panic!("Unexpected get_shutdown_scriptpubkey"),
616 Some(expectation) => expectation.returns,
621 fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
622 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
623 let state = self.make_enforcement_state_cell(keys.commitment_seed);
624 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
627 fn get_secure_random_bytes(&self) -> [u8; 32] {
628 let override_random_bytes = self.override_random_bytes.lock().unwrap();
629 if let Some(bytes) = &*override_random_bytes {
632 self.backing.get_secure_random_bytes()
635 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
636 let mut reader = io::Cursor::new(buffer);
638 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
639 let state = self.make_enforcement_state_cell(inner.commitment_seed);
641 Ok(EnforcingSigner::new_with_revoked(
644 self.disable_revocation_policy_check
648 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
649 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
653 impl TestKeysInterface {
654 pub fn new(seed: &[u8; 32], network: Network) -> Self {
655 let now = Duration::from_secs(genesis_block(network).header.time as u64);
657 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
658 override_random_bytes: Mutex::new(None),
659 disable_revocation_policy_check: false,
660 enforcement_states: Mutex::new(HashMap::new()),
661 expectations: Mutex::new(None),
665 /// Sets an expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] is
667 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
668 self.expectations.lock().unwrap()
669 .get_or_insert_with(|| VecDeque::new())
670 .push_back(expectation);
674 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
675 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
676 let state = self.make_enforcement_state_cell(keys.commitment_seed);
677 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
680 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
681 let mut states = self.enforcement_states.lock().unwrap();
682 if !states.contains_key(&commitment_seed) {
683 let state = EnforcementState::new();
684 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
686 let cell = states.get(&commitment_seed).unwrap();
691 pub(crate) fn panicking() -> bool {
692 #[cfg(feature = "std")]
693 let panicking = ::std::thread::panicking();
694 #[cfg(not(feature = "std"))]
695 let panicking = false;
699 impl Drop for TestKeysInterface {
705 if let Some(expectations) = &*self.expectations.lock().unwrap() {
706 if !expectations.is_empty() {
707 panic!("Unsatisfied expectations: {:?}", expectations);
713 /// An expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] was called and
714 /// returns a [`ShutdownScript`].
715 pub struct OnGetShutdownScriptpubkey {
716 /// A shutdown script used to close a channel.
717 pub returns: ShutdownScript,
720 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
721 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
722 f.debug_struct("OnGetShutdownScriptpubkey").finish()
726 pub struct TestChainSource {
727 pub genesis_hash: BlockHash,
728 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
729 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
730 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
733 impl TestChainSource {
734 pub fn new(network: Network) -> Self {
735 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
737 genesis_hash: genesis_block(network).block_hash(),
738 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
739 watched_txn: Mutex::new(HashSet::new()),
740 watched_outputs: Mutex::new(HashSet::new()),
745 impl chain::Access for TestChainSource {
746 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
747 if self.genesis_hash != *genesis_hash {
748 return Err(chain::AccessError::UnknownChain);
751 self.utxo_ret.lock().unwrap().clone()
755 impl chain::Filter for TestChainSource {
756 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
757 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
760 fn register_output(&self, output: WatchedOutput) {
761 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
765 impl Drop for TestChainSource {
773 /// A scorer useful in testing, when the passage of time isn't a concern.
774 pub type TestScorer = FixedPenaltyScorer;