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::{EffectiveCapacity, 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::{ChannelUsage, Score};
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::cell::RefCell;
52 use core::time::Duration;
53 use crate::sync::{Mutex, Arc};
54 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
56 use bitcoin::bech32::u5;
57 use crate::chain::keysinterface::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
59 #[cfg(feature = "std")]
60 use std::time::{SystemTime, UNIX_EPOCH};
61 use bitcoin::Sequence;
63 pub struct TestVecWriter(pub Vec<u8>);
64 impl Writer for TestVecWriter {
65 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
66 self.0.extend_from_slice(buf);
71 pub struct TestFeeEstimator {
72 pub sat_per_kw: Mutex<u32>,
74 impl chaininterface::FeeEstimator for TestFeeEstimator {
75 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
76 *self.sat_per_kw.lock().unwrap()
80 pub struct TestRouter<'a> {
81 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
82 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
83 pub scorer: &'a Mutex<TestScorer>,
86 impl<'a> TestRouter<'a> {
87 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a Mutex<TestScorer>) -> Self {
88 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
91 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
92 let mut expected_routes = self.next_routes.lock().unwrap();
93 expected_routes.push_back((query, result));
97 impl<'a> Router for TestRouter<'a> {
99 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
100 inflight_htlcs: &InFlightHtlcs
101 ) -> Result<Route, msgs::LightningError> {
102 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
103 assert_eq!(find_route_query, *params);
104 if let Ok(ref route) = find_route_res {
105 let locked_scorer = self.scorer.lock().unwrap();
106 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer, inflight_htlcs);
107 for path in &route.paths {
108 let mut aggregate_msat = 0u64;
109 for (idx, hop) in path.iter().rev().enumerate() {
110 aggregate_msat += hop.fee_msat;
111 let usage = ChannelUsage {
112 amount_msat: aggregate_msat,
113 inflight_htlc_msat: 0,
114 effective_capacity: EffectiveCapacity::Unknown,
117 // Since the path is reversed, the last element in our iteration is the first
119 if idx == path.len() - 1 {
120 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
122 let curr_hop_path_idx = path.len() - 1 - idx;
123 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[curr_hop_path_idx - 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
128 return find_route_res;
130 let logger = TestLogger::new();
131 let scorer = self.scorer.lock().unwrap();
133 payer, params, &self.network_graph, first_hops, &logger,
134 &ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs),
138 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
139 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
140 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
141 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
144 #[cfg(feature = "std")] // If we put this on the `if`, we get "attributes are not yet allowed on `if` expressions" on 1.41.1
145 impl<'a> Drop for TestRouter<'a> {
147 if std::thread::panicking() {
150 assert!(self.next_routes.lock().unwrap().is_empty());
154 pub struct OnlyReadsKeysInterface {}
156 impl EntropySource for OnlyReadsKeysInterface {
157 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
159 impl SignerProvider for OnlyReadsKeysInterface {
160 type Signer = EnforcingSigner;
162 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
164 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
166 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
167 let inner: InMemorySigner = Readable::read(&mut reader)?;
168 let state = Arc::new(Mutex::new(EnforcementState::new()));
170 Ok(EnforcingSigner::new_with_revoked(
177 fn get_destination_script(&self) -> Script { unreachable!(); }
178 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); }
181 pub struct TestChainMonitor<'a> {
182 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
183 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
184 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
185 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
186 pub keys_manager: &'a TestKeysInterface,
187 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
188 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
190 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
192 impl<'a> TestChainMonitor<'a> {
193 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 {
195 added_monitors: Mutex::new(Vec::new()),
196 monitor_updates: Mutex::new(HashMap::new()),
197 latest_monitor_update_id: Mutex::new(HashMap::new()),
198 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
200 expect_channel_force_closed: Mutex::new(None),
204 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
205 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
206 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
209 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
210 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
211 // At every point where we get a monitor update, we should be able to send a useful monitor
212 // to a watchtower and disk...
213 let mut w = TestVecWriter(Vec::new());
214 monitor.write(&mut w).unwrap();
215 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
216 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
217 assert!(new_monitor == monitor);
218 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
219 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
220 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
221 self.chain_monitor.watch_channel(funding_txo, new_monitor)
224 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
225 // Every monitor update should survive roundtrip
226 let mut w = TestVecWriter(Vec::new());
227 update.write(&mut w).unwrap();
228 assert!(channelmonitor::ChannelMonitorUpdate::read(
229 &mut io::Cursor::new(&w.0)).unwrap() == *update);
231 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
233 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
234 assert_eq!(funding_txo.to_channel_id(), exp.0);
235 assert_eq!(update.updates.len(), 1);
236 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
237 assert_eq!(should_broadcast, exp.1);
241 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
242 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
243 let update_res = self.chain_monitor.update_channel(funding_txo, update);
244 // At every point where we get a monitor update, we should be able to send a useful monitor
245 // to a watchtower and disk...
246 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
248 monitor.write(&mut w).unwrap();
249 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
250 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
251 assert!(new_monitor == *monitor);
252 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
256 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
257 return self.chain_monitor.release_pending_monitor_events();
261 pub struct TestPersister {
262 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
264 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
265 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
266 /// MonitorUpdateId here.
267 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
268 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
269 /// MonitorUpdateId here.
270 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
273 pub fn new() -> Self {
275 update_rets: Mutex::new(VecDeque::new()),
276 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
277 offchain_monitor_updates: Mutex::new(HashMap::new()),
281 /// Queue an update status to return.
282 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
283 self.update_rets.lock().unwrap().push_back(next_ret);
286 impl<Signer: keysinterface::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
287 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
288 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
291 chain::ChannelMonitorUpdateStatus::Completed
294 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
295 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
296 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
299 if update.is_none() {
300 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
302 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
308 pub struct TestBroadcaster {
309 pub txn_broadcasted: Mutex<Vec<Transaction>>,
310 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
313 impl TestBroadcaster {
314 pub fn new(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> TestBroadcaster {
315 TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks }
319 impl chaininterface::BroadcasterInterface for TestBroadcaster {
320 fn broadcast_transaction(&self, tx: &Transaction) {
321 let lock_time = tx.lock_time.0;
322 assert!(lock_time < 1_500_000_000);
323 if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 {
324 for inp in tx.input.iter() {
325 if inp.sequence != Sequence::MAX {
326 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
330 self.txn_broadcasted.lock().unwrap().push(tx.clone());
334 pub struct TestChannelMessageHandler {
335 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
336 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
339 impl TestChannelMessageHandler {
340 pub fn new() -> Self {
341 TestChannelMessageHandler {
342 pending_events: Mutex::new(Vec::new()),
343 expected_recv_msgs: Mutex::new(None),
348 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
349 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
350 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
351 expected_msgs.as_mut().unwrap().push(ev);
354 fn received_msg(&self, _ev: wire::Message<()>) {
355 let mut msgs = self.expected_recv_msgs.lock().unwrap();
356 if msgs.is_none() { return; }
357 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
359 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
360 msgs.as_mut().unwrap().remove(0);
364 impl Drop for TestChannelMessageHandler {
366 #[cfg(feature = "std")]
368 let l = self.expected_recv_msgs.lock().unwrap();
369 if !std::thread::panicking() {
370 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
376 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
377 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
378 self.received_msg(wire::Message::OpenChannel(msg.clone()));
380 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
381 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
383 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
384 self.received_msg(wire::Message::FundingCreated(msg.clone()));
386 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
387 self.received_msg(wire::Message::FundingSigned(msg.clone()));
389 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
390 self.received_msg(wire::Message::ChannelReady(msg.clone()));
392 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
393 self.received_msg(wire::Message::Shutdown(msg.clone()));
395 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
396 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
398 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
399 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
401 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
402 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
404 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
405 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
407 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
408 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
410 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
411 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
413 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
414 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
416 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
417 self.received_msg(wire::Message::UpdateFee(msg.clone()));
419 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
420 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
422 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
423 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
425 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
426 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
428 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
429 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> {
430 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
431 // bother re-generating the expected Init message in all tests.
434 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
435 self.received_msg(wire::Message::Error(msg.clone()));
437 fn provided_node_features(&self) -> NodeFeatures {
438 channelmanager::provided_node_features(&UserConfig::default())
440 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
441 channelmanager::provided_init_features(&UserConfig::default())
445 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
446 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
447 let mut pending_events = self.pending_events.lock().unwrap();
448 let mut ret = Vec::new();
449 mem::swap(&mut ret, &mut *pending_events);
454 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
455 use bitcoin::secp256k1::ffi::Signature as FFISignature;
456 let secp_ctx = Secp256k1::new();
457 let network = Network::Testnet;
458 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
459 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
460 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
461 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
462 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
463 features: ChannelFeatures::empty(),
464 chain_hash: genesis_block(network).header.block_hash(),
465 short_channel_id: short_chan_id,
466 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
467 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
468 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
469 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
470 excess_data: Vec::new(),
474 msgs::ChannelAnnouncement {
475 node_signature_1: Signature::from(FFISignature::new()),
476 node_signature_2: Signature::from(FFISignature::new()),
477 bitcoin_signature_1: Signature::from(FFISignature::new()),
478 bitcoin_signature_2: Signature::from(FFISignature::new()),
479 contents: unsigned_ann,
484 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
485 use bitcoin::secp256k1::ffi::Signature as FFISignature;
486 let network = Network::Testnet;
487 msgs::ChannelUpdate {
488 signature: Signature::from(unsafe { FFISignature::new() }),
489 contents: msgs::UnsignedChannelUpdate {
490 chain_hash: genesis_block(network).header.block_hash(),
491 short_channel_id: short_chan_id,
494 cltv_expiry_delta: 0,
495 htlc_minimum_msat: 0,
496 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
498 fee_proportional_millionths: 0,
504 pub struct TestRoutingMessageHandler {
505 pub chan_upds_recvd: AtomicUsize,
506 pub chan_anns_recvd: AtomicUsize,
507 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
508 pub request_full_sync: AtomicBool,
511 impl TestRoutingMessageHandler {
512 pub fn new() -> Self {
513 TestRoutingMessageHandler {
514 chan_upds_recvd: AtomicUsize::new(0),
515 chan_anns_recvd: AtomicUsize::new(0),
516 pending_events: Mutex::new(vec![]),
517 request_full_sync: AtomicBool::new(false),
521 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
522 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
523 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
525 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
526 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
527 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
529 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
530 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
531 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
533 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
534 let chan_upd_1 = get_dummy_channel_update(starting_point);
535 let chan_upd_2 = get_dummy_channel_update(starting_point);
536 let chan_ann = get_dummy_channel_announcement(starting_point);
538 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
541 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
545 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> {
546 if !init_msg.features.supports_gossip_queries() {
550 #[allow(unused_mut, unused_assignments)]
551 let mut gossip_start_time = 0;
552 #[cfg(feature = "std")]
554 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
555 if self.request_full_sync.load(Ordering::Acquire) {
556 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
558 gossip_start_time -= 60 * 60; // an hour ago
562 let mut pending_events = self.pending_events.lock().unwrap();
563 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
564 node_id: their_node_id.clone(),
565 msg: msgs::GossipTimestampFilter {
566 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
567 first_timestamp: gossip_start_time as u32,
568 timestamp_range: u32::max_value(),
574 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
578 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
582 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
586 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
590 fn provided_node_features(&self) -> NodeFeatures {
591 let mut features = NodeFeatures::empty();
592 features.set_gossip_queries_optional();
596 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
597 let mut features = InitFeatures::empty();
598 features.set_gossip_queries_optional();
602 fn processing_queue_high(&self) -> bool { false }
605 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
606 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
607 let mut ret = Vec::new();
608 let mut pending_events = self.pending_events.lock().unwrap();
609 core::mem::swap(&mut ret, &mut pending_events);
614 pub struct TestLogger {
616 pub(crate) id: String,
617 pub lines: Mutex<HashMap<(String, String), usize>>,
621 pub fn new() -> TestLogger {
622 Self::with_id("".to_owned())
624 pub fn with_id(id: String) -> TestLogger {
628 lines: Mutex::new(HashMap::new())
631 pub fn enable(&mut self, level: Level) {
634 pub fn assert_log(&self, module: String, line: String, count: usize) {
635 let log_entries = self.lines.lock().unwrap();
636 assert_eq!(log_entries.get(&(module, line)), Some(&count));
639 /// Search for the number of occurrence of the logged lines which
640 /// 1. belongs to the specified module and
641 /// 2. contains `line` in it.
642 /// And asserts if the number of occurrences is the same with the given `count`
643 pub fn assert_log_contains(&self, module: String, line: String, count: usize) {
644 let log_entries = self.lines.lock().unwrap();
645 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
646 m == &module && l.contains(line.as_str())
647 }).map(|(_, c) | { c }).sum();
651 /// Search for the number of occurrences of logged lines which
652 /// 1. belong to the specified module and
653 /// 2. match the given regex pattern.
654 /// Assert that the number of occurrences equals the given `count`
655 pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) {
656 let log_entries = self.lines.lock().unwrap();
657 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
658 m == &module && pattern.is_match(&l)
659 }).map(|(_, c) | { c }).sum();
664 impl Logger for TestLogger {
665 fn log(&self, record: &Record) {
666 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
667 if record.level >= self.level {
668 #[cfg(feature = "std")]
669 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
674 pub struct TestNodeSigner {
675 node_secret: SecretKey,
678 impl TestNodeSigner {
679 pub fn new(node_secret: SecretKey) -> Self {
684 impl NodeSigner for TestNodeSigner {
685 fn get_inbound_payment_key_material(&self) -> crate::chain::keysinterface::KeyMaterial {
689 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
690 let node_secret = match recipient {
691 Recipient::Node => Ok(&self.node_secret),
692 Recipient::PhantomNode => Err(())
694 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
697 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
698 let mut node_secret = match recipient {
699 Recipient::Node => Ok(self.node_secret.clone()),
700 Recipient::PhantomNode => Err(())
702 if let Some(tweak) = tweak {
703 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
705 Ok(SharedSecret::new(other_key, &node_secret))
708 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
712 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
717 pub struct TestKeysInterface {
718 pub backing: keysinterface::PhantomKeysManager,
719 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
720 pub disable_revocation_policy_check: bool,
721 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
722 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
725 impl EntropySource for TestKeysInterface {
726 fn get_secure_random_bytes(&self) -> [u8; 32] {
727 let override_random_bytes = self.override_random_bytes.lock().unwrap();
728 if let Some(bytes) = &*override_random_bytes {
731 self.backing.get_secure_random_bytes()
735 impl NodeSigner for TestKeysInterface {
736 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
737 self.backing.get_node_id(recipient)
740 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
741 self.backing.ecdh(recipient, other_key, tweak)
744 fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial {
745 self.backing.get_inbound_payment_key_material()
748 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
749 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
752 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
753 self.backing.sign_gossip_message(msg)
757 impl SignerProvider for TestKeysInterface {
758 type Signer = EnforcingSigner;
760 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
761 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
764 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
765 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
766 let state = self.make_enforcement_state_cell(keys.commitment_seed);
767 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
770 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
771 let mut reader = io::Cursor::new(buffer);
773 let inner: InMemorySigner = Readable::read(&mut reader)?;
774 let state = self.make_enforcement_state_cell(inner.commitment_seed);
776 Ok(EnforcingSigner::new_with_revoked(
779 self.disable_revocation_policy_check
783 fn get_destination_script(&self) -> Script { self.backing.get_destination_script() }
785 fn get_shutdown_scriptpubkey(&self) -> ShutdownScript {
786 match &mut *self.expectations.lock().unwrap() {
787 None => self.backing.get_shutdown_scriptpubkey(),
788 Some(expectations) => match expectations.pop_front() {
789 None => panic!("Unexpected get_shutdown_scriptpubkey"),
790 Some(expectation) => expectation.returns,
796 impl TestKeysInterface {
797 pub fn new(seed: &[u8; 32], network: Network) -> Self {
798 let now = Duration::from_secs(genesis_block(network).header.time as u64);
800 backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
801 override_random_bytes: Mutex::new(None),
802 disable_revocation_policy_check: false,
803 enforcement_states: Mutex::new(HashMap::new()),
804 expectations: Mutex::new(None),
808 /// Sets an expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] is
810 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
811 self.expectations.lock().unwrap()
812 .get_or_insert_with(|| VecDeque::new())
813 .push_back(expectation);
817 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
818 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
819 let state = self.make_enforcement_state_cell(keys.commitment_seed);
820 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
823 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
824 let mut states = self.enforcement_states.lock().unwrap();
825 if !states.contains_key(&commitment_seed) {
826 let state = EnforcementState::new();
827 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
829 let cell = states.get(&commitment_seed).unwrap();
834 pub(crate) fn panicking() -> bool {
835 #[cfg(feature = "std")]
836 let panicking = ::std::thread::panicking();
837 #[cfg(not(feature = "std"))]
838 let panicking = false;
842 impl Drop for TestKeysInterface {
848 if let Some(expectations) = &*self.expectations.lock().unwrap() {
849 if !expectations.is_empty() {
850 panic!("Unsatisfied expectations: {:?}", expectations);
856 /// An expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] was called and
857 /// returns a [`ShutdownScript`].
858 pub struct OnGetShutdownScriptpubkey {
859 /// A shutdown script used to close a channel.
860 pub returns: ShutdownScript,
863 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
864 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
865 f.debug_struct("OnGetShutdownScriptpubkey").finish()
869 pub struct TestChainSource {
870 pub genesis_hash: BlockHash,
871 pub utxo_ret: Mutex<UtxoResult>,
872 pub get_utxo_call_count: AtomicUsize,
873 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
874 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
877 impl TestChainSource {
878 pub fn new(network: Network) -> Self {
879 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
881 genesis_hash: genesis_block(network).block_hash(),
882 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
883 get_utxo_call_count: AtomicUsize::new(0),
884 watched_txn: Mutex::new(HashSet::new()),
885 watched_outputs: Mutex::new(HashSet::new()),
890 impl UtxoLookup for TestChainSource {
891 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
892 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
893 if self.genesis_hash != *genesis_hash {
894 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
897 self.utxo_ret.lock().unwrap().clone()
901 impl chain::Filter for TestChainSource {
902 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
903 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
906 fn register_output(&self, output: WatchedOutput) {
907 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
911 impl Drop for TestChainSource {
919 pub struct TestScorer {
920 /// Stores a tuple of (scid, ChannelUsage)
921 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
925 pub fn new() -> Self {
927 scorer_expectations: RefCell::new(None),
931 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
932 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
937 impl crate::util::ser::Writeable for TestScorer {
938 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
941 impl Score for TestScorer {
942 fn channel_penalty_msat(
943 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
945 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
946 match scorer_expectations.pop_front() {
947 Some((scid, expectation)) => {
948 assert_eq!(expectation, usage);
949 assert_eq!(scid, short_channel_id);
957 fn payment_path_failed(&mut self, _actual_path: &[&RouteHop], _actual_short_channel_id: u64) {}
959 fn payment_path_successful(&mut self, _actual_path: &[&RouteHop]) {}
961 fn probe_failed(&mut self, _actual_path: &[&RouteHop], _: u64) {}
963 fn probe_successful(&mut self, _actual_path: &[&RouteHop]) {}
966 impl Drop for TestScorer {
968 #[cfg(feature = "std")] {
969 if std::thread::panicking() {
974 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
975 if !scorer_expectations.is_empty() {
976 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)