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::Block;
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 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
121 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
122 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
125 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
126 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> Result<(), chain::ChannelMonitorUpdateErr> {
127 // At every point where we get a monitor update, we should be able to send a useful monitor
128 // to a watchtower and disk...
129 let mut w = TestVecWriter(Vec::new());
130 monitor.write(&mut w).unwrap();
131 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
132 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
133 assert!(new_monitor == monitor);
134 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
135 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
136 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
137 self.chain_monitor.watch_channel(funding_txo, new_monitor)
140 fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> Result<(), chain::ChannelMonitorUpdateErr> {
141 // Every monitor update should survive roundtrip
142 let mut w = TestVecWriter(Vec::new());
143 update.write(&mut w).unwrap();
144 assert!(channelmonitor::ChannelMonitorUpdate::read(
145 &mut io::Cursor::new(&w.0)).unwrap() == update);
147 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
149 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
150 assert_eq!(funding_txo.to_channel_id(), exp.0);
151 assert_eq!(update.updates.len(), 1);
152 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
153 assert_eq!(should_broadcast, exp.1);
157 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
158 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update)));
159 let update_res = self.chain_monitor.update_channel(funding_txo, update);
160 // At every point where we get a monitor update, we should be able to send a useful monitor
161 // to a watchtower and disk...
162 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
164 monitor.write(&mut w).unwrap();
165 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
166 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap().1;
167 assert!(new_monitor == *monitor);
168 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
172 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>)> {
173 return self.chain_monitor.release_pending_monitor_events();
177 pub struct TestPersister {
178 pub update_ret: Mutex<Result<(), chain::ChannelMonitorUpdateErr>>,
179 /// If this is set to Some(), after the next return, we'll always return this until update_ret
181 pub next_update_ret: Mutex<Option<Result<(), chain::ChannelMonitorUpdateErr>>>,
182 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
183 /// MonitorUpdateId here.
184 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
185 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
186 /// MonitorUpdateId here.
187 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
190 pub fn new() -> Self {
192 update_ret: Mutex::new(Ok(())),
193 next_update_ret: Mutex::new(None),
194 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
195 offchain_monitor_updates: Mutex::new(HashMap::new()),
199 pub fn set_update_ret(&self, ret: Result<(), chain::ChannelMonitorUpdateErr>) {
200 *self.update_ret.lock().unwrap() = ret;
203 pub fn set_next_update_ret(&self, next_ret: Option<Result<(), chain::ChannelMonitorUpdateErr>>) {
204 *self.next_update_ret.lock().unwrap() = next_ret;
207 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
208 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
209 let ret = self.update_ret.lock().unwrap().clone();
210 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
211 *self.update_ret.lock().unwrap() = next_ret;
216 fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option<channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> Result<(), chain::ChannelMonitorUpdateErr> {
217 let ret = self.update_ret.lock().unwrap().clone();
218 if let Some(next_ret) = self.next_update_ret.lock().unwrap().take() {
219 *self.update_ret.lock().unwrap() = next_ret;
221 if update.is_none() {
222 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
224 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
230 pub struct TestBroadcaster {
231 pub txn_broadcasted: Mutex<Vec<Transaction>>,
232 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
235 impl TestBroadcaster {
236 pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
237 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
241 impl chaininterface::BroadcasterInterface for TestBroadcaster {
242 fn broadcast_transaction(&self, tx: &Transaction) {
243 assert!(tx.lock_time < 1_500_000_000);
244 if tx.lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && tx.lock_time < 500_000_000 {
245 for inp in tx.input.iter() {
246 if inp.sequence != 0xffffffff {
247 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
251 self.txn_broadcasted.lock().unwrap().push(tx.clone());
255 pub struct TestChannelMessageHandler {
256 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
257 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
260 impl TestChannelMessageHandler {
261 pub fn new() -> Self {
262 TestChannelMessageHandler {
263 pending_events: Mutex::new(Vec::new()),
264 expected_recv_msgs: Mutex::new(None),
269 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
270 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
271 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
272 expected_msgs.as_mut().unwrap().push(ev);
275 fn received_msg(&self, _ev: wire::Message<()>) {
276 let mut msgs = self.expected_recv_msgs.lock().unwrap();
277 if msgs.is_none() { return; }
278 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
280 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
281 msgs.as_mut().unwrap().remove(0);
285 impl Drop for TestChannelMessageHandler {
287 let l = self.expected_recv_msgs.lock().unwrap();
288 #[cfg(feature = "std")]
290 if !std::thread::panicking() {
291 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
297 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
298 fn handle_open_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
299 self.received_msg(wire::Message::OpenChannel(msg.clone()));
301 fn handle_accept_channel(&self, _their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
302 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
304 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
305 self.received_msg(wire::Message::FundingCreated(msg.clone()));
307 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
308 self.received_msg(wire::Message::FundingSigned(msg.clone()));
310 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
311 self.received_msg(wire::Message::ChannelReady(msg.clone()));
313 fn handle_shutdown(&self, _their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
314 self.received_msg(wire::Message::Shutdown(msg.clone()));
316 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
317 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
319 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
320 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
322 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
323 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
325 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
326 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
328 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
329 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
331 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
332 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
334 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
335 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
337 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
338 self.received_msg(wire::Message::UpdateFee(msg.clone()));
340 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
341 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
343 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
344 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
346 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
347 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
349 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
350 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {
351 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
352 // bother re-generating the expected Init message in all tests.
354 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
355 self.received_msg(wire::Message::Error(msg.clone()));
359 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
360 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
361 let mut pending_events = self.pending_events.lock().unwrap();
362 let mut ret = Vec::new();
363 mem::swap(&mut ret, &mut *pending_events);
368 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
369 use bitcoin::secp256k1::ffi::Signature as FFISignature;
370 let secp_ctx = Secp256k1::new();
371 let network = Network::Testnet;
372 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
373 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
374 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
375 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
376 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
377 features: ChannelFeatures::known(),
378 chain_hash: genesis_block(network).header.block_hash(),
379 short_channel_id: short_chan_id,
380 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
381 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
382 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
383 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
384 excess_data: Vec::new(),
388 msgs::ChannelAnnouncement {
389 node_signature_1: Signature::from(FFISignature::new()),
390 node_signature_2: Signature::from(FFISignature::new()),
391 bitcoin_signature_1: Signature::from(FFISignature::new()),
392 bitcoin_signature_2: Signature::from(FFISignature::new()),
393 contents: unsigned_ann,
398 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
399 use bitcoin::secp256k1::ffi::Signature as FFISignature;
400 let network = Network::Testnet;
401 msgs::ChannelUpdate {
402 signature: Signature::from(unsafe { FFISignature::new() }),
403 contents: msgs::UnsignedChannelUpdate {
404 chain_hash: genesis_block(network).header.block_hash(),
405 short_channel_id: short_chan_id,
408 cltv_expiry_delta: 0,
409 htlc_minimum_msat: 0,
410 htlc_maximum_msat: OptionalField::Absent,
412 fee_proportional_millionths: 0,
418 pub struct TestRoutingMessageHandler {
419 pub chan_upds_recvd: AtomicUsize,
420 pub chan_anns_recvd: AtomicUsize,
421 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
422 pub request_full_sync: AtomicBool,
425 impl TestRoutingMessageHandler {
426 pub fn new() -> Self {
427 TestRoutingMessageHandler {
428 chan_upds_recvd: AtomicUsize::new(0),
429 chan_anns_recvd: AtomicUsize::new(0),
430 pending_events: Mutex::new(vec![]),
431 request_full_sync: AtomicBool::new(false),
435 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
436 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
437 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
439 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
440 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
441 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
443 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
444 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
445 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
447 fn get_next_channel_announcements(&self, starting_point: u64, batch_amount: u8) -> Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
448 let mut chan_anns = Vec::new();
449 const TOTAL_UPDS: u64 = 50;
450 let end: u64 = cmp::min(starting_point + batch_amount as u64, TOTAL_UPDS);
451 for i in starting_point..end {
452 let chan_upd_1 = get_dummy_channel_update(i);
453 let chan_upd_2 = get_dummy_channel_update(i);
454 let chan_ann = get_dummy_channel_announcement(i);
456 chan_anns.push((chan_ann, Some(chan_upd_1), Some(chan_upd_2)));
462 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> {
466 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) {
467 if !init_msg.features.supports_gossip_queries() {
471 let should_request_full_sync = self.request_full_sync.load(Ordering::Acquire);
473 #[allow(unused_mut, unused_assignments)]
474 let mut gossip_start_time = 0;
475 #[cfg(feature = "std")]
477 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
478 if should_request_full_sync {
479 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
481 gossip_start_time -= 60 * 60; // an hour ago
485 let mut pending_events = self.pending_events.lock().unwrap();
486 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
487 node_id: their_node_id.clone(),
488 msg: msgs::GossipTimestampFilter {
489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
490 first_timestamp: gossip_start_time as u32,
491 timestamp_range: u32::max_value(),
496 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
500 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
504 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
508 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
513 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
514 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
515 let mut ret = Vec::new();
516 let mut pending_events = self.pending_events.lock().unwrap();
517 core::mem::swap(&mut ret, &mut pending_events);
522 pub struct TestLogger {
524 #[cfg(feature = "std")]
526 #[cfg(not(feature = "std"))]
528 pub lines: Mutex<HashMap<(String, String), usize>>,
532 pub fn new() -> TestLogger {
533 Self::with_id("".to_owned())
535 pub fn with_id(id: String) -> TestLogger {
538 #[cfg(feature = "std")]
540 #[cfg(not(feature = "std"))]
542 lines: Mutex::new(HashMap::new())
545 pub fn enable(&mut self, level: Level) {
548 pub fn assert_log(&self, module: String, line: String, count: usize) {
549 let log_entries = self.lines.lock().unwrap();
550 assert_eq!(log_entries.get(&(module, line)), Some(&count));
553 /// Search for the number of occurrence of the logged lines which
554 /// 1. belongs to the specified module and
555 /// 2. contains `line` in it.
556 /// And asserts if the number of occurrences is the same with the given `count`
557 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
558 let log_entries = self.lines.lock().unwrap();
559 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
560 m == &module && l.contains(line.as_str())
561 }).map(|(_, c) | { c }).sum();
565 /// Search for the number of occurrences of logged lines which
566 /// 1. belong to the specified module and
567 /// 2. match the given regex pattern.
568 /// Assert that the number of occurrences equals the given `count`
569 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
570 let log_entries = self.lines.lock().unwrap();
571 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
572 m == &module && pattern.is_match(&l)
573 }).map(|(_, c) | { c }).sum();
578 impl Logger for TestLogger {
579 fn log(&self, record: &Record) {
580 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
581 if record.level >= self.level {
582 #[cfg(feature = "std")]
583 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
588 pub struct TestKeysInterface {
589 pub backing: keysinterface::PhantomKeysManager,
590 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
591 pub disable_revocation_policy_check: bool,
592 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
593 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
596 impl keysinterface::KeysInterface for TestKeysInterface {
597 type Signer = EnforcingSigner;
599 fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
600 self.backing.get_node_secret(recipient)
602 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
603 self.backing.get_inbound_payment_key_material()
605 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
607 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
608 match &mut *self.expectations.lock().unwrap() {
609 None => self.backing.get_shutdown_scriptpubkey(),
610 Some(expectations) => match expectations.pop_front() {
611 None => panic!("Unexpected get_shutdown_scriptpubkey"),
612 Some(expectation) => expectation.returns,
617 fn get_channel_signer(&self, inbound: bool, channel_value_satoshis: u64) -> EnforcingSigner {
618 let keys = self.backing.get_channel_signer(inbound, channel_value_satoshis);
619 let state = self.make_enforcement_state_cell(keys.commitment_seed);
620 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
623 fn get_secure_random_bytes(&self) -> [u8; 32] {
624 let override_random_bytes = self.override_random_bytes.lock().unwrap();
625 if let Some(bytes) = &*override_random_bytes {
628 self.backing.get_secure_random_bytes()
631 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
632 let mut reader = io::Cursor::new(buffer);
634 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
635 let state = self.make_enforcement_state_cell(inner.commitment_seed);
637 Ok(EnforcingSigner::new_with_revoked(
640 self.disable_revocation_policy_check
644 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
645 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
649 impl TestKeysInterface {
650 pub fn new(seed: &[u8; 32], network: Network) -> Self {
651 let now = Duration::from_secs(genesis_block(network).header.time as u64);
653 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
654 override_random_bytes: Mutex::new(None),
655 disable_revocation_policy_check: false,
656 enforcement_states: Mutex::new(HashMap::new()),
657 expectations: Mutex::new(None),
661 /// Sets an expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] is
663 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
664 self.expectations.lock().unwrap()
665 .get_or_insert_with(|| VecDeque::new())
666 .push_back(expectation);
670 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
671 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
672 let state = self.make_enforcement_state_cell(keys.commitment_seed);
673 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
676 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
677 let mut states = self.enforcement_states.lock().unwrap();
678 if !states.contains_key(&commitment_seed) {
679 let state = EnforcementState::new();
680 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
682 let cell = states.get(&commitment_seed).unwrap();
687 pub(crate) fn panicking() -> bool {
688 #[cfg(feature = "std")]
689 let panicking = ::std::thread::panicking();
690 #[cfg(not(feature = "std"))]
691 let panicking = false;
695 impl Drop for TestKeysInterface {
701 if let Some(expectations) = &*self.expectations.lock().unwrap() {
702 if !expectations.is_empty() {
703 panic!("Unsatisfied expectations: {:?}", expectations);
709 /// An expectation that [`keysinterface::KeysInterface::get_shutdown_scriptpubkey`] was called and
710 /// returns a [`ShutdownScript`].
711 pub struct OnGetShutdownScriptpubkey {
712 /// A shutdown script used to close a channel.
713 pub returns: ShutdownScript,
716 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
717 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
718 f.debug_struct("OnGetShutdownScriptpubkey").finish()
722 pub struct TestChainSource {
723 pub genesis_hash: BlockHash,
724 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
725 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
726 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
727 expectations: Mutex<Option<VecDeque<OnRegisterOutput>>>,
730 impl TestChainSource {
731 pub fn new(network: Network) -> Self {
732 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
734 genesis_hash: genesis_block(network).block_hash(),
735 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
736 watched_txn: Mutex::new(HashSet::new()),
737 watched_outputs: Mutex::new(HashSet::new()),
738 expectations: Mutex::new(None),
742 /// Sets an expectation that [`chain::Filter::register_output`] is called.
743 pub fn expect(&self, expectation: OnRegisterOutput) -> &Self {
744 self.expectations.lock().unwrap()
745 .get_or_insert_with(|| VecDeque::new())
746 .push_back(expectation);
751 impl chain::Access for TestChainSource {
752 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
753 if self.genesis_hash != *genesis_hash {
754 return Err(chain::AccessError::UnknownChain);
757 self.utxo_ret.lock().unwrap().clone()
761 impl chain::Filter for TestChainSource {
762 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
763 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
766 fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)> {
767 let dependent_tx = match &mut *self.expectations.lock().unwrap() {
769 Some(expectations) => match expectations.pop_front() {
771 panic!("Unexpected register_output: {:?}",
772 (output.outpoint, output.script_pubkey));
774 Some(expectation) => {
775 assert_eq!(output.outpoint, expectation.outpoint());
776 assert_eq!(&output.script_pubkey, expectation.script_pubkey());
782 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
787 impl Drop for TestChainSource {
793 if let Some(expectations) = &*self.expectations.lock().unwrap() {
794 if !expectations.is_empty() {
795 panic!("Unsatisfied expectations: {:?}", expectations);
801 /// An expectation that [`chain::Filter::register_output`] was called with a transaction output and
802 /// returns an optional dependent transaction that spends the output in the same block.
803 pub struct OnRegisterOutput {
804 /// The transaction output to register.
805 pub with: TxOutReference,
807 /// A dependent transaction spending the output along with its position in the block.
808 pub returns: Option<(usize, Transaction)>,
811 /// A transaction output as identified by an index into a transaction's output list.
812 pub struct TxOutReference(pub Transaction, pub usize);
814 impl OnRegisterOutput {
815 fn outpoint(&self) -> OutPoint {
816 let txid = self.with.0.txid();
817 let index = self.with.1 as u16;
818 OutPoint { txid, index }
821 fn script_pubkey(&self) -> &Script {
822 let index = self.with.1;
823 &self.with.0.output[index].script_pubkey
827 impl core::fmt::Debug for OnRegisterOutput {
828 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
829 f.debug_struct("OnRegisterOutput")
830 .field("outpoint", &self.outpoint())
831 .field("script_pubkey", self.script_pubkey())
836 /// A scorer useful in testing, when the passage of time isn't a concern.
837 pub type TestScorer = FixedPenaltyScorer;