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::msgs::OptionalField;
23 use ln::script::ShutdownScript;
24 use routing::scoring::FixedPenaltyScorer;
25 use util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
27 use util::logger::{Logger, Level, Record};
28 use util::ser::{Readable, ReadableArgs, Writer, Writeable};
30 use bitcoin::blockdata::constants::genesis_block;
31 use bitcoin::blockdata::transaction::{Transaction, TxOut};
32 use bitcoin::blockdata::script::{Builder, Script};
33 use bitcoin::blockdata::opcodes;
34 use bitcoin::blockdata::block::BlockHeader;
35 use bitcoin::network::constants::Network;
36 use bitcoin::hash_types::{BlockHash, Txid};
38 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature};
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 get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); }
78 fn get_destination_script(&self) -> Script { unreachable!(); }
79 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
80 fn get_channel_signer(&self, _inbound: bool, _channel_value_satoshis: u64) -> EnforcingSigner { unreachable!(); }
81 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }
83 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
84 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
85 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
86 let state = Arc::new(Mutex::new(EnforcementState::new()));
88 Ok(EnforcingSigner::new_with_revoked(
94 fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result<RecoverableSignature, ()> { unreachable!(); }
97 pub struct TestChainMonitor<'a> {
98 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
99 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
100 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
101 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
102 pub keys_manager: &'a TestKeysInterface,
103 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
104 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
106 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
108 impl<'a> TestChainMonitor<'a> {
109 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 {
111 added_monitors: Mutex::new(Vec::new()),
112 monitor_updates: Mutex::new(HashMap::new()),
113 latest_monitor_update_id: Mutex::new(HashMap::new()),
114 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
116 expect_channel_force_closed: Mutex::new(None),
120 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
121 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
122 // At every point where we get a monitor update, we should be able to send a useful monitor
123 // to a watchtower and disk...
124 let mut w = TestVecWriter(Vec::new());
125 monitor.write(&mut w).unwrap();
126 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
127 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
128 assert!(new_monitor == monitor);
129 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
130 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
131 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
132 self.chain_monitor.watch_channel(funding_txo, new_monitor)
135 fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
136 // Every monitor update should survive roundtrip
137 let mut w = TestVecWriter(Vec::new());
138 update.write(&mut w).unwrap();
139 assert!(channelmonitor::ChannelMonitorUpdate::read(
140 &mut io::Cursor::new(&w.0)).unwrap() == update);
142 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
144 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
145 assert_eq!(funding_txo.to_channel_id(), exp.0);
146 assert_eq!(update.updates.len(), 1);
147 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
148 assert_eq!(should_broadcast, exp.1);
152 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
153 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
154 let update_res = self.chain_monitor.update_channel(funding_txo, update);
155 // At every point where we get a monitor update, we should be able to send a useful monitor
156 // to a watchtower and disk...
157 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
159 monitor.write(&mut w).unwrap();
160 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
161 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
162 assert!(new_monitor == *monitor);
163 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
167 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>)> {
168 return self.chain_monitor.release_pending_monitor_events();
172 pub struct TestPersister {
173 pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
174 /// If this is set to Some(), after the next return, we'll always return this until update_ret
176 pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
177 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
178 /// MonitorUpdateId here.
179 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
180 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
181 /// MonitorUpdateId here.
182 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
185 pub fn new() -> Self {
187 update_ret: Mutex::new(Ok(())),
188 next_update_ret: Mutex::new(None),
189 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
190 offchain_monitor_updates: Mutex::new(HashMap::new()),
194 pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
195 *self.update_ret.lock().unwrap() = ret;
198 pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
199 *self.next_update_ret.lock().unwrap() = next_ret;
202 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
203 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
204 let ret = self.update_ret.lock().unwrap().clone();
205 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
206 *self.update_ret.lock().unwrap() = next_ret;
211 fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
212 let ret = self.update_ret.lock().unwrap().clone();
213 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
214 *self.update_ret.lock().unwrap() = next_ret;
216 if update.is_none() {
217 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
219 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
225 pub struct TestBroadcaster {
226 pub txn_broadcasted: Mutex<Vec<Transaction>>,
227 pub blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>,
230 impl TestBroadcaster {
231 pub fn new(blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>) -> TestBroadcaster {
232 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
236 impl chaininterface::BroadcasterInterface for TestBroadcaster {
237 fn broadcast_transaction(&self, tx: &Transaction) {
238 assert!(tx.lock_time < 1_500_000_000);
239 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
240 for inp in tx.input.iter() {
241 if inp.sequence != 0xffffffff {
242 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
246 self.txn_broadcasted.lock().unwrap().push(tx.clone());
250 pub struct TestChannelMessageHandler {
251 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
252 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
255 impl TestChannelMessageHandler {
256 pub fn new() -> Self {
257 TestChannelMessageHandler {
258 pending_events: Mutex::new(Vec::new()),
259 expected_recv_msgs: Mutex::new(None),
264 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
265 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
266 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
267 expected_msgs.as_mut().unwrap().push(ev);
270 fn received_msg(&self, _ev: wire::Message<()>) {
271 let mut msgs = self.expected_recv_msgs.lock().unwrap();
272 if msgs.is_none() { return; }
273 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
275 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
276 msgs.as_mut().unwrap().remove(0);
280 impl Drop for TestChannelMessageHandler {
282 let l = self.expected_recv_msgs.lock().unwrap();
283 #[cfg(feature = "std")]
285 if !std::thread::panicking() {
286 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
292 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
293 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
294 self.received_msg(wire::Message::OpenChannel(msg.clone()));
296 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
297 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
299 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
300 self.received_msg(wire::Message::FundingCreated(msg.clone()));
302 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
303 self.received_msg(wire::Message::FundingSigned(msg.clone()));
305 fn handle_funding_locked(&self, _their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
306 self.received_msg(wire::Message::FundingLocked(msg.clone()));
308 fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
309 self.received_msg(wire::Message::Shutdown(msg.clone()));
311 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
312 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
314 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
315 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
317 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
318 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
320 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
321 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
323 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
324 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
326 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
327 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
329 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
330 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
332 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
333 self.received_msg(wire::Message::UpdateFee(msg.clone()));
335 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
336 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
338 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
339 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
341 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
342 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
344 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
345 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {
346 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
347 // bother re-generating the expected Init message in all tests.
349 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
350 self.received_msg(wire::Message::Error(msg.clone()));
354 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
355 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
356 let mut pending_events = self.pending_events.lock().unwrap();
357 let mut ret = Vec::new();
358 mem::swap(&mut ret, &mut *pending_events);
363 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
364 use bitcoin::secp256k1::ffi::Signature as FFISignature;
365 let secp_ctx = Secp256k1::new();
366 let network = Network::Testnet;
367 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
368 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
369 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
370 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
371 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
372 features: ChannelFeatures::known(),
373 chain_hash: genesis_block(network).header.block_hash(),
374 short_channel_id: short_chan_id,
375 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
376 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
377 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
378 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
379 excess_data: Vec::new(),
383 msgs::ChannelAnnouncement {
384 node_signature_1: Signature::from(FFISignature::new()),
385 node_signature_2: Signature::from(FFISignature::new()),
386 bitcoin_signature_1: Signature::from(FFISignature::new()),
387 bitcoin_signature_2: Signature::from(FFISignature::new()),
388 contents: unsigned_ann,
393 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
394 use bitcoin::secp256k1::ffi::Signature as FFISignature;
395 let network = Network::Testnet;
396 msgs::ChannelUpdate {
397 signature: Signature::from(unsafe { FFISignature::new() }),
398 contents: msgs::UnsignedChannelUpdate {
399 chain_hash: genesis_block(network).header.block_hash(),
400 short_channel_id: short_chan_id,
403 cltv_expiry_delta: 0,
404 htlc_minimum_msat: 0,
405 htlc_maximum_msat: OptionalField::Absent,
407 fee_proportional_millionths: 0,
413 pub struct TestRoutingMessageHandler {
414 pub chan_upds_recvd: AtomicUsize,
415 pub chan_anns_recvd: AtomicUsize,
416 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
417 pub request_full_sync: AtomicBool,
420 impl TestRoutingMessageHandler {
421 pub fn new() -> Self {
422 TestRoutingMessageHandler {
423 chan_upds_recvd: AtomicUsize::new(0),
424 chan_anns_recvd: AtomicUsize::new(0),
425 pending_events: Mutex::new(vec![]),
426 request_full_sync: AtomicBool::new(false),
430 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
431 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
432 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
434 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
435 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
436 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
438 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
439 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
440 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
442 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
443 let mut chan_anns = Vec::new();
444 const TOTAL_UPDS: u64 = 50;
445 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS);
446 for i in starting_point..end {
447 let chan_upd_1 = get_dummy_channel_update(i);
448 let chan_upd_2 = get_dummy_channel_update(i);
449 let chan_ann = get_dummy_channel_announcement(i);
451 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
457 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
461 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) {
462 if !init_msg.features.supports_gossip_queries() {
466 let should_request_full_sync = self.request_full_sync.load(Ordering::Acquire);
468 #[allow(unused_mut, unused_assignments)]
469 let mut gossip_start_time = 0;
470 #[cfg(feature = "std")]
472 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
473 if should_request_full_sync {
474 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
476 gossip_start_time -= 60 * 60; // an hour ago
480 let mut pending_events = self.pending_events.lock().unwrap();
481 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
482 node_id: their_node_id.clone(),
483 msg: msgs::GossipTimestampFilter {
484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
485 first_timestamp: gossip_start_time as u32,
486 timestamp_range: u32::max_value(),
491 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
495 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
499 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
503 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
508 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
509 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
510 let mut ret = Vec::new();
511 let mut pending_events = self.pending_events.lock().unwrap();
512 core::mem::swap(&mut ret, &mut pending_events);
517 pub struct TestLogger {
519 #[cfg(feature = "std")]
521 #[cfg(not(feature = "std"))]
523 pub lines: Mutex<HashMap<(String, String), usize>>,
527 pub fn new() -> TestLogger {
528 Self::with_id("".to_owned())
530 pub fn with_id(id: String) -> TestLogger {
533 #[cfg(feature = "std")]
535 #[cfg(not(feature = "std"))]
537 lines: Mutex::new(HashMap::new())
540 pub fn enable(&mut self, level: Level) {
543 pub fn assert_log(&self, module: String, line: String, count: usize) {
544 let log_entries = self.lines.lock().unwrap();
545 assert_eq!(log_entries.get(&(module, line)), Some(&count));
548 /// Search for the number of occurrence of the logged lines which
549 /// 1. belongs to the specified module and
550 /// 2. contains `line` in it.
551 /// And asserts if the number of occurrences is the same with the given `count`
552 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
553 let log_entries = self.lines.lock().unwrap();
554 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
555 m == &module && l.contains(line.as_str())
556 }).map(|(_, c) | { c }).sum();
560 /// Search for the number of occurrences of logged lines which
561 /// 1. belong to the specified module and
562 /// 2. match the given regex pattern.
563 /// Assert that the number of occurrences equals the given `count`
564 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
565 let log_entries = self.lines.lock().unwrap();
566 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
567 m == &module && pattern.is_match(&l)
568 }).map(|(_, c) | { c }).sum();
573 impl Logger for TestLogger {
574 fn log(&self, record: &Record) {
575 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
576 if record.level >= self.level {
577 #[cfg(feature = "std")]
578 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
583 pub struct TestKeysInterface {
584 pub backing: keysinterface::PhantomKeysManager,
585 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
586 pub disable_revocation_policy_check: bool,
587 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
588 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
591 impl keysinterface::KeysInterface for TestKeysInterface {
592 type Signer = EnforcingSigner;
594 fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
595 self.backing.get_node_secret(recipient)
597 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
598 self.backing.get_inbound_payment_key_material()
600 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
602 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
603 match &mut *self.expectations.lock().unwrap() {
604 None => self.backing.get_shutdown_scriptpubkey(),
605 Some(expectations) => match expectations.pop_front() {
606 None => panic!("Unexpected get_shutdown_scriptpubkey"),
607 Some(expectation) => expectation.returns,
612 fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
613 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
614 let state = self.make_enforcement_state_cell(keys.commitment_seed);
615 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
618 fn get_secure_random_bytes(&self) -> [u8; 32] {
619 let override_random_bytes = self.override_random_bytes.lock().unwrap();
620 if let Some(bytes) = &*override_random_bytes {
623 self.backing.get_secure_random_bytes()
626 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
627 let mut reader = io::Cursor::new(buffer);
629 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
630 let state = self.make_enforcement_state_cell(inner.commitment_seed);
632 Ok(EnforcingSigner::new_with_revoked(
635 self.disable_revocation_policy_check
639 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
640 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
644 impl TestKeysInterface {
645 pub fn new(seed: &[u8; 32], network: Network) -> Self {
646 let now = Duration::from_secs(genesis_block(network).header.time as u64);
648 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
649 override_random_bytes: Mutex::new(None),
650 disable_revocation_policy_check: false,
651 enforcement_states: Mutex::new(HashMap::new()),
652 expectations: Mutex::new(None),
656 /// Sets an expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] is
658 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
659 self.expectations.lock().unwrap()
660 .get_or_insert_with(|| VecDeque::new())
661 .push_back(expectation);
665 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
666 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
667 let state = self.make_enforcement_state_cell(keys.commitment_seed);
668 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
671 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
672 let mut states = self.enforcement_states.lock().unwrap();
673 if !states.contains_key(&commitment_seed) {
674 let state = EnforcementState::new();
675 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
677 let cell = states.get(&commitment_seed).unwrap();
682 pub(crate) fn panicking() -> bool {
683 #[cfg(feature = "std")]
684 let panicking = ::std::thread::panicking();
685 #[cfg(not(feature = "std"))]
686 let panicking = false;
690 impl Drop for TestKeysInterface {
696 if let Some(expectations) = &*self.expectations.lock().unwrap() {
697 if !expectations.is_empty() {
698 panic!("Unsatisfied expectations: {:?}", expectations);
704 /// An expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] was called and
705 /// returns a [`ShutdownScript`].
706 pub struct OnGetShutdownScriptpubkey {
707 /// A shutdown script used to close a channel.
708 pub returns: ShutdownScript,
711 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
712 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
713 f.debug_struct("OnGetShutdownScriptpubkey").finish()
717 pub struct TestChainSource {
718 pub genesis_hash: BlockHash,
719 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
720 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
721 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
722 expectations: Mutex<Option<VecDeque<OnRegisterOutput>>>,
725 impl TestChainSource {
726 pub fn new(network: Network) -> Self {
727 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
729 genesis_hash: genesis_block(network).block_hash(),
730 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
731 watched_txn: Mutex::new(HashSet::new()),
732 watched_outputs: Mutex::new(HashSet::new()),
733 expectations: Mutex::new(None),
737 /// Sets an expectation that [`chain::Filter::register_output`] is called.
738 pub fn expect(&self, expectation: OnRegisterOutput) -> &Self {
739 self.expectations.lock().unwrap()
740 .get_or_insert_with(|| VecDeque::new())
741 .push_back(expectation);
746 impl chain::Access for TestChainSource {
747 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
748 if self.genesis_hash != *genesis_hash {
749 return Err(chain::AccessError::UnknownChain);
752 self.utxo_ret.lock().unwrap().clone()
756 impl chain::Filter for TestChainSource {
757 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
758 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
761 fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)> {
762 let dependent_tx = match &mut *self.expectations.lock().unwrap() {
764 Some(expectations) => match expectations.pop_front() {
766 panic!("Unexpected register_output: {:?}",
767 (output.outpoint, output.script_pubkey));
769 Some(expectation) => {
770 assert_eq!(output.outpoint, expectation.outpoint());
771 assert_eq!(&output.script_pubkey, expectation.script_pubkey());
777 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
782 impl Drop for TestChainSource {
788 if let Some(expectations) = &*self.expectations.lock().unwrap() {
789 if !expectations.is_empty() {
790 panic!("Unsatisfied expectations: {:?}", expectations);
796 /// An expectation that [`chain::Filter::register_output`] was called with a transaction output and
797 /// returns an optional dependent transaction that spends the output in the same block.
798 pub struct OnRegisterOutput {
799 /// The transaction output to register.
800 pub with: TxOutReference,
802 /// A dependent transaction spending the output along with its position in the block.
803 pub returns: Option<(usize, Transaction)>,
806 /// A transaction output as identified by an index into a transaction's output list.
807 pub struct TxOutReference(pub Transaction, pub usize);
809 impl OnRegisterOutput {
810 fn outpoint(&self) -> OutPoint {
811 let txid = self.with.0.txid();
812 let index = self.with.1 as u16;
813 OutPoint { txid, index }
816 fn script_pubkey(&self) -> &Script {
817 let index = self.with.1;
818 &self.with.0.output[index].script_pubkey
822 impl core::fmt::Debug for OnRegisterOutput {
823 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
824 f.debug_struct("OnRegisterOutput")
825 .field("outpoint", &self.outpoint())
826 .field("script_pubkey", self.script_pubkey())
831 /// A scorer useful in testing, when the passage of time isn't a concern.
832 pub type TestScorer = FixedPenaltyScorer;