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 crate::chain::WatchedOutput;
12 use crate::chain::chaininterface;
13 use crate::chain::chaininterface::ConfirmationTarget;
14 use crate::chain::chainmonitor;
15 use crate::chain::chainmonitor::MonitorUpdateId;
16 use crate::chain::channelmonitor;
17 use crate::chain::channelmonitor::MonitorEvent;
18 use crate::chain::transaction::OutPoint;
19 use crate::chain::keysinterface;
20 use crate::ln::channelmanager;
21 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
22 use crate::ln::{msgs, wire};
23 use crate::ln::script::ShutdownScript;
24 use crate::routing::gossip::NetworkGraph;
25 use crate::routing::router::{find_route, InFlightHtlcs, Route, RouteHop, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
26 use crate::routing::scoring::FixedPenaltyScorer;
27 use crate::util::config::UserConfig;
28 use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
29 use crate::util::events;
30 use crate::util::logger::{Logger, Level, Record};
31 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::blockdata::transaction::{Transaction, TxOut};
35 use bitcoin::blockdata::script::{Builder, Script};
36 use bitcoin::blockdata::opcodes;
37 use bitcoin::blockdata::block::Block;
38 use bitcoin::network::constants::Network;
39 use bitcoin::hash_types::{BlockHash, Txid};
41 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature, Scalar};
42 use bitcoin::secp256k1::ecdh::SharedSecret;
43 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
48 use crate::prelude::*;
49 use core::time::Duration;
50 use crate::sync::{Mutex, Arc};
51 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
53 use bitcoin::bech32::u5;
54 use crate::chain::keysinterface::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
56 #[cfg(feature = "std")]
57 use std::time::{SystemTime, UNIX_EPOCH};
58 use bitcoin::Sequence;
60 pub struct TestVecWriter(pub Vec<u8>);
61 impl Writer for TestVecWriter {
62 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
63 self.0.extend_from_slice(buf);
68 pub struct TestFeeEstimator {
69 pub sat_per_kw: Mutex<u32>,
71 impl chaininterface::FeeEstimator for TestFeeEstimator {
72 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
73 *self.sat_per_kw.lock().unwrap()
77 pub struct TestRouter<'a> {
78 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
81 impl<'a> TestRouter<'a> {
82 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>) -> Self {
83 Self { network_graph }
87 impl<'a> Router for TestRouter<'a> {
89 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
90 inflight_htlcs: &InFlightHtlcs
91 ) -> Result<Route, msgs::LightningError> {
92 let logger = TestLogger::new();
94 payer, params, &self.network_graph, first_hops, &logger,
95 &ScorerAccountingForInFlightHtlcs::new(TestScorer::with_penalty(0), &inflight_htlcs),
99 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
100 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
101 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
102 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
105 pub struct OnlyReadsKeysInterface {}
107 impl EntropySource for OnlyReadsKeysInterface {
108 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
110 impl SignerProvider for OnlyReadsKeysInterface {
111 type Signer = EnforcingSigner;
113 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
115 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
117 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
118 let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap();
119 let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?;
120 let state = Arc::new(Mutex::new(EnforcementState::new()));
122 Ok(EnforcingSigner::new_with_revoked(
129 fn get_destination_script(&self) -> Script { unreachable!(); }
130 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
133 pub struct TestChainMonitor<'a> {
134 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
135 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
136 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
137 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
138 pub keys_manager: &'a TestKeysInterface,
139 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
140 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
142 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
144 impl<'a> TestChainMonitor<'a> {
145 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 {
147 added_monitors: Mutex::new(Vec::new()),
148 monitor_updates: Mutex::new(HashMap::new()),
149 latest_monitor_update_id: Mutex::new(HashMap::new()),
150 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
152 expect_channel_force_closed: Mutex::new(None),
156 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
157 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
158 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
161 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
162 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
163 // At every point where we get a monitor update, we should be able to send a useful monitor
164 // to a watchtower and disk...
165 let mut w = TestVecWriter(Vec::new());
166 monitor.write(&mut w).unwrap();
167 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
168 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
169 assert!(new_monitor == monitor);
170 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
171 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
172 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
173 self.chain_monitor.watch_channel(funding_txo, new_monitor)
176 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
177 // Every monitor update should survive roundtrip
178 let mut w = TestVecWriter(Vec::new());
179 update.write(&mut w).unwrap();
180 assert!(channelmonitor::ChannelMonitorUpdate::read(
181 &mut io::Cursor::new(&w.0)).unwrap() == *update);
183 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
185 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
186 assert_eq!(funding_txo.to_channel_id(), exp.0);
187 assert_eq!(update.updates.len(), 1);
188 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
189 assert_eq!(should_broadcast, exp.1);
193 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
194 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
195 let update_res = self.chain_monitor.update_channel(funding_txo, update);
196 // At every point where we get a monitor update, we should be able to send a useful monitor
197 // to a watchtower and disk...
198 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
200 monitor.write(&mut w).unwrap();
201 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
202 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
203 assert!(new_monitor == *monitor);
204 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
208 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
209 return self.chain_monitor.release_pending_monitor_events();
213 pub struct TestPersister {
214 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
216 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
217 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
218 /// MonitorUpdateId here.
219 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
220 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
221 /// MonitorUpdateId here.
222 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
225 pub fn new() -> Self {
227 update_rets: Mutex::new(VecDeque::new()),
228 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
229 offchain_monitor_updates: Mutex::new(HashMap::new()),
233 /// Queue an update status to return.
234 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
235 self.update_rets.lock().unwrap().push_back(next_ret);
238 impl<Signer: keysinterface::Sign> chainmonitor::Persist<Signer> for TestPersister {
239 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
240 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
243 chain::ChannelMonitorUpdateStatus::Completed
246 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
247 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
248 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
251 if update.is_none() {
252 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
254 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
260 pub struct TestBroadcaster {
261 pub txn_broadcasted: Mutex<Vec<Transaction>>,
262 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
265 impl TestBroadcaster {
266 pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
267 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
271 impl chaininterface::BroadcasterInterface for TestBroadcaster {
272 fn broadcast_transaction(&self, tx: &Transaction) {
273 let lock_time = tx.lock_time.0;
274 assert!(lock_time < 1_500_000_000);
275 if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 {
276 for inp in tx.input.iter() {
277 if inp.sequence != Sequence::MAX {
278 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
282 self.txn_broadcasted.lock().unwrap().push(tx.clone());
286 pub struct TestChannelMessageHandler {
287 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
288 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
291 impl TestChannelMessageHandler {
292 pub fn new() -> Self {
293 TestChannelMessageHandler {
294 pending_events: Mutex::new(Vec::new()),
295 expected_recv_msgs: Mutex::new(None),
300 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
301 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
302 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
303 expected_msgs.as_mut().unwrap().push(ev);
306 fn received_msg(&self, _ev: wire::Message<()>) {
307 let mut msgs = self.expected_recv_msgs.lock().unwrap();
308 if msgs.is_none() { return; }
309 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
311 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
312 msgs.as_mut().unwrap().remove(0);
316 impl Drop for TestChannelMessageHandler {
318 #[cfg(feature = "std")]
320 let l = self.expected_recv_msgs.lock().unwrap();
321 if !std::thread::panicking() {
322 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
328 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
329 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
330 self.received_msg(wire::Message::OpenChannel(msg.clone()));
332 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
333 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
335 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
336 self.received_msg(wire::Message::FundingCreated(msg.clone()));
338 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
339 self.received_msg(wire::Message::FundingSigned(msg.clone()));
341 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
342 self.received_msg(wire::Message::ChannelReady(msg.clone()));
344 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
345 self.received_msg(wire::Message::Shutdown(msg.clone()));
347 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
348 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
350 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
351 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
353 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
354 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
356 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
357 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
359 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
360 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
362 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
363 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
365 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
366 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
368 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
369 self.received_msg(wire::Message::UpdateFee(msg.clone()));
371 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
372 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
374 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
375 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
377 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
378 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
380 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
381 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> {
382 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
383 // bother re-generating the expected Init message in all tests.
386 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
387 self.received_msg(wire::Message::Error(msg.clone()));
389 fn provided_node_features(&self) -> NodeFeatures {
390 channelmanager::provided_node_features(&UserConfig::default())
392 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
393 channelmanager::provided_init_features(&UserConfig::default())
397 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
398 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
399 let mut pending_events = self.pending_events.lock().unwrap();
400 let mut ret = Vec::new();
401 mem::swap(&mut ret, &mut *pending_events);
406 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
407 use bitcoin::secp256k1::ffi::Signature as FFISignature;
408 let secp_ctx = Secp256k1::new();
409 let network = Network::Testnet;
410 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
411 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
412 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
413 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
414 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
415 features: ChannelFeatures::empty(),
416 chain_hash: genesis_block(network).header.block_hash(),
417 short_channel_id: short_chan_id,
418 node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey),
419 node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey),
420 bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey),
421 bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey),
422 excess_data: Vec::new(),
426 msgs::ChannelAnnouncement {
427 node_signature_1: Signature::from(FFISignature::new()),
428 node_signature_2: Signature::from(FFISignature::new()),
429 bitcoin_signature_1: Signature::from(FFISignature::new()),
430 bitcoin_signature_2: Signature::from(FFISignature::new()),
431 contents: unsigned_ann,
436 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
437 use bitcoin::secp256k1::ffi::Signature as FFISignature;
438 let network = Network::Testnet;
439 msgs::ChannelUpdate {
440 signature: Signature::from(unsafe { FFISignature::new() }),
441 contents: msgs::UnsignedChannelUpdate {
442 chain_hash: genesis_block(network).header.block_hash(),
443 short_channel_id: short_chan_id,
446 cltv_expiry_delta: 0,
447 htlc_minimum_msat: 0,
448 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
450 fee_proportional_millionths: 0,
456 pub struct TestRoutingMessageHandler {
457 pub chan_upds_recvd: AtomicUsize,
458 pub chan_anns_recvd: AtomicUsize,
459 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
460 pub request_full_sync: AtomicBool,
463 impl TestRoutingMessageHandler {
464 pub fn new() -> Self {
465 TestRoutingMessageHandler {
466 chan_upds_recvd: AtomicUsize::new(0),
467 chan_anns_recvd: AtomicUsize::new(0),
468 pending_events: Mutex::new(vec![]),
469 request_full_sync: AtomicBool::new(false),
473 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
474 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
475 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
477 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
478 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
479 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
481 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
482 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
483 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
485 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
486 let chan_upd_1 = get_dummy_channel_update(starting_point);
487 let chan_upd_2 = get_dummy_channel_update(starting_point);
488 let chan_ann = get_dummy_channel_announcement(starting_point);
490 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
493 fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option<msgs::NodeAnnouncement> {
497 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
498 if !init_msg.features.supports_gossip_queries() {
502 #[allow(unused_mut, unused_assignments)]
503 let mut gossip_start_time = 0;
504 #[cfg(feature = "std")]
506 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
507 if self.request_full_sync.load(Ordering::Acquire) {
508 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
510 gossip_start_time -= 60 * 60; // an hour ago
514 let mut pending_events = self.pending_events.lock().unwrap();
515 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
516 node_id: their_node_id.clone(),
517 msg: msgs::GossipTimestampFilter {
518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
519 first_timestamp: gossip_start_time as u32,
520 timestamp_range: u32::max_value(),
526 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
530 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
534 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
538 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
542 fn provided_node_features(&self) -> NodeFeatures {
543 let mut features = NodeFeatures::empty();
544 features.set_gossip_queries_optional();
548 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
549 let mut features = InitFeatures::empty();
550 features.set_gossip_queries_optional();
555 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
556 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
557 let mut ret = Vec::new();
558 let mut pending_events = self.pending_events.lock().unwrap();
559 core::mem::swap(&mut ret, &mut pending_events);
564 pub struct TestLogger {
566 pub(crate) id: String,
567 pub lines: Mutex<HashMap<(String, String), usize>>,
571 pub fn new() -> TestLogger {
572 Self::with_id("".to_owned())
574 pub fn with_id(id: String) -> TestLogger {
578 lines: Mutex::new(HashMap::new())
581 pub fn enable(&mut self, level: Level) {
584 pub fn assert_log(&self, module: String, line: String, count: usize) {
585 let log_entries = self.lines.lock().unwrap();
586 assert_eq!(log_entries.get(&(module, line)), Some(&count));
589 /// Search for the number of occurrence of the logged lines which
590 /// 1. belongs to the specified module and
591 /// 2. contains `line` in it.
592 /// And asserts if the number of occurrences is the same with the given `count`
593 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
594 let log_entries = self.lines.lock().unwrap();
595 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
596 m == &module && l.contains(line.as_str())
597 }).map(|(_, c) | { c }).sum();
601 /// Search for the number of occurrences of logged lines which
602 /// 1. belong to the specified module and
603 /// 2. match the given regex pattern.
604 /// Assert that the number of occurrences equals the given `count`
605 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
606 let log_entries = self.lines.lock().unwrap();
607 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
608 m == &module && pattern.is_match(&l)
609 }).map(|(_, c) | { c }).sum();
614 impl Logger for TestLogger {
615 fn log(&self, record: &Record) {
616 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
617 if record.level >= self.level {
618 #[cfg(feature = "std")]
619 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
624 pub struct TestKeysInterface {
625 pub backing: keysinterface::PhantomKeysManager,
626 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
627 pub disable_revocation_policy_check: bool,
628 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
629 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
632 impl EntropySource for TestKeysInterface {
633 fn get_secure_random_bytes(&self) -> [u8; 32] {
634 let override_random_bytes = self.override_random_bytes.lock().unwrap();
635 if let Some(bytes) = &*override_random_bytes {
638 self.backing.get_secure_random_bytes()
642 impl NodeSigner for TestKeysInterface {
643 fn get_node_secret(&self, recipient: Recipient) -> Result<SecretKey, ()> {
644 self.backing.get_node_secret(recipient)
647 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
648 self.backing.get_node_id(recipient)
651 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
652 self.backing.ecdh(recipient, other_key, tweak)
655 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
656 self.backing.get_inbound_payment_key_material()
659 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
660 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
664 impl SignerProvider for TestKeysInterface {
665 type Signer = EnforcingSigner;
667 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
668 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
671 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
672 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
673 let state = self.make_enforcement_state_cell(keys.commitment_seed);
674 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
677 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
678 let mut reader = io::Cursor::new(buffer);
680 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?;
681 let state = self.make_enforcement_state_cell(inner.commitment_seed);
683 Ok(EnforcingSigner::new_with_revoked(
686 self.disable_revocation_policy_check
690 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
692 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
693 match &mut *self.expectations.lock().unwrap() {
694 None => self.backing.get_shutdown_scriptpubkey(),
695 Some(expectations) => match expectations.pop_front() {
696 None => panic!("Unexpected get_shutdown_scriptpubkey"),
697 Some(expectation) => expectation.returns,
703 impl TestKeysInterface {
704 pub fn new(seed: &[u8; 32], network: Network) -> Self {
705 let now = Duration::from_secs(genesis_block(network).header.time as u64);
707 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
708 override_random_bytes: Mutex::new(None),
709 disable_revocation_policy_check: false,
710 enforcement_states: Mutex::new(HashMap::new()),
711 expectations: Mutex::new(None),
715 /// Sets an expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] is
717 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
718 self.expectations.lock().unwrap()
719 .get_or_insert_with(|| VecDeque::new())
720 .push_back(expectation);
724 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
725 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
726 let state = self.make_enforcement_state_cell(keys.commitment_seed);
727 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
730 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
731 let mut states = self.enforcement_states.lock().unwrap();
732 if !states.contains_key(&commitment_seed) {
733 let state = EnforcementState::new();
734 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
736 let cell = states.get(&commitment_seed).unwrap();
741 pub(crate) fn panicking() -> bool {
742 #[cfg(feature = "std")]
743 let panicking = ::std::thread::panicking();
744 #[cfg(not(feature = "std"))]
745 let panicking = false;
749 impl Drop for TestKeysInterface {
755 if let Some(expectations) = &*self.expectations.lock().unwrap() {
756 if !expectations.is_empty() {
757 panic!("Unsatisfied expectations: {:?}", expectations);
763 /// An expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] was called and
764 /// returns a [`ShutdownScript`].
765 pub struct OnGetShutdownScriptpubkey {
766 /// A shutdown script used to close a channel.
767 pub returns: ShutdownScript,
770 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
771 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
772 f.debug_struct("OnGetShutdownScriptpubkey").finish()
776 pub struct TestChainSource {
777 pub genesis_hash: BlockHash,
778 pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
779 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
780 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
783 impl TestChainSource {
784 pub fn new(network: Network) -> Self {
785 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
787 genesis_hash: genesis_block(network).block_hash(),
788 utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
789 watched_txn: Mutex::new(HashSet::new()),
790 watched_outputs: Mutex::new(HashSet::new()),
795 impl chain::Access for TestChainSource {
796 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
797 if self.genesis_hash != *genesis_hash {
798 return Err(chain::AccessError::UnknownChain);
801 self.utxo_ret.lock().unwrap().clone()
805 impl chain::Filter for TestChainSource {
806 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
807 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
810 fn register_output(&self, output: WatchedOutput) {
811 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
815 impl Drop for TestChainSource {
823 /// A scorer useful in testing, when the passage of time isn't a concern.
824 pub type TestScorer = FixedPenaltyScorer;