1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
11 use crate::chain::WatchedOutput;
12 use crate::chain::chaininterface;
13 use crate::chain::chaininterface::ConfirmationTarget;
14 use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
15 use crate::chain::chainmonitor;
16 use crate::chain::chainmonitor::{MonitorUpdateId, UpdateOrigin};
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::MonitorEvent;
19 use crate::chain::transaction::OutPoint;
22 use crate::events::bump_transaction::{WalletSource, Utxo};
23 use crate::ln::ChannelId;
24 use crate::ln::channelmanager;
25 use crate::ln::chan_utils::CommitmentTransaction;
26 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
27 use crate::ln::{msgs, wire};
28 use crate::ln::msgs::LightningError;
29 use crate::ln::script::ShutdownScript;
30 use crate::offers::invoice::UnsignedBolt12Invoice;
31 use crate::offers::invoice_request::UnsignedInvoiceRequest;
32 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
33 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
34 use crate::routing::router::{find_route, InFlightHtlcs, Path, Route, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
35 use crate::routing::scoring::{ChannelUsage, ScoreUpdate, ScoreLookUp};
36 use crate::sync::RwLock;
37 use crate::util::config::UserConfig;
38 use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
39 use crate::util::logger::{Logger, Level, Record};
40 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
41 use crate::util::persist::KVStore;
43 use bitcoin::EcdsaSighashType;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::blockdata::constants::genesis_block;
46 use bitcoin::blockdata::transaction::{Transaction, TxOut};
47 use bitcoin::blockdata::script::{Builder, Script};
48 use bitcoin::blockdata::opcodes;
49 use bitcoin::blockdata::block::Block;
50 use bitcoin::network::constants::Network;
51 use bitcoin::hash_types::{BlockHash, Txid};
52 use bitcoin::util::sighash::SighashCache;
54 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
55 use bitcoin::secp256k1::ecdh::SharedSecret;
56 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
57 use bitcoin::secp256k1::schnorr;
59 #[cfg(any(test, feature = "_test_utils"))]
63 use crate::prelude::*;
64 use core::cell::RefCell;
65 use core::time::Duration;
66 use crate::sync::{Mutex, Arc};
67 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
69 use bitcoin::bech32::u5;
70 use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
72 #[cfg(feature = "std")]
73 use std::time::{SystemTime, UNIX_EPOCH};
74 use bitcoin::Sequence;
76 pub fn pubkey(byte: u8) -> PublicKey {
77 let secp_ctx = Secp256k1::new();
78 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
81 pub fn privkey(byte: u8) -> SecretKey {
82 SecretKey::from_slice(&[byte; 32]).unwrap()
85 pub struct TestVecWriter(pub Vec<u8>);
86 impl Writer for TestVecWriter {
87 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
88 self.0.extend_from_slice(buf);
93 pub struct TestFeeEstimator {
94 pub sat_per_kw: Mutex<u32>,
96 impl chaininterface::FeeEstimator for TestFeeEstimator {
97 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
98 match confirmation_target {
99 ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => {
100 core::cmp::max(25 * 250, *self.sat_per_kw.lock().unwrap() * 10)
102 _ => *self.sat_per_kw.lock().unwrap(),
107 pub struct TestRouter<'a> {
108 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
109 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
110 pub scorer: &'a RwLock<TestScorer>,
113 impl<'a> TestRouter<'a> {
114 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a RwLock<TestScorer>) -> Self {
115 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
118 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
119 let mut expected_routes = self.next_routes.lock().unwrap();
120 expected_routes.push_back((query, result));
124 impl<'a> Router for TestRouter<'a> {
126 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
127 inflight_htlcs: InFlightHtlcs
128 ) -> Result<Route, msgs::LightningError> {
129 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
130 assert_eq!(find_route_query, *params);
131 if let Ok(ref route) = find_route_res {
132 assert_eq!(route.route_params, Some(find_route_query));
133 let scorer = self.scorer.read().unwrap();
134 let scorer = ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs);
135 for path in &route.paths {
136 let mut aggregate_msat = 0u64;
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 // Since the path is reversed, the last element in our iteration is the first
147 if idx == path.hops.len() - 1 {
148 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &Default::default());
150 let curr_hop_path_idx = path.hops.len() - 1 - idx;
151 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path.hops[curr_hop_path_idx - 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage, &Default::default());
156 return find_route_res;
158 let logger = TestLogger::new();
160 payer, params, &self.network_graph, first_hops, &logger,
161 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read().unwrap(), &inflight_htlcs), &Default::default(),
167 impl<'a> Drop for TestRouter<'a> {
169 #[cfg(feature = "std")] {
170 if std::thread::panicking() {
174 assert!(self.next_routes.lock().unwrap().is_empty());
178 pub struct OnlyReadsKeysInterface {}
180 impl EntropySource for OnlyReadsKeysInterface {
181 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
183 impl SignerProvider for OnlyReadsKeysInterface {
184 type Signer = TestChannelSigner;
186 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
188 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
190 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
191 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
192 let state = Arc::new(Mutex::new(EnforcementState::new()));
194 Ok(TestChannelSigner::new_with_revoked(
201 fn get_destination_script(&self) -> Result<Script, ()> { Err(()) }
202 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
205 pub struct TestChainMonitor<'a> {
206 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<TestChannelSigner>)>>,
207 pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
208 pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, MonitorUpdateId)>>,
209 pub chain_monitor: chainmonitor::ChainMonitor<TestChannelSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<TestChannelSigner>>,
210 pub keys_manager: &'a TestKeysInterface,
211 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
212 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
214 pub expect_channel_force_closed: Mutex<Option<(ChannelId, bool)>>,
215 /// If this is set to Some(), the next round trip serialization check will not hold after an
216 /// update_channel call (not watch_channel) for the given channel_id.
217 pub expect_monitor_round_trip_fail: Mutex<Option<ChannelId>>,
219 impl<'a> TestChainMonitor<'a> {
220 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<TestChannelSigner>, keys_manager: &'a TestKeysInterface) -> Self {
222 added_monitors: Mutex::new(Vec::new()),
223 monitor_updates: Mutex::new(HashMap::new()),
224 latest_monitor_update_id: Mutex::new(HashMap::new()),
225 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
227 expect_channel_force_closed: Mutex::new(None),
228 expect_monitor_round_trip_fail: Mutex::new(None),
232 pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) {
233 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
234 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
237 impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
238 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
239 // At every point where we get a monitor update, we should be able to send a useful monitor
240 // to a watchtower and disk...
241 let mut w = TestVecWriter(Vec::new());
242 monitor.write(&mut w).unwrap();
243 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
244 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
245 assert!(new_monitor == monitor);
246 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
247 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
248 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
249 self.chain_monitor.watch_channel(funding_txo, new_monitor)
252 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
253 // Every monitor update should survive roundtrip
254 let mut w = TestVecWriter(Vec::new());
255 update.write(&mut w).unwrap();
256 assert!(channelmonitor::ChannelMonitorUpdate::read(
257 &mut io::Cursor::new(&w.0)).unwrap() == *update);
259 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
261 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
262 assert_eq!(funding_txo.to_channel_id(), exp.0);
263 assert_eq!(update.updates.len(), 1);
264 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
265 assert_eq!(should_broadcast, exp.1);
269 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
270 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
271 let update_res = self.chain_monitor.update_channel(funding_txo, update);
272 // At every point where we get a monitor update, we should be able to send a useful monitor
273 // to a watchtower and disk...
274 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
276 monitor.write(&mut w).unwrap();
277 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
278 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
279 if let Some(chan_id) = self.expect_monitor_round_trip_fail.lock().unwrap().take() {
280 assert_eq!(chan_id, funding_txo.to_channel_id());
281 assert!(new_monitor != *monitor);
283 assert!(new_monitor == *monitor);
285 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
289 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
290 return self.chain_monitor.release_pending_monitor_events();
294 struct JusticeTxData {
295 justice_tx: Transaction,
297 commitment_number: u64,
300 pub(crate) struct WatchtowerPersister {
301 persister: TestPersister,
302 /// Upon a new commitment_signed, we'll get a
303 /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
304 /// amount, and commitment number so we can build the justice tx after our counterparty
306 unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
307 /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
308 /// tx which would be used to provide a watchtower with the data it needs.
309 watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
310 destination_script: Script,
313 impl WatchtowerPersister {
315 pub(crate) fn new(destination_script: Script) -> Self {
316 WatchtowerPersister {
317 persister: TestPersister::new(),
318 unsigned_justice_tx_data: Mutex::new(HashMap::new()),
319 watchtower_state: Mutex::new(HashMap::new()),
325 pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
326 -> Option<Transaction> {
327 self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
330 fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
331 -> Option<JusticeTxData> {
332 let trusted_tx = counterparty_commitment_tx.trust();
333 let output_idx = trusted_tx.revokeable_output_index()?;
334 let built_tx = trusted_tx.built_transaction();
335 let value = built_tx.transaction.output[output_idx as usize].value;
336 let justice_tx = trusted_tx.build_to_local_justice_tx(
337 FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
338 let commitment_number = counterparty_commitment_tx.commitment_number();
339 Some(JusticeTxData { justice_tx, value, commitment_number })
343 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
344 fn persist_new_channel(&self, funding_txo: OutPoint,
345 data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
346 ) -> chain::ChannelMonitorUpdateStatus {
347 let res = self.persister.persist_new_channel(funding_txo, data, id);
349 assert!(self.unsigned_justice_tx_data.lock().unwrap()
350 .insert(funding_txo, VecDeque::new()).is_none());
351 assert!(self.watchtower_state.lock().unwrap()
352 .insert(funding_txo, HashMap::new()).is_none());
354 let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
355 .expect("First and only call expects Some");
356 if let Some(justice_data)
357 = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
358 self.unsigned_justice_tx_data.lock().unwrap()
359 .get_mut(&funding_txo).unwrap()
360 .push_back(justice_data);
365 fn update_persisted_channel(
366 &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
367 data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
368 ) -> chain::ChannelMonitorUpdateStatus {
369 let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);
371 if let Some(update) = update {
372 let commitment_txs = data.counterparty_commitment_txs_from_update(update);
373 let justice_datas = commitment_txs.into_iter()
374 .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
375 let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
376 let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
377 channel_state.extend(justice_datas);
379 while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
381 let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
382 match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
383 Ok(signed_justice_tx) => {
384 let dup = self.watchtower_state.lock().unwrap()
385 .get_mut(&funding_txo).unwrap()
386 .insert(commitment_txid, signed_justice_tx);
387 assert!(dup.is_none());
388 channel_state.pop_front();
398 pub struct TestPersister {
399 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
401 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
402 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
403 /// MonitorUpdateId here.
404 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
405 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
406 /// MonitorUpdateId here.
407 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
410 pub fn new() -> Self {
412 update_rets: Mutex::new(VecDeque::new()),
413 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
414 offchain_monitor_updates: Mutex::new(HashMap::new()),
418 /// Queue an update status to return.
419 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
420 self.update_rets.lock().unwrap().push_back(next_ret);
423 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
424 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
425 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
428 chain::ChannelMonitorUpdateStatus::Completed
431 fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
432 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
433 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
436 let is_chain_sync = if let UpdateOrigin::ChainSync(_) = update_id.contents { true } else { false };
438 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
440 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
446 pub struct TestStore {
447 persisted_bytes: Mutex<HashMap<String, HashMap<String, Vec<u8>>>>,
452 pub fn new(read_only: bool) -> Self {
453 let persisted_bytes = Mutex::new(HashMap::new());
454 Self { persisted_bytes, read_only }
458 impl KVStore for TestStore {
459 fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result<Vec<u8>> {
460 let persisted_lock = self.persisted_bytes.lock().unwrap();
461 let prefixed = if secondary_namespace.is_empty() {
462 primary_namespace.to_string()
464 format!("{}/{}", primary_namespace, secondary_namespace)
467 if let Some(outer_ref) = persisted_lock.get(&prefixed) {
468 if let Some(inner_ref) = outer_ref.get(key) {
469 let bytes = inner_ref.clone();
472 Err(io::Error::new(io::ErrorKind::NotFound, "Key not found"))
475 Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found"))
479 fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> {
481 return Err(io::Error::new(
482 io::ErrorKind::PermissionDenied,
483 "Cannot modify read-only store",
486 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
488 let prefixed = if secondary_namespace.is_empty() {
489 primary_namespace.to_string()
491 format!("{}/{}", primary_namespace, secondary_namespace)
493 let outer_e = persisted_lock.entry(prefixed).or_insert(HashMap::new());
494 let mut bytes = Vec::new();
495 bytes.write_all(buf)?;
496 outer_e.insert(key.to_string(), bytes);
500 fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> {
502 return Err(io::Error::new(
503 io::ErrorKind::PermissionDenied,
504 "Cannot modify read-only store",
508 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
510 let prefixed = if secondary_namespace.is_empty() {
511 primary_namespace.to_string()
513 format!("{}/{}", primary_namespace, secondary_namespace)
515 if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) {
516 outer_ref.remove(&key.to_string());
522 fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> io::Result<Vec<String>> {
523 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
525 let prefixed = if secondary_namespace.is_empty() {
526 primary_namespace.to_string()
528 format!("{}/{}", primary_namespace, secondary_namespace)
530 match persisted_lock.entry(prefixed) {
531 hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()),
532 hash_map::Entry::Vacant(_) => Ok(Vec::new()),
537 pub struct TestBroadcaster {
538 pub txn_broadcasted: Mutex<Vec<Transaction>>,
539 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
542 impl TestBroadcaster {
543 pub fn new(network: Network) -> Self {
545 txn_broadcasted: Mutex::new(Vec::new()),
546 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
550 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
551 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
554 pub fn txn_broadcast(&self) -> Vec<Transaction> {
555 self.txn_broadcasted.lock().unwrap().split_off(0)
558 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
559 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
560 let mut seen = HashSet::new();
561 txn.retain(|tx| seen.insert(tx.txid()));
566 impl chaininterface::BroadcasterInterface for TestBroadcaster {
567 fn broadcast_transactions(&self, txs: &[&Transaction]) {
569 let lock_time = tx.lock_time.0;
570 assert!(lock_time < 1_500_000_000);
571 if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
572 for inp in tx.input.iter() {
573 if inp.sequence != Sequence::MAX {
574 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
579 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
580 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
584 pub struct TestChannelMessageHandler {
585 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
586 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
587 connected_peers: Mutex<HashSet<PublicKey>>,
588 pub message_fetch_counter: AtomicUsize,
589 chain_hash: ChainHash,
592 impl TestChannelMessageHandler {
593 pub fn new(chain_hash: ChainHash) -> Self {
594 TestChannelMessageHandler {
595 pending_events: Mutex::new(Vec::new()),
596 expected_recv_msgs: Mutex::new(None),
597 connected_peers: Mutex::new(HashSet::new()),
598 message_fetch_counter: AtomicUsize::new(0),
604 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
605 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
606 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
607 expected_msgs.as_mut().unwrap().push(ev);
610 fn received_msg(&self, _ev: wire::Message<()>) {
611 let mut msgs = self.expected_recv_msgs.lock().unwrap();
612 if msgs.is_none() { return; }
613 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
615 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
616 msgs.as_mut().unwrap().remove(0);
620 impl Drop for TestChannelMessageHandler {
622 #[cfg(feature = "std")]
624 let l = self.expected_recv_msgs.lock().unwrap();
625 if !std::thread::panicking() {
626 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
632 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
633 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
634 self.received_msg(wire::Message::OpenChannel(msg.clone()));
636 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
637 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
639 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
640 self.received_msg(wire::Message::FundingCreated(msg.clone()));
642 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
643 self.received_msg(wire::Message::FundingSigned(msg.clone()));
645 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
646 self.received_msg(wire::Message::ChannelReady(msg.clone()));
648 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
649 self.received_msg(wire::Message::Shutdown(msg.clone()));
651 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
652 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
654 fn handle_stfu(&self, _their_node_id: &PublicKey, msg: &msgs::Stfu) {
655 self.received_msg(wire::Message::Stfu(msg.clone()));
657 fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
658 self.received_msg(wire::Message::Splice(msg.clone()));
660 fn handle_splice_ack(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
661 self.received_msg(wire::Message::SpliceAck(msg.clone()));
663 fn handle_splice_locked(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
664 self.received_msg(wire::Message::SpliceLocked(msg.clone()));
666 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
667 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
669 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
670 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
672 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
673 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
675 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
676 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
678 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
679 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
681 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
682 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
684 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
685 self.received_msg(wire::Message::UpdateFee(msg.clone()));
687 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
688 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
690 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
691 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
693 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
694 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
696 fn peer_disconnected(&self, their_node_id: &PublicKey) {
697 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
699 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
700 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
701 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
702 // bother re-generating the expected Init message in all tests.
705 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
706 self.received_msg(wire::Message::Error(msg.clone()));
708 fn provided_node_features(&self) -> NodeFeatures {
709 channelmanager::provided_node_features(&UserConfig::default())
711 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
712 channelmanager::provided_init_features(&UserConfig::default())
715 fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
716 Some(vec![self.chain_hash])
719 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
720 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
723 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
724 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
727 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
728 self.received_msg(wire::Message::TxAddInput(msg.clone()));
731 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
732 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
735 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
736 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
739 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
740 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
743 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
744 self.received_msg(wire::Message::TxComplete(msg.clone()));
747 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
748 self.received_msg(wire::Message::TxSignatures(msg.clone()));
751 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
752 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
755 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
756 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
759 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
760 self.received_msg(wire::Message::TxAbort(msg.clone()));
764 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
765 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
766 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
767 let mut pending_events = self.pending_events.lock().unwrap();
768 let mut ret = Vec::new();
769 mem::swap(&mut ret, &mut *pending_events);
774 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
775 use bitcoin::secp256k1::ffi::Signature as FFISignature;
776 let secp_ctx = Secp256k1::new();
777 let network = Network::Testnet;
778 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
779 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
780 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
781 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
782 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
783 features: ChannelFeatures::empty(),
784 chain_hash: ChainHash::using_genesis_block(network),
785 short_channel_id: short_chan_id,
786 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
787 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
788 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
789 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
790 excess_data: Vec::new(),
794 msgs::ChannelAnnouncement {
795 node_signature_1: Signature::from(FFISignature::new()),
796 node_signature_2: Signature::from(FFISignature::new()),
797 bitcoin_signature_1: Signature::from(FFISignature::new()),
798 bitcoin_signature_2: Signature::from(FFISignature::new()),
799 contents: unsigned_ann,
804 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
805 use bitcoin::secp256k1::ffi::Signature as FFISignature;
806 let network = Network::Testnet;
807 msgs::ChannelUpdate {
808 signature: Signature::from(unsafe { FFISignature::new() }),
809 contents: msgs::UnsignedChannelUpdate {
810 chain_hash: ChainHash::using_genesis_block(network),
811 short_channel_id: short_chan_id,
814 cltv_expiry_delta: 0,
815 htlc_minimum_msat: 0,
816 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
818 fee_proportional_millionths: 0,
824 pub struct TestRoutingMessageHandler {
825 pub chan_upds_recvd: AtomicUsize,
826 pub chan_anns_recvd: AtomicUsize,
827 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
828 pub request_full_sync: AtomicBool,
831 impl TestRoutingMessageHandler {
832 pub fn new() -> Self {
833 TestRoutingMessageHandler {
834 chan_upds_recvd: AtomicUsize::new(0),
835 chan_anns_recvd: AtomicUsize::new(0),
836 pending_events: Mutex::new(vec![]),
837 request_full_sync: AtomicBool::new(false),
841 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
842 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
843 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
845 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
846 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
847 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
849 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
850 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
851 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
853 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
854 let chan_upd_1 = get_dummy_channel_update(starting_point);
855 let chan_upd_2 = get_dummy_channel_update(starting_point);
856 let chan_ann = get_dummy_channel_announcement(starting_point);
858 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
861 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
865 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
866 if !init_msg.features.supports_gossip_queries() {
870 #[allow(unused_mut, unused_assignments)]
871 let mut gossip_start_time = 0;
872 #[cfg(feature = "std")]
874 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
875 if self.request_full_sync.load(Ordering::Acquire) {
876 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
878 gossip_start_time -= 60 * 60; // an hour ago
882 let mut pending_events = self.pending_events.lock().unwrap();
883 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
884 node_id: their_node_id.clone(),
885 msg: msgs::GossipTimestampFilter {
886 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
887 first_timestamp: gossip_start_time as u32,
888 timestamp_range: u32::max_value(),
894 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
898 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
902 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
906 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
910 fn provided_node_features(&self) -> NodeFeatures {
911 let mut features = NodeFeatures::empty();
912 features.set_gossip_queries_optional();
916 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
917 let mut features = InitFeatures::empty();
918 features.set_gossip_queries_optional();
922 fn processing_queue_high(&self) -> bool { false }
925 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
926 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
927 let mut ret = Vec::new();
928 let mut pending_events = self.pending_events.lock().unwrap();
929 core::mem::swap(&mut ret, &mut pending_events);
934 pub struct TestLogger {
936 pub(crate) id: String,
937 pub lines: Mutex<HashMap<(String, String), usize>>,
941 pub fn new() -> TestLogger {
942 Self::with_id("".to_owned())
944 pub fn with_id(id: String) -> TestLogger {
948 lines: Mutex::new(HashMap::new())
951 pub fn enable(&mut self, level: Level) {
954 pub fn assert_log(&self, module: String, line: String, count: usize) {
955 let log_entries = self.lines.lock().unwrap();
956 assert_eq!(log_entries.get(&(module, line)), Some(&count));
959 /// Search for the number of occurrence of the logged lines which
960 /// 1. belongs to the specified module and
961 /// 2. contains `line` in it.
962 /// And asserts if the number of occurrences is the same with the given `count`
963 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
964 let log_entries = self.lines.lock().unwrap();
965 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
966 m == module && l.contains(line)
967 }).map(|(_, c) | { c }).sum();
971 /// Search for the number of occurrences of logged lines which
972 /// 1. belong to the specified module and
973 /// 2. match the given regex pattern.
974 /// Assert that the number of occurrences equals the given `count`
975 #[cfg(any(test, feature = "_test_utils"))]
976 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
977 let log_entries = self.lines.lock().unwrap();
978 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
979 m == module && pattern.is_match(&l)
980 }).map(|(_, c) | { c }).sum();
985 impl Logger for TestLogger {
986 fn log(&self, record: &Record) {
987 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
988 if record.level >= self.level {
989 #[cfg(all(not(ldk_bench), feature = "std"))] {
990 let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line);
991 println!("{:<55}{}", pfx, record.args);
997 pub struct TestNodeSigner {
998 node_secret: SecretKey,
1001 impl TestNodeSigner {
1002 pub fn new(node_secret: SecretKey) -> Self {
1003 Self { node_secret }
1007 impl NodeSigner for TestNodeSigner {
1008 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
1012 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1013 let node_secret = match recipient {
1014 Recipient::Node => Ok(&self.node_secret),
1015 Recipient::PhantomNode => Err(())
1017 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
1020 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
1021 let mut node_secret = match recipient {
1022 Recipient::Node => Ok(self.node_secret.clone()),
1023 Recipient::PhantomNode => Err(())
1025 if let Some(tweak) = tweak {
1026 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1028 Ok(SharedSecret::new(other_key, &node_secret))
1031 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
1035 fn sign_bolt12_invoice_request(
1036 &self, _invoice_request: &UnsignedInvoiceRequest
1037 ) -> Result<schnorr::Signature, ()> {
1041 fn sign_bolt12_invoice(
1042 &self, _invoice: &UnsignedBolt12Invoice,
1043 ) -> Result<schnorr::Signature, ()> {
1047 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1052 pub struct TestKeysInterface {
1053 pub backing: sign::PhantomKeysManager,
1054 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
1055 pub disable_revocation_policy_check: bool,
1056 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
1057 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
1060 impl EntropySource for TestKeysInterface {
1061 fn get_secure_random_bytes(&self) -> [u8; 32] {
1062 let override_random_bytes = self.override_random_bytes.lock().unwrap();
1063 if let Some(bytes) = &*override_random_bytes {
1066 self.backing.get_secure_random_bytes()
1070 impl NodeSigner for TestKeysInterface {
1071 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1072 self.backing.get_node_id(recipient)
1075 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1076 self.backing.ecdh(recipient, other_key, tweak)
1079 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
1080 self.backing.get_inbound_payment_key_material()
1083 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1084 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
1087 fn sign_bolt12_invoice_request(
1088 &self, invoice_request: &UnsignedInvoiceRequest
1089 ) -> Result<schnorr::Signature, ()> {
1090 self.backing.sign_bolt12_invoice_request(invoice_request)
1093 fn sign_bolt12_invoice(
1094 &self, invoice: &UnsignedBolt12Invoice,
1095 ) -> Result<schnorr::Signature, ()> {
1096 self.backing.sign_bolt12_invoice(invoice)
1099 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1100 self.backing.sign_gossip_message(msg)
1104 impl SignerProvider for TestKeysInterface {
1105 type Signer = TestChannelSigner;
1107 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1108 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1111 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner {
1112 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
1113 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1114 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1117 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
1118 let mut reader = io::Cursor::new(buffer);
1120 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
1121 let state = self.make_enforcement_state_cell(inner.commitment_seed);
1123 Ok(TestChannelSigner::new_with_revoked(
1126 self.disable_revocation_policy_check
1130 fn get_destination_script(&self) -> Result<Script, ()> { self.backing.get_destination_script() }
1132 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1133 match &mut *self.expectations.lock().unwrap() {
1134 None => self.backing.get_shutdown_scriptpubkey(),
1135 Some(expectations) => match expectations.pop_front() {
1136 None => panic!("Unexpected get_shutdown_scriptpubkey"),
1137 Some(expectation) => Ok(expectation.returns),
1143 impl TestKeysInterface {
1144 pub fn new(seed: &[u8; 32], network: Network) -> Self {
1145 let now = Duration::from_secs(genesis_block(network).header.time as u64);
1147 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1148 override_random_bytes: Mutex::new(None),
1149 disable_revocation_policy_check: false,
1150 enforcement_states: Mutex::new(HashMap::new()),
1151 expectations: Mutex::new(None),
1155 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
1157 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
1158 self.expectations.lock().unwrap()
1159 .get_or_insert_with(|| VecDeque::new())
1160 .push_back(expectation);
1164 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner {
1165 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
1166 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1167 TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1170 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
1171 let mut states = self.enforcement_states.lock().unwrap();
1172 if !states.contains_key(&commitment_seed) {
1173 let state = EnforcementState::new();
1174 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1176 let cell = states.get(&commitment_seed).unwrap();
1181 pub(crate) fn panicking() -> bool {
1182 #[cfg(feature = "std")]
1183 let panicking = ::std::thread::panicking();
1184 #[cfg(not(feature = "std"))]
1185 let panicking = false;
1189 impl Drop for TestKeysInterface {
1190 fn drop(&mut self) {
1195 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1196 if !expectations.is_empty() {
1197 panic!("Unsatisfied expectations: {:?}", expectations);
1203 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1204 /// returns a [`ShutdownScript`].
1205 pub struct OnGetShutdownScriptpubkey {
1206 /// A shutdown script used to close a channel.
1207 pub returns: ShutdownScript,
1210 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1211 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1212 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1216 pub struct TestChainSource {
1217 pub chain_hash: ChainHash,
1218 pub utxo_ret: Mutex<UtxoResult>,
1219 pub get_utxo_call_count: AtomicUsize,
1220 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
1221 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
1224 impl TestChainSource {
1225 pub fn new(network: Network) -> Self {
1226 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1228 chain_hash: ChainHash::using_genesis_block(network),
1229 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1230 get_utxo_call_count: AtomicUsize::new(0),
1231 watched_txn: Mutex::new(HashSet::new()),
1232 watched_outputs: Mutex::new(HashSet::new()),
1237 impl UtxoLookup for TestChainSource {
1238 fn get_utxo(&self, chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
1239 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1240 if self.chain_hash != *chain_hash {
1241 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1244 self.utxo_ret.lock().unwrap().clone()
1248 impl chain::Filter for TestChainSource {
1249 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1250 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
1253 fn register_output(&self, output: WatchedOutput) {
1254 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1258 impl Drop for TestChainSource {
1259 fn drop(&mut self) {
1266 pub struct TestScorer {
1267 /// Stores a tuple of (scid, ChannelUsage)
1268 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1272 pub fn new() -> Self {
1274 scorer_expectations: RefCell::new(None),
1278 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1279 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1284 impl crate::util::ser::Writeable for TestScorer {
1285 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1288 impl ScoreLookUp for TestScorer {
1289 type ScoreParams = ();
1290 fn channel_penalty_msat(
1291 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams
1293 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1294 match scorer_expectations.pop_front() {
1295 Some((scid, expectation)) => {
1296 assert_eq!(expectation, usage);
1297 assert_eq!(scid, short_channel_id);
1306 impl ScoreUpdate for TestScorer {
1307 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {}
1309 fn payment_path_successful(&mut self, _actual_path: &Path) {}
1311 fn probe_failed(&mut self, _actual_path: &Path, _: u64) {}
1313 fn probe_successful(&mut self, _actual_path: &Path) {}
1316 impl Drop for TestScorer {
1317 fn drop(&mut self) {
1318 #[cfg(feature = "std")] {
1319 if std::thread::panicking() {
1324 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1325 if !scorer_expectations.is_empty() {
1326 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1332 pub struct TestWalletSource {
1333 secret_key: SecretKey,
1334 utxos: RefCell<Vec<Utxo>>,
1335 secp: Secp256k1<bitcoin::secp256k1::All>,
1338 impl TestWalletSource {
1339 pub fn new(secret_key: SecretKey) -> Self {
1342 utxos: RefCell::new(Vec::new()),
1343 secp: Secp256k1::new(),
1347 pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1348 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1349 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1350 self.utxos.borrow_mut().push(utxo.clone());
1354 pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1355 let output = utxo.output.clone();
1356 self.utxos.borrow_mut().push(utxo);
1360 pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1361 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1365 impl WalletSource for TestWalletSource {
1366 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1367 Ok(self.utxos.borrow().clone())
1370 fn get_change_script(&self) -> Result<Script, ()> {
1371 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1372 Ok(Script::new_p2pkh(&public_key.pubkey_hash()))
1375 fn sign_tx(&self, mut tx: Transaction) -> Result<Transaction, ()> {
1376 let utxos = self.utxos.borrow();
1377 for i in 0..tx.input.len() {
1378 if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1379 let sighash = SighashCache::new(&tx)
1380 .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1382 let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key);
1383 let bitcoin_sig = bitcoin::EcdsaSig { sig, hash_ty: EcdsaSighashType::All }.to_vec();
1384 tx.input[i].script_sig = Builder::new()
1385 .push_slice(&bitcoin_sig)
1386 .push_slice(&self.secret_key.public_key(&self.secp).serialize())