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::msgs::LightningError;
24 use crate::ln::script::ShutdownScript;
25 use crate::routing::gossip::{NetworkGraph, NodeId};
26 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
27 use crate::routing::router::{find_route, InFlightHtlcs, Route, RouteHop, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
28 use crate::routing::scoring::FixedPenaltyScorer;
29 use crate::util::config::UserConfig;
30 use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
31 use crate::util::events;
32 use crate::util::logger::{Logger, Level, Record};
33 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
35 use bitcoin::blockdata::constants::genesis_block;
36 use bitcoin::blockdata::transaction::{Transaction, TxOut};
37 use bitcoin::blockdata::script::{Builder, Script};
38 use bitcoin::blockdata::opcodes;
39 use bitcoin::blockdata::block::Block;
40 use bitcoin::network::constants::Network;
41 use bitcoin::hash_types::{BlockHash, Txid};
43 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature, Scalar};
44 use bitcoin::secp256k1::ecdh::SharedSecret;
45 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
50 use crate::prelude::*;
51 use core::time::Duration;
52 use crate::sync::{Mutex, Arc};
53 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
55 use bitcoin::bech32::u5;
56 use crate::chain::keysinterface::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
58 #[cfg(feature = "std")]
59 use std::time::{SystemTime, UNIX_EPOCH};
60 use bitcoin::Sequence;
62 pub struct TestVecWriter(pub Vec<u8>);
63 impl Writer for TestVecWriter {
64 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
65 self.0.extend_from_slice(buf);
70 pub struct TestFeeEstimator {
71 pub sat_per_kw: Mutex<u32>,
73 impl chaininterface::FeeEstimator for TestFeeEstimator {
74 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
75 *self.sat_per_kw.lock().unwrap()
79 pub struct TestRouter<'a> {
80 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
81 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
84 impl<'a> TestRouter<'a> {
85 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>) -> Self {
86 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), }
89 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
90 let mut expected_routes = self.next_routes.lock().unwrap();
91 expected_routes.push_back((query, result));
95 impl<'a> Router for TestRouter<'a> {
97 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
98 inflight_htlcs: &InFlightHtlcs
99 ) -> Result<Route, msgs::LightningError> {
100 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
101 assert_eq!(find_route_query, *params);
102 return find_route_res;
104 let logger = TestLogger::new();
106 payer, params, &self.network_graph, first_hops, &logger,
107 &ScorerAccountingForInFlightHtlcs::new(TestScorer::with_penalty(0), &inflight_htlcs),
111 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
112 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
113 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
114 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
117 #[cfg(feature = "std")] // If we put this on the `if`, we get "attributes are not yet allowed on `if` expressions" on 1.41.1
118 impl<'a> Drop for TestRouter<'a> {
120 if std::thread::panicking() {
123 assert!(self.next_routes.lock().unwrap().is_empty());
127 pub struct OnlyReadsKeysInterface {}
129 impl EntropySource for OnlyReadsKeysInterface {
130 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
132 impl SignerProvider for OnlyReadsKeysInterface {
133 type Signer = EnforcingSigner;
135 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
137 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
139 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
140 let inner: InMemorySigner = Readable::read(&mut reader)?;
141 let state = Arc::new(Mutex::new(EnforcementState::new()));
143 Ok(EnforcingSigner::new_with_revoked(
150 fn get_destination_script(&self) -> Script { unreachable!(); }
151 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
154 pub struct TestChainMonitor<'a> {
155 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
156 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
157 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
158 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
159 pub keys_manager: &'a TestKeysInterface,
160 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
161 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
163 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
165 impl<'a> TestChainMonitor<'a> {
166 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 {
168 added_monitors: Mutex::new(Vec::new()),
169 monitor_updates: Mutex::new(HashMap::new()),
170 latest_monitor_update_id: Mutex::new(HashMap::new()),
171 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
173 expect_channel_force_closed: Mutex::new(None),
177 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
178 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
179 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
182 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
183 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
184 // At every point where we get a monitor update, we should be able to send a useful monitor
185 // to a watchtower and disk...
186 let mut w = TestVecWriter(Vec::new());
187 monitor.write(&mut w).unwrap();
188 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
189 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
190 assert!(new_monitor == monitor);
191 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
192 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
193 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
194 self.chain_monitor.watch_channel(funding_txo, new_monitor)
197 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
198 // Every monitor update should survive roundtrip
199 let mut w = TestVecWriter(Vec::new());
200 update.write(&mut w).unwrap();
201 assert!(channelmonitor::ChannelMonitorUpdate::read(
202 &mut io::Cursor::new(&w.0)).unwrap() == *update);
204 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
206 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
207 assert_eq!(funding_txo.to_channel_id(), exp.0);
208 assert_eq!(update.updates.len(), 1);
209 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
210 assert_eq!(should_broadcast, exp.1);
214 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
215 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
216 let update_res = self.chain_monitor.update_channel(funding_txo, update);
217 // At every point where we get a monitor update, we should be able to send a useful monitor
218 // to a watchtower and disk...
219 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
221 monitor.write(&mut w).unwrap();
222 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
223 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
224 assert!(new_monitor == *monitor);
225 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
229 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
230 return self.chain_monitor.release_pending_monitor_events();
234 pub struct TestPersister {
235 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
237 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
238 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
239 /// MonitorUpdateId here.
240 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
241 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
242 /// MonitorUpdateId here.
243 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
246 pub fn new() -> Self {
248 update_rets: Mutex::new(VecDeque::new()),
249 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
250 offchain_monitor_updates: Mutex::new(HashMap::new()),
254 /// Queue an update status to return.
255 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
256 self.update_rets.lock().unwrap().push_back(next_ret);
259 impl<Signer: keysinterface::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
260 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
261 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
264 chain::ChannelMonitorUpdateStatus::Completed
267 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
268 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
269 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
272 if update.is_none() {
273 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
275 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
281 pub struct TestBroadcaster {
282 pub txn_broadcasted: Mutex<Vec<Transaction>>,
283 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
286 impl TestBroadcaster {
287 pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
288 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
292 impl chaininterface::BroadcasterInterface for TestBroadcaster {
293 fn broadcast_transaction(&self, tx: &Transaction) {
294 let lock_time = tx.lock_time.0;
295 assert!(lock_time < 1_500_000_000);
296 if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 {
297 for inp in tx.input.iter() {
298 if inp.sequence != Sequence::MAX {
299 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
303 self.txn_broadcasted.lock().unwrap().push(tx.clone());
307 pub struct TestChannelMessageHandler {
308 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
309 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
312 impl TestChannelMessageHandler {
313 pub fn new() -> Self {
314 TestChannelMessageHandler {
315 pending_events: Mutex::new(Vec::new()),
316 expected_recv_msgs: Mutex::new(None),
321 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
322 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
323 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
324 expected_msgs.as_mut().unwrap().push(ev);
327 fn received_msg(&self, _ev: wire::Message<()>) {
328 let mut msgs = self.expected_recv_msgs.lock().unwrap();
329 if msgs.is_none() { return; }
330 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
332 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
333 msgs.as_mut().unwrap().remove(0);
337 impl Drop for TestChannelMessageHandler {
339 #[cfg(feature = "std")]
341 let l = self.expected_recv_msgs.lock().unwrap();
342 if !std::thread::panicking() {
343 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
349 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
350 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
351 self.received_msg(wire::Message::OpenChannel(msg.clone()));
353 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
354 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
356 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
357 self.received_msg(wire::Message::FundingCreated(msg.clone()));
359 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
360 self.received_msg(wire::Message::FundingSigned(msg.clone()));
362 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
363 self.received_msg(wire::Message::ChannelReady(msg.clone()));
365 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
366 self.received_msg(wire::Message::Shutdown(msg.clone()));
368 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
369 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
371 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
372 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
374 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
375 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
377 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
378 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
380 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
381 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
383 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
384 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
386 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
387 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
389 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
390 self.received_msg(wire::Message::UpdateFee(msg.clone()));
392 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
393 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
395 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
396 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
398 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
399 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
401 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
402 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> {
403 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
404 // bother re-generating the expected Init message in all tests.
407 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
408 self.received_msg(wire::Message::Error(msg.clone()));
410 fn provided_node_features(&self) -> NodeFeatures {
411 channelmanager::provided_node_features(&UserConfig::default())
413 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
414 channelmanager::provided_init_features(&UserConfig::default())
418 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
419 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
420 let mut pending_events = self.pending_events.lock().unwrap();
421 let mut ret = Vec::new();
422 mem::swap(&mut ret, &mut *pending_events);
427 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
428 use bitcoin::secp256k1::ffi::Signature as FFISignature;
429 let secp_ctx = Secp256k1::new();
430 let network = Network::Testnet;
431 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
432 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
433 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
434 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
435 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
436 features: ChannelFeatures::empty(),
437 chain_hash: genesis_block(network).header.block_hash(),
438 short_channel_id: short_chan_id,
439 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
440 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
441 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
442 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
443 excess_data: Vec::new(),
447 msgs::ChannelAnnouncement {
448 node_signature_1: Signature::from(FFISignature::new()),
449 node_signature_2: Signature::from(FFISignature::new()),
450 bitcoin_signature_1: Signature::from(FFISignature::new()),
451 bitcoin_signature_2: Signature::from(FFISignature::new()),
452 contents: unsigned_ann,
457 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
458 use bitcoin::secp256k1::ffi::Signature as FFISignature;
459 let network = Network::Testnet;
460 msgs::ChannelUpdate {
461 signature: Signature::from(unsafe { FFISignature::new() }),
462 contents: msgs::UnsignedChannelUpdate {
463 chain_hash: genesis_block(network).header.block_hash(),
464 short_channel_id: short_chan_id,
467 cltv_expiry_delta: 0,
468 htlc_minimum_msat: 0,
469 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
471 fee_proportional_millionths: 0,
477 pub struct TestRoutingMessageHandler {
478 pub chan_upds_recvd: AtomicUsize,
479 pub chan_anns_recvd: AtomicUsize,
480 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
481 pub request_full_sync: AtomicBool,
484 impl TestRoutingMessageHandler {
485 pub fn new() -> Self {
486 TestRoutingMessageHandler {
487 chan_upds_recvd: AtomicUsize::new(0),
488 chan_anns_recvd: AtomicUsize::new(0),
489 pending_events: Mutex::new(vec![]),
490 request_full_sync: AtomicBool::new(false),
494 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
495 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
496 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
498 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
499 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
500 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
502 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
503 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
504 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
506 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
507 let chan_upd_1 = get_dummy_channel_update(starting_point);
508 let chan_upd_2 = get_dummy_channel_update(starting_point);
509 let chan_ann = get_dummy_channel_announcement(starting_point);
511 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
514 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
518 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
519 if !init_msg.features.supports_gossip_queries() {
523 #[allow(unused_mut, unused_assignments)]
524 let mut gossip_start_time = 0;
525 #[cfg(feature = "std")]
527 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
528 if self.request_full_sync.load(Ordering::Acquire) {
529 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
531 gossip_start_time -= 60 * 60; // an hour ago
535 let mut pending_events = self.pending_events.lock().unwrap();
536 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
537 node_id: their_node_id.clone(),
538 msg: msgs::GossipTimestampFilter {
539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
540 first_timestamp: gossip_start_time as u32,
541 timestamp_range: u32::max_value(),
547 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
551 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
555 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
559 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
563 fn provided_node_features(&self) -> NodeFeatures {
564 let mut features = NodeFeatures::empty();
565 features.set_gossip_queries_optional();
569 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
570 let mut features = InitFeatures::empty();
571 features.set_gossip_queries_optional();
575 fn processing_queue_high(&self) -> bool { false }
578 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
579 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
580 let mut ret = Vec::new();
581 let mut pending_events = self.pending_events.lock().unwrap();
582 core::mem::swap(&mut ret, &mut pending_events);
587 pub struct TestLogger {
589 pub(crate) id: String,
590 pub lines: Mutex<HashMap<(String, String), usize>>,
594 pub fn new() -> TestLogger {
595 Self::with_id("".to_owned())
597 pub fn with_id(id: String) -> TestLogger {
601 lines: Mutex::new(HashMap::new())
604 pub fn enable(&mut self, level: Level) {
607 pub fn assert_log(&self, module: String, line: String, count: usize) {
608 let log_entries = self.lines.lock().unwrap();
609 assert_eq!(log_entries.get(&(module, line)), Some(&count));
612 /// Search for the number of occurrence of the logged lines which
613 /// 1. belongs to the specified module and
614 /// 2. contains `line` in it.
615 /// And asserts if the number of occurrences is the same with the given `count`
616 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
617 let log_entries = self.lines.lock().unwrap();
618 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
619 m == &module && l.contains(line.as_str())
620 }).map(|(_, c) | { c }).sum();
624 /// Search for the number of occurrences of logged lines which
625 /// 1. belong to the specified module and
626 /// 2. match the given regex pattern.
627 /// Assert that the number of occurrences equals the given `count`
628 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
629 let log_entries = self.lines.lock().unwrap();
630 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
631 m == &module && pattern.is_match(&l)
632 }).map(|(_, c) | { c }).sum();
637 impl Logger for TestLogger {
638 fn log(&self, record: &Record) {
639 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
640 if record.level >= self.level {
641 #[cfg(feature = "std")]
642 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
647 pub struct TestNodeSigner {
648 node_secret: SecretKey,
651 impl TestNodeSigner {
652 pub fn new(node_secret: SecretKey) -> Self {
657 impl NodeSigner for TestNodeSigner {
658 fn get_inbound_payment_key_material(&self) -> crate::chain::keysinterface::KeyMaterial {
662 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
663 let node_secret = match recipient {
664 Recipient::Node => Ok(&self.node_secret),
665 Recipient::PhantomNode => Err(())
667 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
670 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
671 let mut node_secret = match recipient {
672 Recipient::Node => Ok(self.node_secret.clone()),
673 Recipient::PhantomNode => Err(())
675 if let Some(tweak) = tweak {
676 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
678 Ok(SharedSecret::new(other_key, &node_secret))
681 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
685 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
690 pub struct TestKeysInterface {
691 pub backing: keysinterface::PhantomKeysManager,
692 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
693 pub disable_revocation_policy_check: bool,
694 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
695 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
698 impl EntropySource for TestKeysInterface {
699 fn get_secure_random_bytes(&self) -> [u8; 32] {
700 let override_random_bytes = self.override_random_bytes.lock().unwrap();
701 if let Some(bytes) = &*override_random_bytes {
704 self.backing.get_secure_random_bytes()
708 impl NodeSigner for TestKeysInterface {
709 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
710 self.backing.get_node_id(recipient)
713 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
714 self.backing.ecdh(recipient, other_key, tweak)
717 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
718 self.backing.get_inbound_payment_key_material()
721 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
722 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
725 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
726 self.backing.sign_gossip_message(msg)
730 impl SignerProvider for TestKeysInterface {
731 type Signer = EnforcingSigner;
733 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
734 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
737 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
738 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
739 let state = self.make_enforcement_state_cell(keys.commitment_seed);
740 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
743 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
744 let mut reader = io::Cursor::new(buffer);
746 let inner: InMemorySigner = Readable::read(&mut reader)?;
747 let state = self.make_enforcement_state_cell(inner.commitment_seed);
749 Ok(EnforcingSigner::new_with_revoked(
752 self.disable_revocation_policy_check
756 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
758 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
759 match &mut *self.expectations.lock().unwrap() {
760 None => self.backing.get_shutdown_scriptpubkey(),
761 Some(expectations) => match expectations.pop_front() {
762 None => panic!("Unexpected get_shutdown_scriptpubkey"),
763 Some(expectation) => expectation.returns,
769 impl TestKeysInterface {
770 pub fn new(seed: &[u8; 32], network: Network) -> Self {
771 let now = Duration::from_secs(genesis_block(network).header.time as u64);
773 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
774 override_random_bytes: Mutex::new(None),
775 disable_revocation_policy_check: false,
776 enforcement_states: Mutex::new(HashMap::new()),
777 expectations: Mutex::new(None),
781 /// Sets an expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] is
783 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
784 self.expectations.lock().unwrap()
785 .get_or_insert_with(|| VecDeque::new())
786 .push_back(expectation);
790 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
791 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
792 let state = self.make_enforcement_state_cell(keys.commitment_seed);
793 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
796 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
797 let mut states = self.enforcement_states.lock().unwrap();
798 if !states.contains_key(&commitment_seed) {
799 let state = EnforcementState::new();
800 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
802 let cell = states.get(&commitment_seed).unwrap();
807 pub(crate) fn panicking() -> bool {
808 #[cfg(feature = "std")]
809 let panicking = ::std::thread::panicking();
810 #[cfg(not(feature = "std"))]
811 let panicking = false;
815 impl Drop for TestKeysInterface {
821 if let Some(expectations) = &*self.expectations.lock().unwrap() {
822 if !expectations.is_empty() {
823 panic!("Unsatisfied expectations: {:?}", expectations);
829 /// An expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] was called and
830 /// returns a [`ShutdownScript`].
831 pub struct OnGetShutdownScriptpubkey {
832 /// A shutdown script used to close a channel.
833 pub returns: ShutdownScript,
836 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
837 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
838 f.debug_struct("OnGetShutdownScriptpubkey").finish()
842 pub struct TestChainSource {
843 pub genesis_hash: BlockHash,
844 pub utxo_ret: Mutex<UtxoResult>,
845 pub get_utxo_call_count: AtomicUsize,
846 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
847 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
850 impl TestChainSource {
851 pub fn new(network: Network) -> Self {
852 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
854 genesis_hash: genesis_block(network).block_hash(),
855 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
856 get_utxo_call_count: AtomicUsize::new(0),
857 watched_txn: Mutex::new(HashSet::new()),
858 watched_outputs: Mutex::new(HashSet::new()),
863 impl UtxoLookup for TestChainSource {
864 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
865 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
866 if self.genesis_hash != *genesis_hash {
867 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
870 self.utxo_ret.lock().unwrap().clone()
874 impl chain::Filter for TestChainSource {
875 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
876 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
879 fn register_output(&self, output: WatchedOutput) {
880 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
884 impl Drop for TestChainSource {
892 /// A scorer useful in testing, when the passage of time isn't a concern.
893 pub type TestScorer = FixedPenaltyScorer;