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
10 use crate::blinded_path::BlindedPath;
11 use crate::blinded_path::payment::ReceiveTlvs;
13 use crate::chain::WatchedOutput;
14 use crate::chain::chaininterface;
15 use crate::chain::chaininterface::ConfirmationTarget;
16 use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
17 use crate::chain::chainmonitor;
18 use crate::chain::chainmonitor::{MonitorUpdateId, UpdateOrigin};
19 use crate::chain::channelmonitor;
20 use crate::chain::channelmonitor::MonitorEvent;
21 use crate::chain::transaction::OutPoint;
22 use crate::routing::router::{CandidateRouteHop, FirstHopCandidate, PublicHopCandidate, PrivateHopCandidate};
25 use crate::events::bump_transaction::{WalletSource, Utxo};
26 use crate::ln::ChannelId;
27 use crate::ln::channelmanager::{ChannelDetails, self};
28 use crate::ln::chan_utils::CommitmentTransaction;
29 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
30 use crate::ln::{msgs, wire};
31 use crate::ln::msgs::LightningError;
32 use crate::ln::script::ShutdownScript;
33 use crate::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
34 use crate::offers::invoice_request::UnsignedInvoiceRequest;
35 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
36 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId, RoutingFees};
37 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
38 use crate::routing::router::{DefaultRouter, InFlightHtlcs, Path, Route, RouteParameters, RouteHintHop, Router, ScorerAccountingForInFlightHtlcs};
39 use crate::routing::scoring::{ChannelUsage, ScoreUpdate, ScoreLookUp};
40 use crate::sync::RwLock;
41 use crate::util::config::UserConfig;
42 use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
43 use crate::util::logger::{Logger, Level, Record};
44 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
45 use crate::util::persist::KVStore;
47 use bitcoin::blockdata::constants::ChainHash;
48 use bitcoin::blockdata::constants::genesis_block;
49 use bitcoin::blockdata::transaction::{Transaction, TxOut};
50 use bitcoin::blockdata::script::{Builder, Script, ScriptBuf};
51 use bitcoin::blockdata::opcodes;
52 use bitcoin::blockdata::block::Block;
53 use bitcoin::network::constants::Network;
54 use bitcoin::hash_types::{BlockHash, Txid};
55 use bitcoin::sighash::{SighashCache, EcdsaSighashType};
57 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, self};
58 use bitcoin::secp256k1::ecdh::SharedSecret;
59 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
60 use bitcoin::secp256k1::schnorr;
62 #[cfg(any(test, feature = "_test_utils"))]
66 use crate::prelude::*;
67 use core::cell::RefCell;
68 use core::time::Duration;
69 use crate::sync::{Mutex, Arc};
70 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
72 use bitcoin::bech32::u5;
73 use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
75 #[cfg(feature = "std")]
76 use std::time::{SystemTime, UNIX_EPOCH};
77 use bitcoin::psbt::PartiallySignedTransaction;
78 use bitcoin::Sequence;
80 pub fn pubkey(byte: u8) -> PublicKey {
81 let secp_ctx = Secp256k1::new();
82 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
85 pub fn privkey(byte: u8) -> SecretKey {
86 SecretKey::from_slice(&[byte; 32]).unwrap()
89 pub struct TestVecWriter(pub Vec<u8>);
90 impl Writer for TestVecWriter {
91 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
92 self.0.extend_from_slice(buf);
97 pub struct TestFeeEstimator {
98 pub sat_per_kw: Mutex<u32>,
100 impl chaininterface::FeeEstimator for TestFeeEstimator {
101 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
102 *self.sat_per_kw.lock().unwrap()
106 pub struct TestRouter<'a> {
107 pub router: DefaultRouter<
108 Arc<NetworkGraph<&'a TestLogger>>,
110 &'a RwLock<TestScorer>,
114 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
115 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
116 pub scorer: &'a RwLock<TestScorer>,
119 impl<'a> TestRouter<'a> {
121 network_graph: Arc<NetworkGraph<&'a TestLogger>>, logger: &'a TestLogger,
122 scorer: &'a RwLock<TestScorer>
125 router: DefaultRouter::new(network_graph.clone(), logger, [42u8; 32], scorer, ()),
127 next_routes: Mutex::new(VecDeque::new()),
132 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
133 let mut expected_routes = self.next_routes.lock().unwrap();
134 expected_routes.push_back((query, result));
138 impl<'a> Router for TestRouter<'a> {
140 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
141 inflight_htlcs: InFlightHtlcs
142 ) -> Result<Route, msgs::LightningError> {
143 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
144 assert_eq!(find_route_query, *params);
145 if let Ok(ref route) = find_route_res {
146 assert_eq!(route.route_params, Some(find_route_query));
147 let scorer = self.scorer.read().unwrap();
148 let scorer = ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs);
149 for path in &route.paths {
150 let mut aggregate_msat = 0u64;
151 let mut prev_hop_node = payer;
152 for (idx, hop) in path.hops.iter().rev().enumerate() {
153 aggregate_msat += hop.fee_msat;
154 let usage = ChannelUsage {
155 amount_msat: aggregate_msat,
156 inflight_htlc_msat: 0,
157 effective_capacity: EffectiveCapacity::Unknown,
160 if idx == path.hops.len() - 1 {
161 if let Some(first_hops) = first_hops {
162 if let Some(idx) = first_hops.iter().position(|h| h.get_outbound_payment_scid() == Some(hop.short_channel_id)) {
163 let node_id = NodeId::from_pubkey(payer);
164 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
165 details: first_hops[idx],
166 payer_node_id: &node_id,
168 scorer.channel_penalty_msat(&candidate, usage, &());
173 let network_graph = self.network_graph.read_only();
174 if let Some(channel) = network_graph.channel(hop.short_channel_id) {
175 let (directed, _) = channel.as_directed_to(&NodeId::from_pubkey(&hop.pubkey)).unwrap();
176 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
178 short_channel_id: hop.short_channel_id,
180 scorer.channel_penalty_msat(&candidate, usage, &());
182 let target_node_id = NodeId::from_pubkey(&hop.pubkey);
183 let route_hint = RouteHintHop {
184 src_node_id: *prev_hop_node,
185 short_channel_id: hop.short_channel_id,
186 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
187 cltv_expiry_delta: 0,
188 htlc_minimum_msat: None,
189 htlc_maximum_msat: None,
191 let candidate = CandidateRouteHop::PrivateHop(PrivateHopCandidate {
193 target_node_id: &target_node_id,
195 scorer.channel_penalty_msat(&candidate, usage, &());
197 prev_hop_node = &hop.pubkey;
201 return find_route_res;
204 self.router.find_route(payer, params, first_hops, inflight_htlcs)
207 fn create_blinded_payment_paths<
208 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
210 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
211 amount_msats: u64, entropy_source: &ES, secp_ctx: &Secp256k1<T>
212 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
213 self.router.create_blinded_payment_paths(
214 recipient, first_hops, tlvs, amount_msats, entropy_source, secp_ctx
219 impl<'a> MessageRouter for TestRouter<'a> {
221 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
222 ) -> Result<OnionMessagePath, ()> {
223 self.router.find_path(sender, peers, destination)
226 fn create_blinded_paths<
227 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
229 &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
230 secp_ctx: &Secp256k1<T>
231 ) -> Result<Vec<BlindedPath>, ()> {
232 self.router.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
236 impl<'a> Drop for TestRouter<'a> {
238 #[cfg(feature = "std")] {
239 if std::thread::panicking() {
243 assert!(self.next_routes.lock().unwrap().is_empty());
247 pub struct TestMessageRouter<'a> {
248 inner: DefaultMessageRouter<Arc<NetworkGraph<&'a TestLogger>>, &'a TestLogger>,
251 impl<'a> TestMessageRouter<'a> {
252 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>) -> Self {
253 Self { inner: DefaultMessageRouter::new(network_graph) }
257 impl<'a> MessageRouter for TestMessageRouter<'a> {
259 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
260 ) -> Result<OnionMessagePath, ()> {
261 self.inner.find_path(sender, peers, destination)
264 fn create_blinded_paths<
265 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
267 &self, recipient: PublicKey, peers: Vec<PublicKey>, entropy_source: &ES,
268 secp_ctx: &Secp256k1<T>
269 ) -> Result<Vec<BlindedPath>, ()> {
270 self.inner.create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
274 pub struct OnlyReadsKeysInterface {}
276 impl EntropySource for OnlyReadsKeysInterface {
277 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
279 impl SignerProvider for OnlyReadsKeysInterface {
280 type EcdsaSigner = TestChannelSigner;
282 type TaprootSigner = TestChannelSigner;
284 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
286 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { unreachable!(); }
288 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::EcdsaSigner, msgs::DecodeError> {
289 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
290 let state = Arc::new(Mutex::new(EnforcementState::new()));
292 Ok(TestChannelSigner::new_with_revoked(
299 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> { Err(()) }
300 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
303 pub struct TestChainMonitor<'a> {
304 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<TestChannelSigner>)>>,
305 pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
306 pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, MonitorUpdateId)>>,
307 pub chain_monitor: chainmonitor::ChainMonitor<TestChannelSigner, &'a TestChainSource, &'a dyn chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a dyn chainmonitor::Persist<TestChannelSigner>>,
308 pub keys_manager: &'a TestKeysInterface,
309 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
310 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
312 pub expect_channel_force_closed: Mutex<Option<(ChannelId, bool)>>,
313 /// If this is set to Some(), the next round trip serialization check will not hold after an
314 /// update_channel call (not watch_channel) for the given channel_id.
315 pub expect_monitor_round_trip_fail: Mutex<Option<ChannelId>>,
317 impl<'a> TestChainMonitor<'a> {
318 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a dyn chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a dyn chainmonitor::Persist<TestChannelSigner>, keys_manager: &'a TestKeysInterface) -> Self {
320 added_monitors: Mutex::new(Vec::new()),
321 monitor_updates: Mutex::new(HashMap::new()),
322 latest_monitor_update_id: Mutex::new(HashMap::new()),
323 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
325 expect_channel_force_closed: Mutex::new(None),
326 expect_monitor_round_trip_fail: Mutex::new(None),
330 pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) {
331 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
332 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
335 impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
336 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
337 // At every point where we get a monitor update, we should be able to send a useful monitor
338 // to a watchtower and disk...
339 let mut w = TestVecWriter(Vec::new());
340 monitor.write(&mut w).unwrap();
341 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
342 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
343 assert!(new_monitor == monitor);
344 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
345 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
346 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
347 self.chain_monitor.watch_channel(funding_txo, new_monitor)
350 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
351 // Every monitor update should survive roundtrip
352 let mut w = TestVecWriter(Vec::new());
353 update.write(&mut w).unwrap();
354 assert!(channelmonitor::ChannelMonitorUpdate::read(
355 &mut io::Cursor::new(&w.0)).unwrap() == *update);
357 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
359 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
360 assert_eq!(funding_txo.to_channel_id(), exp.0);
361 assert_eq!(update.updates.len(), 1);
362 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
363 assert_eq!(should_broadcast, exp.1);
367 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
368 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
369 let update_res = self.chain_monitor.update_channel(funding_txo, update);
370 // At every point where we get a monitor update, we should be able to send a useful monitor
371 // to a watchtower and disk...
372 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
374 monitor.write(&mut w).unwrap();
375 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
376 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
377 if let Some(chan_id) = self.expect_monitor_round_trip_fail.lock().unwrap().take() {
378 assert_eq!(chan_id, funding_txo.to_channel_id());
379 assert!(new_monitor != *monitor);
381 assert!(new_monitor == *monitor);
383 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
387 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
388 return self.chain_monitor.release_pending_monitor_events();
392 struct JusticeTxData {
393 justice_tx: Transaction,
395 commitment_number: u64,
398 pub(crate) struct WatchtowerPersister {
399 persister: TestPersister,
400 /// Upon a new commitment_signed, we'll get a
401 /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
402 /// amount, and commitment number so we can build the justice tx after our counterparty
404 unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
405 /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
406 /// tx which would be used to provide a watchtower with the data it needs.
407 watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
408 destination_script: ScriptBuf,
411 impl WatchtowerPersister {
413 pub(crate) fn new(destination_script: ScriptBuf) -> Self {
414 WatchtowerPersister {
415 persister: TestPersister::new(),
416 unsigned_justice_tx_data: Mutex::new(HashMap::new()),
417 watchtower_state: Mutex::new(HashMap::new()),
423 pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
424 -> Option<Transaction> {
425 self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
428 fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
429 -> Option<JusticeTxData> {
430 let trusted_tx = counterparty_commitment_tx.trust();
431 let output_idx = trusted_tx.revokeable_output_index()?;
432 let built_tx = trusted_tx.built_transaction();
433 let value = built_tx.transaction.output[output_idx as usize].value;
434 let justice_tx = trusted_tx.build_to_local_justice_tx(
435 FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
436 let commitment_number = counterparty_commitment_tx.commitment_number();
437 Some(JusticeTxData { justice_tx, value, commitment_number })
441 impl<Signer: sign::ecdsa::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
442 fn persist_new_channel(&self, funding_txo: OutPoint,
443 data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
444 ) -> chain::ChannelMonitorUpdateStatus {
445 let res = self.persister.persist_new_channel(funding_txo, data, id);
447 assert!(self.unsigned_justice_tx_data.lock().unwrap()
448 .insert(funding_txo, VecDeque::new()).is_none());
449 assert!(self.watchtower_state.lock().unwrap()
450 .insert(funding_txo, HashMap::new()).is_none());
452 let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
453 .expect("First and only call expects Some");
454 if let Some(justice_data)
455 = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
456 self.unsigned_justice_tx_data.lock().unwrap()
457 .get_mut(&funding_txo).unwrap()
458 .push_back(justice_data);
463 fn update_persisted_channel(
464 &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
465 data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
466 ) -> chain::ChannelMonitorUpdateStatus {
467 let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);
469 if let Some(update) = update {
470 let commitment_txs = data.counterparty_commitment_txs_from_update(update);
471 let justice_datas = commitment_txs.into_iter()
472 .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
473 let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
474 let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
475 channel_state.extend(justice_datas);
477 while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
479 let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
480 match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
481 Ok(signed_justice_tx) => {
482 let dup = self.watchtower_state.lock().unwrap()
483 .get_mut(&funding_txo).unwrap()
484 .insert(commitment_txid, signed_justice_tx);
485 assert!(dup.is_none());
486 channel_state.pop_front();
496 pub struct TestPersister {
497 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
499 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
500 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
501 /// MonitorUpdateId here.
502 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
503 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
504 /// MonitorUpdateId here.
505 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
508 pub fn new() -> Self {
510 update_rets: Mutex::new(VecDeque::new()),
511 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
512 offchain_monitor_updates: Mutex::new(HashMap::new()),
516 /// Queue an update status to return.
517 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
518 self.update_rets.lock().unwrap().push_back(next_ret);
521 impl<Signer: sign::ecdsa::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
522 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
523 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
526 chain::ChannelMonitorUpdateStatus::Completed
529 fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
530 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
531 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
534 let is_chain_sync = if let UpdateOrigin::ChainSync(_) = update_id.contents { true } else { false };
536 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
538 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
544 pub struct TestStore {
545 persisted_bytes: Mutex<HashMap<String, HashMap<String, Vec<u8>>>>,
550 pub fn new(read_only: bool) -> Self {
551 let persisted_bytes = Mutex::new(HashMap::new());
552 Self { persisted_bytes, read_only }
556 impl KVStore for TestStore {
557 fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result<Vec<u8>> {
558 let persisted_lock = self.persisted_bytes.lock().unwrap();
559 let prefixed = if secondary_namespace.is_empty() {
560 primary_namespace.to_string()
562 format!("{}/{}", primary_namespace, secondary_namespace)
565 if let Some(outer_ref) = persisted_lock.get(&prefixed) {
566 if let Some(inner_ref) = outer_ref.get(key) {
567 let bytes = inner_ref.clone();
570 Err(io::Error::new(io::ErrorKind::NotFound, "Key not found"))
573 Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found"))
577 fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> {
579 return Err(io::Error::new(
580 io::ErrorKind::PermissionDenied,
581 "Cannot modify read-only store",
584 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
586 let prefixed = if secondary_namespace.is_empty() {
587 primary_namespace.to_string()
589 format!("{}/{}", primary_namespace, secondary_namespace)
591 let outer_e = persisted_lock.entry(prefixed).or_insert(HashMap::new());
592 let mut bytes = Vec::new();
593 bytes.write_all(buf)?;
594 outer_e.insert(key.to_string(), bytes);
598 fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> {
600 return Err(io::Error::new(
601 io::ErrorKind::PermissionDenied,
602 "Cannot modify read-only store",
606 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
608 let prefixed = if secondary_namespace.is_empty() {
609 primary_namespace.to_string()
611 format!("{}/{}", primary_namespace, secondary_namespace)
613 if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) {
614 outer_ref.remove(&key.to_string());
620 fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> io::Result<Vec<String>> {
621 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
623 let prefixed = if secondary_namespace.is_empty() {
624 primary_namespace.to_string()
626 format!("{}/{}", primary_namespace, secondary_namespace)
628 match persisted_lock.entry(prefixed) {
629 hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()),
630 hash_map::Entry::Vacant(_) => Ok(Vec::new()),
635 pub struct TestBroadcaster {
636 pub txn_broadcasted: Mutex<Vec<Transaction>>,
637 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
640 impl TestBroadcaster {
641 pub fn new(network: Network) -> Self {
643 txn_broadcasted: Mutex::new(Vec::new()),
644 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
648 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
649 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
652 pub fn txn_broadcast(&self) -> Vec<Transaction> {
653 self.txn_broadcasted.lock().unwrap().split_off(0)
656 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
657 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
658 let mut seen = HashSet::new();
659 txn.retain(|tx| seen.insert(tx.txid()));
664 impl chaininterface::BroadcasterInterface for TestBroadcaster {
665 fn broadcast_transactions(&self, txs: &[&Transaction]) {
667 let lock_time = tx.lock_time.to_consensus_u32();
668 assert!(lock_time < 1_500_000_000);
669 if tx.lock_time.is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
670 for inp in tx.input.iter() {
671 if inp.sequence != Sequence::MAX {
672 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
677 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
678 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
682 pub struct TestChannelMessageHandler {
683 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
684 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
685 connected_peers: Mutex<HashSet<PublicKey>>,
686 pub message_fetch_counter: AtomicUsize,
687 chain_hash: ChainHash,
690 impl TestChannelMessageHandler {
691 pub fn new(chain_hash: ChainHash) -> Self {
692 TestChannelMessageHandler {
693 pending_events: Mutex::new(Vec::new()),
694 expected_recv_msgs: Mutex::new(None),
695 connected_peers: Mutex::new(HashSet::new()),
696 message_fetch_counter: AtomicUsize::new(0),
702 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
703 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
704 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
705 expected_msgs.as_mut().unwrap().push(ev);
708 fn received_msg(&self, _ev: wire::Message<()>) {
709 let mut msgs = self.expected_recv_msgs.lock().unwrap();
710 if msgs.is_none() { return; }
711 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
713 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
714 msgs.as_mut().unwrap().remove(0);
718 impl Drop for TestChannelMessageHandler {
720 #[cfg(feature = "std")]
722 let l = self.expected_recv_msgs.lock().unwrap();
723 if !std::thread::panicking() {
724 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
730 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
731 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
732 self.received_msg(wire::Message::OpenChannel(msg.clone()));
734 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
735 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
737 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
738 self.received_msg(wire::Message::FundingCreated(msg.clone()));
740 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
741 self.received_msg(wire::Message::FundingSigned(msg.clone()));
743 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
744 self.received_msg(wire::Message::ChannelReady(msg.clone()));
746 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
747 self.received_msg(wire::Message::Shutdown(msg.clone()));
749 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
750 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
752 fn handle_stfu(&self, _their_node_id: &PublicKey, msg: &msgs::Stfu) {
753 self.received_msg(wire::Message::Stfu(msg.clone()));
755 fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
756 self.received_msg(wire::Message::Splice(msg.clone()));
758 fn handle_splice_ack(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
759 self.received_msg(wire::Message::SpliceAck(msg.clone()));
761 fn handle_splice_locked(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
762 self.received_msg(wire::Message::SpliceLocked(msg.clone()));
764 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
765 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
767 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
768 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
770 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
771 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
773 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
774 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
776 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
777 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
779 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
780 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
782 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
783 self.received_msg(wire::Message::UpdateFee(msg.clone()));
785 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
786 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
788 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
789 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
791 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
792 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
794 fn peer_disconnected(&self, their_node_id: &PublicKey) {
795 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
797 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
798 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
799 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
800 // bother re-generating the expected Init message in all tests.
803 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
804 self.received_msg(wire::Message::Error(msg.clone()));
806 fn provided_node_features(&self) -> NodeFeatures {
807 channelmanager::provided_node_features(&UserConfig::default())
809 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
810 channelmanager::provided_init_features(&UserConfig::default())
813 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
814 Some(vec![self.chain_hash])
817 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
818 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
821 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
822 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
825 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
826 self.received_msg(wire::Message::TxAddInput(msg.clone()));
829 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
830 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
833 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
834 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
837 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
838 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
841 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
842 self.received_msg(wire::Message::TxComplete(msg.clone()));
845 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
846 self.received_msg(wire::Message::TxSignatures(msg.clone()));
849 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
850 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
853 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
854 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
857 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
858 self.received_msg(wire::Message::TxAbort(msg.clone()));
862 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
863 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
864 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
865 let mut pending_events = self.pending_events.lock().unwrap();
866 let mut ret = Vec::new();
867 mem::swap(&mut ret, &mut *pending_events);
872 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
873 use bitcoin::secp256k1::ffi::Signature as FFISignature;
874 let secp_ctx = Secp256k1::new();
875 let network = Network::Testnet;
876 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
877 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
878 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
879 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
880 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
881 features: ChannelFeatures::empty(),
882 chain_hash: ChainHash::using_genesis_block(network),
883 short_channel_id: short_chan_id,
884 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
885 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
886 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
887 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
888 excess_data: Vec::new(),
892 msgs::ChannelAnnouncement {
893 node_signature_1: Signature::from(FFISignature::new()),
894 node_signature_2: Signature::from(FFISignature::new()),
895 bitcoin_signature_1: Signature::from(FFISignature::new()),
896 bitcoin_signature_2: Signature::from(FFISignature::new()),
897 contents: unsigned_ann,
902 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
903 use bitcoin::secp256k1::ffi::Signature as FFISignature;
904 let network = Network::Testnet;
905 msgs::ChannelUpdate {
906 signature: Signature::from(unsafe { FFISignature::new() }),
907 contents: msgs::UnsignedChannelUpdate {
908 chain_hash: ChainHash::using_genesis_block(network),
909 short_channel_id: short_chan_id,
912 cltv_expiry_delta: 0,
913 htlc_minimum_msat: 0,
914 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
916 fee_proportional_millionths: 0,
922 pub struct TestRoutingMessageHandler {
923 pub chan_upds_recvd: AtomicUsize,
924 pub chan_anns_recvd: AtomicUsize,
925 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
926 pub request_full_sync: AtomicBool,
929 impl TestRoutingMessageHandler {
930 pub fn new() -> Self {
931 TestRoutingMessageHandler {
932 chan_upds_recvd: AtomicUsize::new(0),
933 chan_anns_recvd: AtomicUsize::new(0),
934 pending_events: Mutex::new(vec![]),
935 request_full_sync: AtomicBool::new(false),
939 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
940 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
941 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
943 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
944 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
945 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
947 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
948 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
949 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
951 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
952 let chan_upd_1 = get_dummy_channel_update(starting_point);
953 let chan_upd_2 = get_dummy_channel_update(starting_point);
954 let chan_ann = get_dummy_channel_announcement(starting_point);
956 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
959 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
963 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
964 if !init_msg.features.supports_gossip_queries() {
968 #[allow(unused_mut, unused_assignments)]
969 let mut gossip_start_time = 0;
970 #[cfg(feature = "std")]
972 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
973 if self.request_full_sync.load(Ordering::Acquire) {
974 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
976 gossip_start_time -= 60 * 60; // an hour ago
980 let mut pending_events = self.pending_events.lock().unwrap();
981 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
982 node_id: their_node_id.clone(),
983 msg: msgs::GossipTimestampFilter {
984 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
985 first_timestamp: gossip_start_time as u32,
986 timestamp_range: u32::max_value(),
992 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
996 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
1000 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
1004 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
1008 fn provided_node_features(&self) -> NodeFeatures {
1009 let mut features = NodeFeatures::empty();
1010 features.set_gossip_queries_optional();
1014 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
1015 let mut features = InitFeatures::empty();
1016 features.set_gossip_queries_optional();
1020 fn processing_queue_high(&self) -> bool { false }
1023 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
1024 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
1025 let mut ret = Vec::new();
1026 let mut pending_events = self.pending_events.lock().unwrap();
1027 core::mem::swap(&mut ret, &mut pending_events);
1032 pub struct TestLogger {
1034 pub(crate) id: String,
1035 pub lines: Mutex<HashMap<(&'static str, String), usize>>,
1036 pub context: Mutex<HashMap<(&'static str, Option<PublicKey>, Option<ChannelId>), usize>>,
1040 pub fn new() -> TestLogger {
1041 Self::with_id("".to_owned())
1043 pub fn with_id(id: String) -> TestLogger {
1045 level: Level::Trace,
1047 lines: Mutex::new(HashMap::new()),
1048 context: Mutex::new(HashMap::new()),
1051 pub fn enable(&mut self, level: Level) {
1054 pub fn assert_log(&self, module: &str, line: String, count: usize) {
1055 let log_entries = self.lines.lock().unwrap();
1056 assert_eq!(log_entries.get(&(module, line)), Some(&count));
1059 /// Search for the number of occurrence of the logged lines which
1060 /// 1. belongs to the specified module and
1061 /// 2. contains `line` in it.
1062 /// And asserts if the number of occurrences is the same with the given `count`
1063 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
1064 let log_entries = self.lines.lock().unwrap();
1065 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
1066 *m == module && l.contains(line)
1067 }).map(|(_, c) | { c }).sum();
1068 assert_eq!(l, count)
1071 /// Search for the number of occurrences of logged lines which
1072 /// 1. belong to the specified module and
1073 /// 2. match the given regex pattern.
1074 /// Assert that the number of occurrences equals the given `count`
1075 #[cfg(any(test, feature = "_test_utils"))]
1076 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
1077 let log_entries = self.lines.lock().unwrap();
1078 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
1079 *m == module && pattern.is_match(&l)
1080 }).map(|(_, c) | { c }).sum();
1081 assert_eq!(l, count)
1084 pub fn assert_log_context_contains(
1085 &self, module: &str, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>, count: usize
1087 let context_entries = self.context.lock().unwrap();
1088 let l = context_entries.get(&(module, peer_id, channel_id)).unwrap();
1089 assert_eq!(*l, count)
1093 impl Logger for TestLogger {
1094 fn log(&self, record: Record) {
1095 *self.lines.lock().unwrap().entry((record.module_path, format!("{}", record.args))).or_insert(0) += 1;
1096 *self.context.lock().unwrap().entry((record.module_path, record.peer_id, record.channel_id)).or_insert(0) += 1;
1097 if record.level >= self.level {
1098 #[cfg(all(not(ldk_bench), feature = "std"))] {
1099 let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line);
1100 println!("{:<55}{}", pfx, record.args);
1106 pub struct TestNodeSigner {
1107 node_secret: SecretKey,
1110 impl TestNodeSigner {
1111 pub fn new(node_secret: SecretKey) -> Self {
1112 Self { node_secret }
1116 impl NodeSigner for TestNodeSigner {
1117 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
1121 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1122 let node_secret = match recipient {
1123 Recipient::Node => Ok(&self.node_secret),
1124 Recipient::PhantomNode => Err(())
1126 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
1129 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
1130 let mut node_secret = match recipient {
1131 Recipient::Node => Ok(self.node_secret.clone()),
1132 Recipient::PhantomNode => Err(())
1134 if let Some(tweak) = tweak {
1135 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1137 Ok(SharedSecret::new(other_key, &node_secret))
1140 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
1144 fn sign_bolt12_invoice_request(
1145 &self, _invoice_request: &UnsignedInvoiceRequest
1146 ) -> Result<schnorr::Signature, ()> {
1150 fn sign_bolt12_invoice(
1151 &self, _invoice: &UnsignedBolt12Invoice,
1152 ) -> Result<schnorr::Signature, ()> {
1156 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1161 pub struct TestKeysInterface {
1162 pub backing: sign::PhantomKeysManager,
1163 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
1164 pub disable_revocation_policy_check: bool,
1165 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
1166 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
1169 impl EntropySource for TestKeysInterface {
1170 fn get_secure_random_bytes(&self) -> [u8; 32] {
1171 let override_random_bytes = self.override_random_bytes.lock().unwrap();
1172 if let Some(bytes) = &*override_random_bytes {
1175 self.backing.get_secure_random_bytes()
1179 impl NodeSigner for TestKeysInterface {
1180 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1181 self.backing.get_node_id(recipient)
1184 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1185 self.backing.ecdh(recipient, other_key, tweak)
1188 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
1189 self.backing.get_inbound_payment_key_material()
1192 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1193 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
1196 fn sign_bolt12_invoice_request(
1197 &self, invoice_request: &UnsignedInvoiceRequest
1198 ) -> Result<schnorr::Signature, ()> {
1199 self.backing.sign_bolt12_invoice_request(invoice_request)
1202 fn sign_bolt12_invoice(
1203 &self, invoice: &UnsignedBolt12Invoice,
1204 ) -> Result<schnorr::Signature, ()> {
1205 self.backing.sign_bolt12_invoice(invoice)
1208 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1209 self.backing.sign_gossip_message(msg)
1213 impl SignerProvider for TestKeysInterface {
1214 type EcdsaSigner = TestChannelSigner;
1216 type TaprootSigner = TestChannelSigner;
1218 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1219 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1222 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner {
1223 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
1224 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1225 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1228 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::EcdsaSigner, msgs::DecodeError> {
1229 let mut reader = io::Cursor::new(buffer);
1231 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
1232 let state = self.make_enforcement_state_cell(inner.commitment_seed);
1234 Ok(TestChannelSigner::new_with_revoked(
1237 self.disable_revocation_policy_check
1241 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> { self.backing.get_destination_script(channel_keys_id) }
1243 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1244 match &mut *self.expectations.lock().unwrap() {
1245 None => self.backing.get_shutdown_scriptpubkey(),
1246 Some(expectations) => match expectations.pop_front() {
1247 None => panic!("Unexpected get_shutdown_scriptpubkey"),
1248 Some(expectation) => Ok(expectation.returns),
1254 impl TestKeysInterface {
1255 pub fn new(seed: &[u8; 32], network: Network) -> Self {
1256 let now = Duration::from_secs(genesis_block(network).header.time as u64);
1258 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1259 override_random_bytes: Mutex::new(None),
1260 disable_revocation_policy_check: false,
1261 enforcement_states: Mutex::new(HashMap::new()),
1262 expectations: Mutex::new(None),
1266 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
1268 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
1269 self.expectations.lock().unwrap()
1270 .get_or_insert_with(|| VecDeque::new())
1271 .push_back(expectation);
1275 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner {
1276 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
1277 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1278 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1281 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
1282 let mut states = self.enforcement_states.lock().unwrap();
1283 if !states.contains_key(&commitment_seed) {
1284 let state = EnforcementState::new();
1285 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1287 let cell = states.get(&commitment_seed).unwrap();
1292 pub(crate) fn panicking() -> bool {
1293 #[cfg(feature = "std")]
1294 let panicking = ::std::thread::panicking();
1295 #[cfg(not(feature = "std"))]
1296 let panicking = false;
1300 impl Drop for TestKeysInterface {
1301 fn drop(&mut self) {
1306 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1307 if !expectations.is_empty() {
1308 panic!("Unsatisfied expectations: {:?}", expectations);
1314 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1315 /// returns a [`ShutdownScript`].
1316 pub struct OnGetShutdownScriptpubkey {
1317 /// A shutdown script used to close a channel.
1318 pub returns: ShutdownScript,
1321 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1322 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1323 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1327 pub struct TestChainSource {
1328 pub chain_hash: ChainHash,
1329 pub utxo_ret: Mutex<UtxoResult>,
1330 pub get_utxo_call_count: AtomicUsize,
1331 pub watched_txn: Mutex<HashSet<(Txid, ScriptBuf)>>,
1332 pub watched_outputs: Mutex<HashSet<(OutPoint, ScriptBuf)>>,
1335 impl TestChainSource {
1336 pub fn new(network: Network) -> Self {
1337 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1339 chain_hash: ChainHash::using_genesis_block(network),
1340 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1341 get_utxo_call_count: AtomicUsize::new(0),
1342 watched_txn: Mutex::new(HashSet::new()),
1343 watched_outputs: Mutex::new(HashSet::new()),
1348 impl UtxoLookup for TestChainSource {
1349 fn get_utxo(&self, chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
1350 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1351 if self.chain_hash != *chain_hash {
1352 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1355 self.utxo_ret.lock().unwrap().clone()
1359 impl chain::Filter for TestChainSource {
1360 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1361 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.into()));
1364 fn register_output(&self, output: WatchedOutput) {
1365 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1369 impl Drop for TestChainSource {
1370 fn drop(&mut self) {
1377 pub struct TestScorer {
1378 /// Stores a tuple of (scid, ChannelUsage)
1379 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1383 pub fn new() -> Self {
1385 scorer_expectations: RefCell::new(None),
1389 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1390 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1395 impl crate::util::ser::Writeable for TestScorer {
1396 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1399 impl ScoreLookUp for TestScorer {
1400 type ScoreParams = ();
1401 fn channel_penalty_msat(
1402 &self, candidate: &CandidateRouteHop, usage: ChannelUsage, _score_params: &Self::ScoreParams
1404 let short_channel_id = match candidate.globally_unique_short_channel_id() {
1408 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1409 match scorer_expectations.pop_front() {
1410 Some((scid, expectation)) => {
1411 assert_eq!(expectation, usage);
1412 assert_eq!(scid, short_channel_id);
1421 impl ScoreUpdate for TestScorer {
1422 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64, _duration_since_epoch: Duration) {}
1424 fn payment_path_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {}
1426 fn probe_failed(&mut self, _actual_path: &Path, _: u64, _duration_since_epoch: Duration) {}
1428 fn probe_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {}
1430 fn time_passed(&mut self, _duration_since_epoch: Duration) {}
1434 impl crate::routing::scoring::Score for TestScorer {}
1436 impl Drop for TestScorer {
1437 fn drop(&mut self) {
1438 #[cfg(feature = "std")] {
1439 if std::thread::panicking() {
1444 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1445 if !scorer_expectations.is_empty() {
1446 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1452 pub struct TestWalletSource {
1453 secret_key: SecretKey,
1454 utxos: RefCell<Vec<Utxo>>,
1455 secp: Secp256k1<bitcoin::secp256k1::All>,
1458 impl TestWalletSource {
1459 pub fn new(secret_key: SecretKey) -> Self {
1462 utxos: RefCell::new(Vec::new()),
1463 secp: Secp256k1::new(),
1467 pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1468 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1469 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1470 self.utxos.borrow_mut().push(utxo.clone());
1474 pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1475 let output = utxo.output.clone();
1476 self.utxos.borrow_mut().push(utxo);
1480 pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1481 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1485 impl WalletSource for TestWalletSource {
1486 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1487 Ok(self.utxos.borrow().clone())
1490 fn get_change_script(&self) -> Result<ScriptBuf, ()> {
1491 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1492 Ok(ScriptBuf::new_p2pkh(&public_key.pubkey_hash()))
1495 fn sign_psbt(&self, psbt: PartiallySignedTransaction) -> Result<Transaction, ()> {
1496 let mut tx = psbt.extract_tx();
1497 let utxos = self.utxos.borrow();
1498 for i in 0..tx.input.len() {
1499 if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1500 let sighash = SighashCache::new(&tx)
1501 .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1503 let sig = self.secp.sign_ecdsa(&(*sighash.as_raw_hash()).into(), &self.secret_key);
1504 let bitcoin_sig = bitcoin::ecdsa::Signature { sig, hash_ty: EcdsaSighashType::All };
1505 tx.input[i].script_sig = Builder::new()
1506 .push_slice(&bitcoin_sig.serialize())
1507 .push_slice(&self.secret_key.public_key(&self.secp).serialize())