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;
21 use crate::ln::channelmanager;
22 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
23 use crate::ln::{msgs, wire};
24 use crate::ln::msgs::LightningError;
25 use crate::ln::script::ShutdownScript;
26 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
27 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
28 use crate::routing::router::{find_route, InFlightHtlcs, Path, Route, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
29 use crate::routing::scoring::{ChannelUsage, Score};
30 use crate::util::config::UserConfig;
31 use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
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::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
59 #[cfg(feature = "std")]
60 use std::time::{SystemTime, UNIX_EPOCH};
61 use bitcoin::Sequence;
63 pub fn pubkey(byte: u8) -> PublicKey {
64 let secp_ctx = Secp256k1::new();
65 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
68 pub fn privkey(byte: u8) -> SecretKey {
69 SecretKey::from_slice(&[byte; 32]).unwrap()
72 pub struct TestVecWriter(pub Vec<u8>);
73 impl Writer for TestVecWriter {
74 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
75 self.0.extend_from_slice(buf);
80 pub struct TestFeeEstimator {
81 pub sat_per_kw: Mutex<u32>,
83 impl chaininterface::FeeEstimator for TestFeeEstimator {
84 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
85 *self.sat_per_kw.lock().unwrap()
89 pub struct TestRouter<'a> {
90 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
91 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
92 pub scorer: &'a Mutex<TestScorer>,
95 impl<'a> TestRouter<'a> {
96 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a Mutex<TestScorer>) -> Self {
97 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
100 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
101 let mut expected_routes = self.next_routes.lock().unwrap();
102 expected_routes.push_back((query, result));
106 impl<'a> Router for TestRouter<'a> {
108 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
109 inflight_htlcs: &InFlightHtlcs
110 ) -> Result<Route, msgs::LightningError> {
111 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
112 assert_eq!(find_route_query, *params);
113 if let Ok(ref route) = find_route_res {
114 let locked_scorer = self.scorer.lock().unwrap();
115 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer, inflight_htlcs);
116 for path in &route.paths {
117 let mut aggregate_msat = 0u64;
118 for (idx, hop) in path.hops.iter().rev().enumerate() {
119 aggregate_msat += hop.fee_msat;
120 let usage = ChannelUsage {
121 amount_msat: aggregate_msat,
122 inflight_htlc_msat: 0,
123 effective_capacity: EffectiveCapacity::Unknown,
126 // Since the path is reversed, the last element in our iteration is the first
128 if idx == path.hops.len() - 1 {
129 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &());
131 let curr_hop_path_idx = path.hops.len() - 1 - idx;
132 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path.hops[curr_hop_path_idx - 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage, &());
137 return find_route_res;
139 let logger = TestLogger::new();
140 let scorer = self.scorer.lock().unwrap();
142 payer, params, &self.network_graph, first_hops, &logger,
143 &ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs), &(),
149 impl<'a> Drop for TestRouter<'a> {
151 #[cfg(feature = "std")] {
152 if std::thread::panicking() {
156 assert!(self.next_routes.lock().unwrap().is_empty());
160 pub struct OnlyReadsKeysInterface {}
162 impl EntropySource for OnlyReadsKeysInterface {
163 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
165 impl SignerProvider for OnlyReadsKeysInterface {
166 type Signer = EnforcingSigner;
168 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
170 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
172 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
173 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
174 let state = Arc::new(Mutex::new(EnforcementState::new()));
176 Ok(EnforcingSigner::new_with_revoked(
183 fn get_destination_script(&self) -> Result<Script, ()> { Err(()) }
184 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
187 pub struct TestChainMonitor<'a> {
188 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
189 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
190 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
191 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
192 pub keys_manager: &'a TestKeysInterface,
193 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
194 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
196 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
198 impl<'a> TestChainMonitor<'a> {
199 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 {
201 added_monitors: Mutex::new(Vec::new()),
202 monitor_updates: Mutex::new(HashMap::new()),
203 latest_monitor_update_id: Mutex::new(HashMap::new()),
204 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
206 expect_channel_force_closed: Mutex::new(None),
210 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
211 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
212 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
215 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
216 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
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 mut w = TestVecWriter(Vec::new());
220 monitor.write(&mut w).unwrap();
221 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
222 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
223 assert!(new_monitor == monitor);
224 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
225 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
226 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
227 self.chain_monitor.watch_channel(funding_txo, new_monitor)
230 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
231 // Every monitor update should survive roundtrip
232 let mut w = TestVecWriter(Vec::new());
233 update.write(&mut w).unwrap();
234 assert!(channelmonitor::ChannelMonitorUpdate::read(
235 &mut io::Cursor::new(&w.0)).unwrap() == *update);
237 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
239 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
240 assert_eq!(funding_txo.to_channel_id(), exp.0);
241 assert_eq!(update.updates.len(), 1);
242 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
243 assert_eq!(should_broadcast, exp.1);
247 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
248 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
249 let update_res = self.chain_monitor.update_channel(funding_txo, update);
250 // At every point where we get a monitor update, we should be able to send a useful monitor
251 // to a watchtower and disk...
252 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
254 monitor.write(&mut w).unwrap();
255 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
256 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
257 assert!(new_monitor == *monitor);
258 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
262 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
263 return self.chain_monitor.release_pending_monitor_events();
267 pub struct TestPersister {
268 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
270 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
271 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
272 /// MonitorUpdateId here.
273 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
274 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
275 /// MonitorUpdateId here.
276 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
279 pub fn new() -> Self {
281 update_rets: Mutex::new(VecDeque::new()),
282 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
283 offchain_monitor_updates: Mutex::new(HashMap::new()),
287 /// Queue an update status to return.
288 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
289 self.update_rets.lock().unwrap().push_back(next_ret);
292 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
293 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
294 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
297 chain::ChannelMonitorUpdateStatus::Completed
300 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
301 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
302 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
305 if update.is_none() {
306 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
308 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
314 pub struct TestBroadcaster {
315 pub txn_broadcasted: Mutex<Vec<Transaction>>,
316 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
319 impl TestBroadcaster {
320 pub fn new(network: Network) -> Self {
322 txn_broadcasted: Mutex::new(Vec::new()),
323 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
327 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
328 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
331 pub fn txn_broadcast(&self) -> Vec<Transaction> {
332 self.txn_broadcasted.lock().unwrap().split_off(0)
335 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
336 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
337 let mut seen = HashSet::new();
338 txn.retain(|tx| seen.insert(tx.txid()));
343 impl chaininterface::BroadcasterInterface for TestBroadcaster {
344 fn broadcast_transactions(&self, txs: &[&Transaction]) {
346 let lock_time = tx.lock_time.0;
347 assert!(lock_time < 1_500_000_000);
348 if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
349 for inp in tx.input.iter() {
350 if inp.sequence != Sequence::MAX {
351 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
356 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
357 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
361 pub struct TestChannelMessageHandler {
362 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
363 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
364 connected_peers: Mutex<HashSet<PublicKey>>,
367 impl TestChannelMessageHandler {
368 pub fn new() -> Self {
369 TestChannelMessageHandler {
370 pending_events: Mutex::new(Vec::new()),
371 expected_recv_msgs: Mutex::new(None),
372 connected_peers: Mutex::new(HashSet::new()),
377 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
378 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
379 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
380 expected_msgs.as_mut().unwrap().push(ev);
383 fn received_msg(&self, _ev: wire::Message<()>) {
384 let mut msgs = self.expected_recv_msgs.lock().unwrap();
385 if msgs.is_none() { return; }
386 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
388 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
389 msgs.as_mut().unwrap().remove(0);
393 impl Drop for TestChannelMessageHandler {
395 #[cfg(feature = "std")]
397 let l = self.expected_recv_msgs.lock().unwrap();
398 if !std::thread::panicking() {
399 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
405 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
406 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
407 self.received_msg(wire::Message::OpenChannel(msg.clone()));
409 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
410 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
412 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
413 self.received_msg(wire::Message::FundingCreated(msg.clone()));
415 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
416 self.received_msg(wire::Message::FundingSigned(msg.clone()));
418 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
419 self.received_msg(wire::Message::ChannelReady(msg.clone()));
421 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
422 self.received_msg(wire::Message::Shutdown(msg.clone()));
424 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
425 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
427 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
428 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
430 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
431 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
433 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
434 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
436 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
437 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
439 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
440 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
442 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
443 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
445 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
446 self.received_msg(wire::Message::UpdateFee(msg.clone()));
448 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
449 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
451 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
452 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
454 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
455 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
457 fn peer_disconnected(&self, their_node_id: &PublicKey) {
458 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
460 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
461 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
462 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
463 // bother re-generating the expected Init message in all tests.
466 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
467 self.received_msg(wire::Message::Error(msg.clone()));
469 fn provided_node_features(&self) -> NodeFeatures {
470 channelmanager::provided_node_features(&UserConfig::default())
472 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
473 channelmanager::provided_init_features(&UserConfig::default())
476 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
477 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
480 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
481 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
484 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
485 self.received_msg(wire::Message::TxAddInput(msg.clone()));
488 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
489 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
492 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
493 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
496 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
497 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
500 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
501 self.received_msg(wire::Message::TxComplete(msg.clone()));
504 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
505 self.received_msg(wire::Message::TxSignatures(msg.clone()));
508 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
509 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
512 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
513 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
516 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
517 self.received_msg(wire::Message::TxAbort(msg.clone()));
521 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
522 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
523 let mut pending_events = self.pending_events.lock().unwrap();
524 let mut ret = Vec::new();
525 mem::swap(&mut ret, &mut *pending_events);
530 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
531 use bitcoin::secp256k1::ffi::Signature as FFISignature;
532 let secp_ctx = Secp256k1::new();
533 let network = Network::Testnet;
534 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
535 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
536 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
537 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
538 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
539 features: ChannelFeatures::empty(),
540 chain_hash: genesis_block(network).header.block_hash(),
541 short_channel_id: short_chan_id,
542 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
543 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
544 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
545 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
546 excess_data: Vec::new(),
550 msgs::ChannelAnnouncement {
551 node_signature_1: Signature::from(FFISignature::new()),
552 node_signature_2: Signature::from(FFISignature::new()),
553 bitcoin_signature_1: Signature::from(FFISignature::new()),
554 bitcoin_signature_2: Signature::from(FFISignature::new()),
555 contents: unsigned_ann,
560 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
561 use bitcoin::secp256k1::ffi::Signature as FFISignature;
562 let network = Network::Testnet;
563 msgs::ChannelUpdate {
564 signature: Signature::from(unsafe { FFISignature::new() }),
565 contents: msgs::UnsignedChannelUpdate {
566 chain_hash: genesis_block(network).header.block_hash(),
567 short_channel_id: short_chan_id,
570 cltv_expiry_delta: 0,
571 htlc_minimum_msat: 0,
572 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
574 fee_proportional_millionths: 0,
580 pub struct TestRoutingMessageHandler {
581 pub chan_upds_recvd: AtomicUsize,
582 pub chan_anns_recvd: AtomicUsize,
583 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
584 pub request_full_sync: AtomicBool,
587 impl TestRoutingMessageHandler {
588 pub fn new() -> Self {
589 TestRoutingMessageHandler {
590 chan_upds_recvd: AtomicUsize::new(0),
591 chan_anns_recvd: AtomicUsize::new(0),
592 pending_events: Mutex::new(vec![]),
593 request_full_sync: AtomicBool::new(false),
597 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
598 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
599 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
601 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
602 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
603 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
605 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
606 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
607 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
609 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
610 let chan_upd_1 = get_dummy_channel_update(starting_point);
611 let chan_upd_2 = get_dummy_channel_update(starting_point);
612 let chan_ann = get_dummy_channel_announcement(starting_point);
614 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
617 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
621 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
622 if !init_msg.features.supports_gossip_queries() {
626 #[allow(unused_mut, unused_assignments)]
627 let mut gossip_start_time = 0;
628 #[cfg(feature = "std")]
630 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
631 if self.request_full_sync.load(Ordering::Acquire) {
632 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
634 gossip_start_time -= 60 * 60; // an hour ago
638 let mut pending_events = self.pending_events.lock().unwrap();
639 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
640 node_id: their_node_id.clone(),
641 msg: msgs::GossipTimestampFilter {
642 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
643 first_timestamp: gossip_start_time as u32,
644 timestamp_range: u32::max_value(),
650 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
654 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
658 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
662 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
666 fn provided_node_features(&self) -> NodeFeatures {
667 let mut features = NodeFeatures::empty();
668 features.set_gossip_queries_optional();
672 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
673 let mut features = InitFeatures::empty();
674 features.set_gossip_queries_optional();
678 fn processing_queue_high(&self) -> bool { false }
681 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
682 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
683 let mut ret = Vec::new();
684 let mut pending_events = self.pending_events.lock().unwrap();
685 core::mem::swap(&mut ret, &mut pending_events);
690 pub struct TestLogger {
692 pub(crate) id: String,
693 pub lines: Mutex<HashMap<(String, String), usize>>,
697 pub fn new() -> TestLogger {
698 Self::with_id("".to_owned())
700 pub fn with_id(id: String) -> TestLogger {
704 lines: Mutex::new(HashMap::new())
707 pub fn enable(&mut self, level: Level) {
710 pub fn assert_log(&self, module: String, line: String, count: usize) {
711 let log_entries = self.lines.lock().unwrap();
712 assert_eq!(log_entries.get(&(module, line)), Some(&count));
715 /// Search for the number of occurrence of the logged lines which
716 /// 1. belongs to the specified module and
717 /// 2. contains `line` in it.
718 /// And asserts if the number of occurrences is the same with the given `count`
719 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
720 let log_entries = self.lines.lock().unwrap();
721 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
722 m == module && l.contains(line)
723 }).map(|(_, c) | { c }).sum();
727 /// Search for the number of occurrences of logged lines which
728 /// 1. belong to the specified module and
729 /// 2. match the given regex pattern.
730 /// Assert that the number of occurrences equals the given `count`
731 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
732 let log_entries = self.lines.lock().unwrap();
733 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
734 m == module && pattern.is_match(&l)
735 }).map(|(_, c) | { c }).sum();
740 impl Logger for TestLogger {
741 fn log(&self, record: &Record) {
742 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
743 if record.level >= self.level {
744 #[cfg(all(not(ldk_bench), feature = "std"))]
745 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
750 pub struct TestNodeSigner {
751 node_secret: SecretKey,
754 impl TestNodeSigner {
755 pub fn new(node_secret: SecretKey) -> Self {
760 impl NodeSigner for TestNodeSigner {
761 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
765 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
766 let node_secret = match recipient {
767 Recipient::Node => Ok(&self.node_secret),
768 Recipient::PhantomNode => Err(())
770 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
773 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
774 let mut node_secret = match recipient {
775 Recipient::Node => Ok(self.node_secret.clone()),
776 Recipient::PhantomNode => Err(())
778 if let Some(tweak) = tweak {
779 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
781 Ok(SharedSecret::new(other_key, &node_secret))
784 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
788 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
793 pub struct TestKeysInterface {
794 pub backing: sign::PhantomKeysManager,
795 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
796 pub disable_revocation_policy_check: bool,
797 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
798 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
801 impl EntropySource for TestKeysInterface {
802 fn get_secure_random_bytes(&self) -> [u8; 32] {
803 let override_random_bytes = self.override_random_bytes.lock().unwrap();
804 if let Some(bytes) = &*override_random_bytes {
807 self.backing.get_secure_random_bytes()
811 impl NodeSigner for TestKeysInterface {
812 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
813 self.backing.get_node_id(recipient)
816 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
817 self.backing.ecdh(recipient, other_key, tweak)
820 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
821 self.backing.get_inbound_payment_key_material()
824 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
825 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
828 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
829 self.backing.sign_gossip_message(msg)
833 impl SignerProvider for TestKeysInterface {
834 type Signer = EnforcingSigner;
836 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
837 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
840 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
841 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
842 let state = self.make_enforcement_state_cell(keys.commitment_seed);
843 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
846 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
847 let mut reader = io::Cursor::new(buffer);
849 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
850 let state = self.make_enforcement_state_cell(inner.commitment_seed);
852 Ok(EnforcingSigner::new_with_revoked(
855 self.disable_revocation_policy_check
859 fn get_destination_script(&self) -> Result<Script, ()> { self.backing.get_destination_script() }
861 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
862 match &mut *self.expectations.lock().unwrap() {
863 None => self.backing.get_shutdown_scriptpubkey(),
864 Some(expectations) => match expectations.pop_front() {
865 None => panic!("Unexpected get_shutdown_scriptpubkey"),
866 Some(expectation) => Ok(expectation.returns),
872 impl TestKeysInterface {
873 pub fn new(seed: &[u8; 32], network: Network) -> Self {
874 let now = Duration::from_secs(genesis_block(network).header.time as u64);
876 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
877 override_random_bytes: Mutex::new(None),
878 disable_revocation_policy_check: false,
879 enforcement_states: Mutex::new(HashMap::new()),
880 expectations: Mutex::new(None),
884 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
886 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
887 self.expectations.lock().unwrap()
888 .get_or_insert_with(|| VecDeque::new())
889 .push_back(expectation);
893 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
894 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
895 let state = self.make_enforcement_state_cell(keys.commitment_seed);
896 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
899 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
900 let mut states = self.enforcement_states.lock().unwrap();
901 if !states.contains_key(&commitment_seed) {
902 let state = EnforcementState::new();
903 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
905 let cell = states.get(&commitment_seed).unwrap();
910 pub(crate) fn panicking() -> bool {
911 #[cfg(feature = "std")]
912 let panicking = ::std::thread::panicking();
913 #[cfg(not(feature = "std"))]
914 let panicking = false;
918 impl Drop for TestKeysInterface {
924 if let Some(expectations) = &*self.expectations.lock().unwrap() {
925 if !expectations.is_empty() {
926 panic!("Unsatisfied expectations: {:?}", expectations);
932 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
933 /// returns a [`ShutdownScript`].
934 pub struct OnGetShutdownScriptpubkey {
935 /// A shutdown script used to close a channel.
936 pub returns: ShutdownScript,
939 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
940 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
941 f.debug_struct("OnGetShutdownScriptpubkey").finish()
945 pub struct TestChainSource {
946 pub genesis_hash: BlockHash,
947 pub utxo_ret: Mutex<UtxoResult>,
948 pub get_utxo_call_count: AtomicUsize,
949 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
950 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
953 impl TestChainSource {
954 pub fn new(network: Network) -> Self {
955 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
957 genesis_hash: genesis_block(network).block_hash(),
958 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
959 get_utxo_call_count: AtomicUsize::new(0),
960 watched_txn: Mutex::new(HashSet::new()),
961 watched_outputs: Mutex::new(HashSet::new()),
966 impl UtxoLookup for TestChainSource {
967 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
968 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
969 if self.genesis_hash != *genesis_hash {
970 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
973 self.utxo_ret.lock().unwrap().clone()
977 impl chain::Filter for TestChainSource {
978 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
979 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
982 fn register_output(&self, output: WatchedOutput) {
983 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
987 impl Drop for TestChainSource {
995 pub struct TestScorer {
996 /// Stores a tuple of (scid, ChannelUsage)
997 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1001 pub fn new() -> Self {
1003 scorer_expectations: RefCell::new(None),
1007 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1008 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1013 impl crate::util::ser::Writeable for TestScorer {
1014 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1017 impl Score for TestScorer {
1018 type ScoreParams = ();
1019 fn channel_penalty_msat(
1020 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams
1022 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1023 match scorer_expectations.pop_front() {
1024 Some((scid, expectation)) => {
1025 assert_eq!(expectation, usage);
1026 assert_eq!(scid, short_channel_id);
1034 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {}
1036 fn payment_path_successful(&mut self, _actual_path: &Path) {}
1038 fn probe_failed(&mut self, _actual_path: &Path, _: u64) {}
1040 fn probe_successful(&mut self, _actual_path: &Path) {}
1043 impl Drop for TestScorer {
1044 fn drop(&mut self) {
1045 #[cfg(feature = "std")] {
1046 if std::thread::panicking() {
1051 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1052 if !scorer_expectations.is_empty() {
1053 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)