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::{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::{find_route, 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 network_graph: Arc<NetworkGraph<&'a TestLogger>>,
108 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
109 pub scorer: &'a RwLock<TestScorer>,
112 impl<'a> TestRouter<'a> {
113 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a RwLock<TestScorer>) -> Self {
114 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
117 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
118 let mut expected_routes = self.next_routes.lock().unwrap();
119 expected_routes.push_back((query, result));
123 impl<'a> Router for TestRouter<'a> {
125 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
126 inflight_htlcs: InFlightHtlcs
127 ) -> Result<Route, msgs::LightningError> {
128 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
129 assert_eq!(find_route_query, *params);
130 if let Ok(ref route) = find_route_res {
131 assert_eq!(route.route_params, Some(find_route_query));
132 let scorer = self.scorer.read().unwrap();
133 let scorer = ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs);
134 for path in &route.paths {
135 let mut aggregate_msat = 0u64;
136 let mut prev_hop_node = payer;
137 for (idx, hop) in path.hops.iter().rev().enumerate() {
138 aggregate_msat += hop.fee_msat;
139 let usage = ChannelUsage {
140 amount_msat: aggregate_msat,
141 inflight_htlc_msat: 0,
142 effective_capacity: EffectiveCapacity::Unknown,
145 if idx == path.hops.len() - 1 {
146 if let Some(first_hops) = first_hops {
147 if let Some(idx) = first_hops.iter().position(|h| h.get_outbound_payment_scid() == Some(hop.short_channel_id)) {
148 let node_id = NodeId::from_pubkey(payer);
149 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
150 details: first_hops[idx],
151 payer_node_id: &node_id,
153 scorer.channel_penalty_msat(&candidate, usage, &());
158 let network_graph = self.network_graph.read_only();
159 if let Some(channel) = network_graph.channel(hop.short_channel_id) {
160 let (directed, _) = channel.as_directed_to(&NodeId::from_pubkey(&hop.pubkey)).unwrap();
161 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
163 short_channel_id: hop.short_channel_id,
165 scorer.channel_penalty_msat(&candidate, usage, &());
167 let target_node_id = NodeId::from_pubkey(&hop.pubkey);
168 let route_hint = RouteHintHop {
169 src_node_id: *prev_hop_node,
170 short_channel_id: hop.short_channel_id,
171 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
172 cltv_expiry_delta: 0,
173 htlc_minimum_msat: None,
174 htlc_maximum_msat: None,
176 let candidate = CandidateRouteHop::PrivateHop(PrivateHopCandidate {
178 target_node_id: &target_node_id,
180 scorer.channel_penalty_msat(&candidate, usage, &());
182 prev_hop_node = &hop.pubkey;
186 return find_route_res;
188 let logger = TestLogger::new();
190 payer, params, &self.network_graph, first_hops, &logger,
191 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read().unwrap(), &inflight_htlcs), &Default::default(),
196 fn create_blinded_payment_paths<
197 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
199 &self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
200 _amount_msats: u64, _entropy_source: &ES, _secp_ctx: &Secp256k1<T>
201 ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
206 impl<'a> MessageRouter for TestRouter<'a> {
208 &self, _sender: PublicKey, _peers: Vec<PublicKey>, _destination: Destination
209 ) -> Result<OnionMessagePath, ()> {
213 fn create_blinded_paths<
214 ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification
216 &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _entropy_source: &ES,
217 _secp_ctx: &Secp256k1<T>
218 ) -> Result<Vec<BlindedPath>, ()> {
223 impl<'a> Drop for TestRouter<'a> {
225 #[cfg(feature = "std")] {
226 if std::thread::panicking() {
230 assert!(self.next_routes.lock().unwrap().is_empty());
234 pub struct OnlyReadsKeysInterface {}
236 impl EntropySource for OnlyReadsKeysInterface {
237 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
239 impl SignerProvider for OnlyReadsKeysInterface {
240 type EcdsaSigner = TestChannelSigner;
242 type TaprootSigner = TestChannelSigner;
244 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
246 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { unreachable!(); }
248 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::EcdsaSigner, msgs::DecodeError> {
249 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
250 let state = Arc::new(Mutex::new(EnforcementState::new()));
252 Ok(TestChannelSigner::new_with_revoked(
259 fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> { Err(()) }
260 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
263 pub struct TestChainMonitor<'a> {
264 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<TestChannelSigner>)>>,
265 pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
266 pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, MonitorUpdateId)>>,
267 pub chain_monitor: chainmonitor::ChainMonitor<TestChannelSigner, &'a TestChainSource, &'a dyn chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a dyn chainmonitor::Persist<TestChannelSigner>>,
268 pub keys_manager: &'a TestKeysInterface,
269 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
270 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
272 pub expect_channel_force_closed: Mutex<Option<(ChannelId, bool)>>,
273 /// If this is set to Some(), the next round trip serialization check will not hold after an
274 /// update_channel call (not watch_channel) for the given channel_id.
275 pub expect_monitor_round_trip_fail: Mutex<Option<ChannelId>>,
277 impl<'a> TestChainMonitor<'a> {
278 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 {
280 added_monitors: Mutex::new(Vec::new()),
281 monitor_updates: Mutex::new(HashMap::new()),
282 latest_monitor_update_id: Mutex::new(HashMap::new()),
283 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
285 expect_channel_force_closed: Mutex::new(None),
286 expect_monitor_round_trip_fail: Mutex::new(None),
290 pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) {
291 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
292 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
295 impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
296 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
297 // At every point where we get a monitor update, we should be able to send a useful monitor
298 // to a watchtower and disk...
299 let mut w = TestVecWriter(Vec::new());
300 monitor.write(&mut w).unwrap();
301 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
302 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
303 assert!(new_monitor == monitor);
304 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
305 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
306 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
307 self.chain_monitor.watch_channel(funding_txo, new_monitor)
310 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
311 // Every monitor update should survive roundtrip
312 let mut w = TestVecWriter(Vec::new());
313 update.write(&mut w).unwrap();
314 assert!(channelmonitor::ChannelMonitorUpdate::read(
315 &mut io::Cursor::new(&w.0)).unwrap() == *update);
317 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
319 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
320 assert_eq!(funding_txo.to_channel_id(), exp.0);
321 assert_eq!(update.updates.len(), 1);
322 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
323 assert_eq!(should_broadcast, exp.1);
327 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
328 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
329 let update_res = self.chain_monitor.update_channel(funding_txo, update);
330 // At every point where we get a monitor update, we should be able to send a useful monitor
331 // to a watchtower and disk...
332 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
334 monitor.write(&mut w).unwrap();
335 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
336 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
337 if let Some(chan_id) = self.expect_monitor_round_trip_fail.lock().unwrap().take() {
338 assert_eq!(chan_id, funding_txo.to_channel_id());
339 assert!(new_monitor != *monitor);
341 assert!(new_monitor == *monitor);
343 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
347 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
348 return self.chain_monitor.release_pending_monitor_events();
352 struct JusticeTxData {
353 justice_tx: Transaction,
355 commitment_number: u64,
358 pub(crate) struct WatchtowerPersister {
359 persister: TestPersister,
360 /// Upon a new commitment_signed, we'll get a
361 /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
362 /// amount, and commitment number so we can build the justice tx after our counterparty
364 unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
365 /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
366 /// tx which would be used to provide a watchtower with the data it needs.
367 watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
368 destination_script: ScriptBuf,
371 impl WatchtowerPersister {
373 pub(crate) fn new(destination_script: ScriptBuf) -> Self {
374 WatchtowerPersister {
375 persister: TestPersister::new(),
376 unsigned_justice_tx_data: Mutex::new(HashMap::new()),
377 watchtower_state: Mutex::new(HashMap::new()),
383 pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
384 -> Option<Transaction> {
385 self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
388 fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
389 -> Option<JusticeTxData> {
390 let trusted_tx = counterparty_commitment_tx.trust();
391 let output_idx = trusted_tx.revokeable_output_index()?;
392 let built_tx = trusted_tx.built_transaction();
393 let value = built_tx.transaction.output[output_idx as usize].value;
394 let justice_tx = trusted_tx.build_to_local_justice_tx(
395 FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
396 let commitment_number = counterparty_commitment_tx.commitment_number();
397 Some(JusticeTxData { justice_tx, value, commitment_number })
401 impl<Signer: sign::ecdsa::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
402 fn persist_new_channel(&self, funding_txo: OutPoint,
403 data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
404 ) -> chain::ChannelMonitorUpdateStatus {
405 let res = self.persister.persist_new_channel(funding_txo, data, id);
407 assert!(self.unsigned_justice_tx_data.lock().unwrap()
408 .insert(funding_txo, VecDeque::new()).is_none());
409 assert!(self.watchtower_state.lock().unwrap()
410 .insert(funding_txo, HashMap::new()).is_none());
412 let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
413 .expect("First and only call expects Some");
414 if let Some(justice_data)
415 = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
416 self.unsigned_justice_tx_data.lock().unwrap()
417 .get_mut(&funding_txo).unwrap()
418 .push_back(justice_data);
423 fn update_persisted_channel(
424 &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
425 data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
426 ) -> chain::ChannelMonitorUpdateStatus {
427 let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);
429 if let Some(update) = update {
430 let commitment_txs = data.counterparty_commitment_txs_from_update(update);
431 let justice_datas = commitment_txs.into_iter()
432 .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
433 let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
434 let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
435 channel_state.extend(justice_datas);
437 while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
439 let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
440 match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
441 Ok(signed_justice_tx) => {
442 let dup = self.watchtower_state.lock().unwrap()
443 .get_mut(&funding_txo).unwrap()
444 .insert(commitment_txid, signed_justice_tx);
445 assert!(dup.is_none());
446 channel_state.pop_front();
456 pub struct TestPersister {
457 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
459 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
460 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
461 /// MonitorUpdateId here.
462 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
463 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
464 /// MonitorUpdateId here.
465 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
468 pub fn new() -> Self {
470 update_rets: Mutex::new(VecDeque::new()),
471 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
472 offchain_monitor_updates: Mutex::new(HashMap::new()),
476 /// Queue an update status to return.
477 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
478 self.update_rets.lock().unwrap().push_back(next_ret);
481 impl<Signer: sign::ecdsa::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
482 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
483 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
486 chain::ChannelMonitorUpdateStatus::Completed
489 fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
490 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
491 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
494 let is_chain_sync = if let UpdateOrigin::ChainSync(_) = update_id.contents { true } else { false };
496 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
498 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
504 pub struct TestStore {
505 persisted_bytes: Mutex<HashMap<String, HashMap<String, Vec<u8>>>>,
510 pub fn new(read_only: bool) -> Self {
511 let persisted_bytes = Mutex::new(HashMap::new());
512 Self { persisted_bytes, read_only }
516 impl KVStore for TestStore {
517 fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result<Vec<u8>> {
518 let persisted_lock = self.persisted_bytes.lock().unwrap();
519 let prefixed = if secondary_namespace.is_empty() {
520 primary_namespace.to_string()
522 format!("{}/{}", primary_namespace, secondary_namespace)
525 if let Some(outer_ref) = persisted_lock.get(&prefixed) {
526 if let Some(inner_ref) = outer_ref.get(key) {
527 let bytes = inner_ref.clone();
530 Err(io::Error::new(io::ErrorKind::NotFound, "Key not found"))
533 Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found"))
537 fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> {
539 return Err(io::Error::new(
540 io::ErrorKind::PermissionDenied,
541 "Cannot modify read-only store",
544 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
546 let prefixed = if secondary_namespace.is_empty() {
547 primary_namespace.to_string()
549 format!("{}/{}", primary_namespace, secondary_namespace)
551 let outer_e = persisted_lock.entry(prefixed).or_insert(HashMap::new());
552 let mut bytes = Vec::new();
553 bytes.write_all(buf)?;
554 outer_e.insert(key.to_string(), bytes);
558 fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> {
560 return Err(io::Error::new(
561 io::ErrorKind::PermissionDenied,
562 "Cannot modify read-only store",
566 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
568 let prefixed = if secondary_namespace.is_empty() {
569 primary_namespace.to_string()
571 format!("{}/{}", primary_namespace, secondary_namespace)
573 if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) {
574 outer_ref.remove(&key.to_string());
580 fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> io::Result<Vec<String>> {
581 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
583 let prefixed = if secondary_namespace.is_empty() {
584 primary_namespace.to_string()
586 format!("{}/{}", primary_namespace, secondary_namespace)
588 match persisted_lock.entry(prefixed) {
589 hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()),
590 hash_map::Entry::Vacant(_) => Ok(Vec::new()),
595 pub struct TestBroadcaster {
596 pub txn_broadcasted: Mutex<Vec<Transaction>>,
597 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
600 impl TestBroadcaster {
601 pub fn new(network: Network) -> Self {
603 txn_broadcasted: Mutex::new(Vec::new()),
604 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
608 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
609 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
612 pub fn txn_broadcast(&self) -> Vec<Transaction> {
613 self.txn_broadcasted.lock().unwrap().split_off(0)
616 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
617 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
618 let mut seen = HashSet::new();
619 txn.retain(|tx| seen.insert(tx.txid()));
624 impl chaininterface::BroadcasterInterface for TestBroadcaster {
625 fn broadcast_transactions(&self, txs: &[&Transaction]) {
627 let lock_time = tx.lock_time.to_consensus_u32();
628 assert!(lock_time < 1_500_000_000);
629 if tx.lock_time.is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
630 for inp in tx.input.iter() {
631 if inp.sequence != Sequence::MAX {
632 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
637 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
638 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
642 pub struct TestChannelMessageHandler {
643 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
644 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
645 connected_peers: Mutex<HashSet<PublicKey>>,
646 pub message_fetch_counter: AtomicUsize,
647 chain_hash: ChainHash,
650 impl TestChannelMessageHandler {
651 pub fn new(chain_hash: ChainHash) -> Self {
652 TestChannelMessageHandler {
653 pending_events: Mutex::new(Vec::new()),
654 expected_recv_msgs: Mutex::new(None),
655 connected_peers: Mutex::new(HashSet::new()),
656 message_fetch_counter: AtomicUsize::new(0),
662 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
663 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
664 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
665 expected_msgs.as_mut().unwrap().push(ev);
668 fn received_msg(&self, _ev: wire::Message<()>) {
669 let mut msgs = self.expected_recv_msgs.lock().unwrap();
670 if msgs.is_none() { return; }
671 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
673 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
674 msgs.as_mut().unwrap().remove(0);
678 impl Drop for TestChannelMessageHandler {
680 #[cfg(feature = "std")]
682 let l = self.expected_recv_msgs.lock().unwrap();
683 if !std::thread::panicking() {
684 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
690 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
691 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
692 self.received_msg(wire::Message::OpenChannel(msg.clone()));
694 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
695 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
697 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
698 self.received_msg(wire::Message::FundingCreated(msg.clone()));
700 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
701 self.received_msg(wire::Message::FundingSigned(msg.clone()));
703 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
704 self.received_msg(wire::Message::ChannelReady(msg.clone()));
706 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
707 self.received_msg(wire::Message::Shutdown(msg.clone()));
709 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
710 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
712 fn handle_stfu(&self, _their_node_id: &PublicKey, msg: &msgs::Stfu) {
713 self.received_msg(wire::Message::Stfu(msg.clone()));
715 fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
716 self.received_msg(wire::Message::Splice(msg.clone()));
718 fn handle_splice_ack(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
719 self.received_msg(wire::Message::SpliceAck(msg.clone()));
721 fn handle_splice_locked(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
722 self.received_msg(wire::Message::SpliceLocked(msg.clone()));
724 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
725 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
727 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
728 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
730 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
731 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
733 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
734 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
736 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
737 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
739 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
740 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
742 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
743 self.received_msg(wire::Message::UpdateFee(msg.clone()));
745 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
746 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
748 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
749 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
751 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
752 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
754 fn peer_disconnected(&self, their_node_id: &PublicKey) {
755 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
757 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
758 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
759 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
760 // bother re-generating the expected Init message in all tests.
763 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
764 self.received_msg(wire::Message::Error(msg.clone()));
766 fn provided_node_features(&self) -> NodeFeatures {
767 channelmanager::provided_node_features(&UserConfig::default())
769 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
770 channelmanager::provided_init_features(&UserConfig::default())
773 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
774 Some(vec![self.chain_hash])
777 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
778 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
781 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
782 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
785 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
786 self.received_msg(wire::Message::TxAddInput(msg.clone()));
789 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
790 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
793 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
794 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
797 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
798 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
801 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
802 self.received_msg(wire::Message::TxComplete(msg.clone()));
805 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
806 self.received_msg(wire::Message::TxSignatures(msg.clone()));
809 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
810 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
813 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
814 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
817 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
818 self.received_msg(wire::Message::TxAbort(msg.clone()));
822 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
823 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
824 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
825 let mut pending_events = self.pending_events.lock().unwrap();
826 let mut ret = Vec::new();
827 mem::swap(&mut ret, &mut *pending_events);
832 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
833 use bitcoin::secp256k1::ffi::Signature as FFISignature;
834 let secp_ctx = Secp256k1::new();
835 let network = Network::Testnet;
836 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
837 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
838 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
839 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
840 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
841 features: ChannelFeatures::empty(),
842 chain_hash: ChainHash::using_genesis_block(network),
843 short_channel_id: short_chan_id,
844 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
845 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
846 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
847 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
848 excess_data: Vec::new(),
852 msgs::ChannelAnnouncement {
853 node_signature_1: Signature::from(FFISignature::new()),
854 node_signature_2: Signature::from(FFISignature::new()),
855 bitcoin_signature_1: Signature::from(FFISignature::new()),
856 bitcoin_signature_2: Signature::from(FFISignature::new()),
857 contents: unsigned_ann,
862 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
863 use bitcoin::secp256k1::ffi::Signature as FFISignature;
864 let network = Network::Testnet;
865 msgs::ChannelUpdate {
866 signature: Signature::from(unsafe { FFISignature::new() }),
867 contents: msgs::UnsignedChannelUpdate {
868 chain_hash: ChainHash::using_genesis_block(network),
869 short_channel_id: short_chan_id,
872 cltv_expiry_delta: 0,
873 htlc_minimum_msat: 0,
874 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
876 fee_proportional_millionths: 0,
882 pub struct TestRoutingMessageHandler {
883 pub chan_upds_recvd: AtomicUsize,
884 pub chan_anns_recvd: AtomicUsize,
885 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
886 pub request_full_sync: AtomicBool,
889 impl TestRoutingMessageHandler {
890 pub fn new() -> Self {
891 TestRoutingMessageHandler {
892 chan_upds_recvd: AtomicUsize::new(0),
893 chan_anns_recvd: AtomicUsize::new(0),
894 pending_events: Mutex::new(vec![]),
895 request_full_sync: AtomicBool::new(false),
899 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
900 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
901 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
903 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
904 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
905 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
907 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
908 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
909 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
911 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
912 let chan_upd_1 = get_dummy_channel_update(starting_point);
913 let chan_upd_2 = get_dummy_channel_update(starting_point);
914 let chan_ann = get_dummy_channel_announcement(starting_point);
916 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
919 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
923 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
924 if !init_msg.features.supports_gossip_queries() {
928 #[allow(unused_mut, unused_assignments)]
929 let mut gossip_start_time = 0;
930 #[cfg(feature = "std")]
932 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
933 if self.request_full_sync.load(Ordering::Acquire) {
934 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
936 gossip_start_time -= 60 * 60; // an hour ago
940 let mut pending_events = self.pending_events.lock().unwrap();
941 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
942 node_id: their_node_id.clone(),
943 msg: msgs::GossipTimestampFilter {
944 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
945 first_timestamp: gossip_start_time as u32,
946 timestamp_range: u32::max_value(),
952 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
956 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
960 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
964 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
968 fn provided_node_features(&self) -> NodeFeatures {
969 let mut features = NodeFeatures::empty();
970 features.set_gossip_queries_optional();
974 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
975 let mut features = InitFeatures::empty();
976 features.set_gossip_queries_optional();
980 fn processing_queue_high(&self) -> bool { false }
983 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
984 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
985 let mut ret = Vec::new();
986 let mut pending_events = self.pending_events.lock().unwrap();
987 core::mem::swap(&mut ret, &mut pending_events);
992 pub struct TestLogger {
994 pub(crate) id: String,
995 pub lines: Mutex<HashMap<(&'static str, String), usize>>,
996 pub context: Mutex<HashMap<(&'static str, Option<PublicKey>, Option<ChannelId>), usize>>,
1000 pub fn new() -> TestLogger {
1001 Self::with_id("".to_owned())
1003 pub fn with_id(id: String) -> TestLogger {
1005 level: Level::Trace,
1007 lines: Mutex::new(HashMap::new()),
1008 context: Mutex::new(HashMap::new()),
1011 pub fn enable(&mut self, level: Level) {
1014 pub fn assert_log(&self, module: &str, line: String, count: usize) {
1015 let log_entries = self.lines.lock().unwrap();
1016 assert_eq!(log_entries.get(&(module, line)), Some(&count));
1019 /// Search for the number of occurrence of the logged lines which
1020 /// 1. belongs to the specified module and
1021 /// 2. contains `line` in it.
1022 /// And asserts if the number of occurrences is the same with the given `count`
1023 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
1024 let log_entries = self.lines.lock().unwrap();
1025 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
1026 *m == module && l.contains(line)
1027 }).map(|(_, c) | { c }).sum();
1028 assert_eq!(l, count)
1031 /// Search for the number of occurrences of logged lines which
1032 /// 1. belong to the specified module and
1033 /// 2. match the given regex pattern.
1034 /// Assert that the number of occurrences equals the given `count`
1035 #[cfg(any(test, feature = "_test_utils"))]
1036 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
1037 let log_entries = self.lines.lock().unwrap();
1038 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
1039 *m == module && pattern.is_match(&l)
1040 }).map(|(_, c) | { c }).sum();
1041 assert_eq!(l, count)
1044 pub fn assert_log_context_contains(
1045 &self, module: &str, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>, count: usize
1047 let context_entries = self.context.lock().unwrap();
1048 let l = context_entries.get(&(module, peer_id, channel_id)).unwrap();
1049 assert_eq!(*l, count)
1053 impl Logger for TestLogger {
1054 fn log(&self, record: Record) {
1055 *self.lines.lock().unwrap().entry((record.module_path, format!("{}", record.args))).or_insert(0) += 1;
1056 *self.context.lock().unwrap().entry((record.module_path, record.peer_id, record.channel_id)).or_insert(0) += 1;
1057 if record.level >= self.level {
1058 #[cfg(all(not(ldk_bench), feature = "std"))] {
1059 let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line);
1060 println!("{:<55}{}", pfx, record.args);
1066 pub struct TestNodeSigner {
1067 node_secret: SecretKey,
1070 impl TestNodeSigner {
1071 pub fn new(node_secret: SecretKey) -> Self {
1072 Self { node_secret }
1076 impl NodeSigner for TestNodeSigner {
1077 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
1081 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1082 let node_secret = match recipient {
1083 Recipient::Node => Ok(&self.node_secret),
1084 Recipient::PhantomNode => Err(())
1086 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
1089 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
1090 let mut node_secret = match recipient {
1091 Recipient::Node => Ok(self.node_secret.clone()),
1092 Recipient::PhantomNode => Err(())
1094 if let Some(tweak) = tweak {
1095 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1097 Ok(SharedSecret::new(other_key, &node_secret))
1100 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
1104 fn sign_bolt12_invoice_request(
1105 &self, _invoice_request: &UnsignedInvoiceRequest
1106 ) -> Result<schnorr::Signature, ()> {
1110 fn sign_bolt12_invoice(
1111 &self, _invoice: &UnsignedBolt12Invoice,
1112 ) -> Result<schnorr::Signature, ()> {
1116 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1121 pub struct TestKeysInterface {
1122 pub backing: sign::PhantomKeysManager,
1123 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
1124 pub disable_revocation_policy_check: bool,
1125 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
1126 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
1129 impl EntropySource for TestKeysInterface {
1130 fn get_secure_random_bytes(&self) -> [u8; 32] {
1131 let override_random_bytes = self.override_random_bytes.lock().unwrap();
1132 if let Some(bytes) = &*override_random_bytes {
1135 self.backing.get_secure_random_bytes()
1139 impl NodeSigner for TestKeysInterface {
1140 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1141 self.backing.get_node_id(recipient)
1144 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1145 self.backing.ecdh(recipient, other_key, tweak)
1148 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
1149 self.backing.get_inbound_payment_key_material()
1152 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1153 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
1156 fn sign_bolt12_invoice_request(
1157 &self, invoice_request: &UnsignedInvoiceRequest
1158 ) -> Result<schnorr::Signature, ()> {
1159 self.backing.sign_bolt12_invoice_request(invoice_request)
1162 fn sign_bolt12_invoice(
1163 &self, invoice: &UnsignedBolt12Invoice,
1164 ) -> Result<schnorr::Signature, ()> {
1165 self.backing.sign_bolt12_invoice(invoice)
1168 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1169 self.backing.sign_gossip_message(msg)
1173 impl SignerProvider for TestKeysInterface {
1174 type EcdsaSigner = TestChannelSigner;
1176 type TaprootSigner = TestChannelSigner;
1178 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1179 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1182 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner {
1183 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
1184 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1185 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1188 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::EcdsaSigner, msgs::DecodeError> {
1189 let mut reader = io::Cursor::new(buffer);
1191 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
1192 let state = self.make_enforcement_state_cell(inner.commitment_seed);
1194 Ok(TestChannelSigner::new_with_revoked(
1197 self.disable_revocation_policy_check
1201 fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> { self.backing.get_destination_script(channel_keys_id) }
1203 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1204 match &mut *self.expectations.lock().unwrap() {
1205 None => self.backing.get_shutdown_scriptpubkey(),
1206 Some(expectations) => match expectations.pop_front() {
1207 None => panic!("Unexpected get_shutdown_scriptpubkey"),
1208 Some(expectation) => Ok(expectation.returns),
1214 impl TestKeysInterface {
1215 pub fn new(seed: &[u8; 32], network: Network) -> Self {
1216 let now = Duration::from_secs(genesis_block(network).header.time as u64);
1218 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1219 override_random_bytes: Mutex::new(None),
1220 disable_revocation_policy_check: false,
1221 enforcement_states: Mutex::new(HashMap::new()),
1222 expectations: Mutex::new(None),
1226 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
1228 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
1229 self.expectations.lock().unwrap()
1230 .get_or_insert_with(|| VecDeque::new())
1231 .push_back(expectation);
1235 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner {
1236 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
1237 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1238 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1241 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
1242 let mut states = self.enforcement_states.lock().unwrap();
1243 if !states.contains_key(&commitment_seed) {
1244 let state = EnforcementState::new();
1245 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1247 let cell = states.get(&commitment_seed).unwrap();
1252 pub(crate) fn panicking() -> bool {
1253 #[cfg(feature = "std")]
1254 let panicking = ::std::thread::panicking();
1255 #[cfg(not(feature = "std"))]
1256 let panicking = false;
1260 impl Drop for TestKeysInterface {
1261 fn drop(&mut self) {
1266 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1267 if !expectations.is_empty() {
1268 panic!("Unsatisfied expectations: {:?}", expectations);
1274 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1275 /// returns a [`ShutdownScript`].
1276 pub struct OnGetShutdownScriptpubkey {
1277 /// A shutdown script used to close a channel.
1278 pub returns: ShutdownScript,
1281 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1282 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1283 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1287 pub struct TestChainSource {
1288 pub chain_hash: ChainHash,
1289 pub utxo_ret: Mutex<UtxoResult>,
1290 pub get_utxo_call_count: AtomicUsize,
1291 pub watched_txn: Mutex<HashSet<(Txid, ScriptBuf)>>,
1292 pub watched_outputs: Mutex<HashSet<(OutPoint, ScriptBuf)>>,
1295 impl TestChainSource {
1296 pub fn new(network: Network) -> Self {
1297 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1299 chain_hash: ChainHash::using_genesis_block(network),
1300 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1301 get_utxo_call_count: AtomicUsize::new(0),
1302 watched_txn: Mutex::new(HashSet::new()),
1303 watched_outputs: Mutex::new(HashSet::new()),
1308 impl UtxoLookup for TestChainSource {
1309 fn get_utxo(&self, chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
1310 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1311 if self.chain_hash != *chain_hash {
1312 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1315 self.utxo_ret.lock().unwrap().clone()
1319 impl chain::Filter for TestChainSource {
1320 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1321 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.into()));
1324 fn register_output(&self, output: WatchedOutput) {
1325 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1329 impl Drop for TestChainSource {
1330 fn drop(&mut self) {
1337 pub struct TestScorer {
1338 /// Stores a tuple of (scid, ChannelUsage)
1339 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1343 pub fn new() -> Self {
1345 scorer_expectations: RefCell::new(None),
1349 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1350 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1355 impl crate::util::ser::Writeable for TestScorer {
1356 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1359 impl ScoreLookUp for TestScorer {
1360 type ScoreParams = ();
1361 fn channel_penalty_msat(
1362 &self, candidate: &CandidateRouteHop, usage: ChannelUsage, _score_params: &Self::ScoreParams
1364 let short_channel_id = match candidate.globally_unique_short_channel_id() {
1368 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1369 match scorer_expectations.pop_front() {
1370 Some((scid, expectation)) => {
1371 assert_eq!(expectation, usage);
1372 assert_eq!(scid, short_channel_id);
1381 impl ScoreUpdate for TestScorer {
1382 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64, _duration_since_epoch: Duration) {}
1384 fn payment_path_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {}
1386 fn probe_failed(&mut self, _actual_path: &Path, _: u64, _duration_since_epoch: Duration) {}
1388 fn probe_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {}
1390 fn time_passed(&mut self, _duration_since_epoch: Duration) {}
1393 impl Drop for TestScorer {
1394 fn drop(&mut self) {
1395 #[cfg(feature = "std")] {
1396 if std::thread::panicking() {
1401 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1402 if !scorer_expectations.is_empty() {
1403 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1409 pub struct TestWalletSource {
1410 secret_key: SecretKey,
1411 utxos: RefCell<Vec<Utxo>>,
1412 secp: Secp256k1<bitcoin::secp256k1::All>,
1415 impl TestWalletSource {
1416 pub fn new(secret_key: SecretKey) -> Self {
1419 utxos: RefCell::new(Vec::new()),
1420 secp: Secp256k1::new(),
1424 pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1425 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1426 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1427 self.utxos.borrow_mut().push(utxo.clone());
1431 pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1432 let output = utxo.output.clone();
1433 self.utxos.borrow_mut().push(utxo);
1437 pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1438 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1442 impl WalletSource for TestWalletSource {
1443 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1444 Ok(self.utxos.borrow().clone())
1447 fn get_change_script(&self) -> Result<ScriptBuf, ()> {
1448 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1449 Ok(ScriptBuf::new_p2pkh(&public_key.pubkey_hash()))
1452 fn sign_psbt(&self, psbt: PartiallySignedTransaction) -> Result<Transaction, ()> {
1453 let mut tx = psbt.extract_tx();
1454 let utxos = self.utxos.borrow();
1455 for i in 0..tx.input.len() {
1456 if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1457 let sighash = SighashCache::new(&tx)
1458 .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1460 let sig = self.secp.sign_ecdsa(&(*sighash.as_raw_hash()).into(), &self.secret_key);
1461 let bitcoin_sig = bitcoin::ecdsa::Signature { sig, hash_ty: EcdsaSighashType::All };
1462 tx.input[i].script_sig = Builder::new()
1463 .push_slice(&bitcoin_sig.serialize())
1464 .push_slice(&self.secret_key.public_key(&self.secp).serialize())