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;
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, Score};
36 use crate::util::config::UserConfig;
37 use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
38 use crate::util::logger::{Logger, Level, Record};
39 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
41 use bitcoin::EcdsaSighashType;
42 use bitcoin::blockdata::constants::ChainHash;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::blockdata::transaction::{Transaction, TxOut};
45 use bitcoin::blockdata::script::{Builder, Script};
46 use bitcoin::blockdata::opcodes;
47 use bitcoin::blockdata::block::Block;
48 use bitcoin::network::constants::Network;
49 use bitcoin::hash_types::{BlockHash, Txid};
50 use bitcoin::util::sighash::SighashCache;
52 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
53 use bitcoin::secp256k1::ecdh::SharedSecret;
54 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
55 use bitcoin::secp256k1::schnorr;
57 #[cfg(any(test, feature = "_test_utils"))]
61 use crate::prelude::*;
62 use core::cell::RefCell;
63 use core::ops::DerefMut;
64 use core::time::Duration;
65 use crate::sync::{Mutex, Arc};
66 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
68 use bitcoin::bech32::u5;
69 use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
71 #[cfg(feature = "std")]
72 use std::time::{SystemTime, UNIX_EPOCH};
73 use bitcoin::Sequence;
75 pub fn pubkey(byte: u8) -> PublicKey {
76 let secp_ctx = Secp256k1::new();
77 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
80 pub fn privkey(byte: u8) -> SecretKey {
81 SecretKey::from_slice(&[byte; 32]).unwrap()
84 pub struct TestVecWriter(pub Vec<u8>);
85 impl Writer for TestVecWriter {
86 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
87 self.0.extend_from_slice(buf);
92 pub struct TestFeeEstimator {
93 pub sat_per_kw: Mutex<u32>,
95 impl chaininterface::FeeEstimator for TestFeeEstimator {
96 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
97 *self.sat_per_kw.lock().unwrap()
101 pub struct TestRouter<'a> {
102 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
103 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
104 pub scorer: &'a Mutex<TestScorer>,
107 impl<'a> TestRouter<'a> {
108 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a Mutex<TestScorer>) -> Self {
109 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
112 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
113 let mut expected_routes = self.next_routes.lock().unwrap();
114 expected_routes.push_back((query, result));
118 impl<'a> Router for TestRouter<'a> {
120 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
121 inflight_htlcs: InFlightHtlcs
122 ) -> Result<Route, msgs::LightningError> {
123 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
124 assert_eq!(find_route_query, *params);
125 if let Ok(ref route) = find_route_res {
126 let mut binding = self.scorer.lock().unwrap();
127 let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), &inflight_htlcs);
128 for path in &route.paths {
129 let mut aggregate_msat = 0u64;
130 for (idx, hop) in path.hops.iter().rev().enumerate() {
131 aggregate_msat += hop.fee_msat;
132 let usage = ChannelUsage {
133 amount_msat: aggregate_msat,
134 inflight_htlc_msat: 0,
135 effective_capacity: EffectiveCapacity::Unknown,
138 // Since the path is reversed, the last element in our iteration is the first
140 if idx == path.hops.len() - 1 {
141 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &());
143 let curr_hop_path_idx = path.hops.len() - 1 - idx;
144 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, &());
149 return find_route_res;
151 let logger = TestLogger::new();
153 payer, params, &self.network_graph, first_hops, &logger,
154 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().unwrap().deref_mut(), &inflight_htlcs), &(),
160 impl<'a> Drop for TestRouter<'a> {
162 #[cfg(feature = "std")] {
163 if std::thread::panicking() {
167 assert!(self.next_routes.lock().unwrap().is_empty());
171 pub struct OnlyReadsKeysInterface {}
173 impl EntropySource for OnlyReadsKeysInterface {
174 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
176 impl SignerProvider for OnlyReadsKeysInterface {
177 type Signer = EnforcingSigner;
179 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
181 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
183 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
184 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
185 let state = Arc::new(Mutex::new(EnforcementState::new()));
187 Ok(EnforcingSigner::new_with_revoked(
194 fn get_destination_script(&self) -> Result<Script, ()> { Err(()) }
195 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
198 pub struct TestChainMonitor<'a> {
199 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
200 pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
201 pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, MonitorUpdateId)>>,
202 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
203 pub keys_manager: &'a TestKeysInterface,
204 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
205 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
207 pub expect_channel_force_closed: Mutex<Option<(ChannelId, bool)>>,
209 impl<'a> TestChainMonitor<'a> {
210 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
212 added_monitors: Mutex::new(Vec::new()),
213 monitor_updates: Mutex::new(HashMap::new()),
214 latest_monitor_update_id: Mutex::new(HashMap::new()),
215 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
217 expect_channel_force_closed: Mutex::new(None),
221 pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) {
222 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
223 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
226 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
227 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
228 // At every point where we get a monitor update, we should be able to send a useful monitor
229 // to a watchtower and disk...
230 let mut w = TestVecWriter(Vec::new());
231 monitor.write(&mut w).unwrap();
232 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
233 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
234 assert!(new_monitor == monitor);
235 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
236 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
237 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
238 self.chain_monitor.watch_channel(funding_txo, new_monitor)
241 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
242 // Every monitor update should survive roundtrip
243 let mut w = TestVecWriter(Vec::new());
244 update.write(&mut w).unwrap();
245 assert!(channelmonitor::ChannelMonitorUpdate::read(
246 &mut io::Cursor::new(&w.0)).unwrap() == *update);
248 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
250 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
251 assert_eq!(funding_txo.to_channel_id(), exp.0);
252 assert_eq!(update.updates.len(), 1);
253 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
254 assert_eq!(should_broadcast, exp.1);
258 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
259 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
260 let update_res = self.chain_monitor.update_channel(funding_txo, update);
261 // At every point where we get a monitor update, we should be able to send a useful monitor
262 // to a watchtower and disk...
263 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
265 monitor.write(&mut w).unwrap();
266 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
267 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
268 assert!(new_monitor == *monitor);
269 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
273 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
274 return self.chain_monitor.release_pending_monitor_events();
278 struct JusticeTxData {
279 justice_tx: Transaction,
281 commitment_number: u64,
284 pub(crate) struct WatchtowerPersister {
285 persister: TestPersister,
286 /// Upon a new commitment_signed, we'll get a
287 /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
288 /// amount, and commitment number so we can build the justice tx after our counterparty
290 unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
291 /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
292 /// tx which would be used to provide a watchtower with the data it needs.
293 watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
294 destination_script: Script,
297 impl WatchtowerPersister {
298 pub(crate) fn new(destination_script: Script) -> Self {
299 WatchtowerPersister {
300 persister: TestPersister::new(),
301 unsigned_justice_tx_data: Mutex::new(HashMap::new()),
302 watchtower_state: Mutex::new(HashMap::new()),
307 pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
308 -> Option<Transaction> {
309 self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
312 fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
313 -> Option<JusticeTxData> {
314 let trusted_tx = counterparty_commitment_tx.trust();
315 let output_idx = trusted_tx.revokeable_output_index()?;
316 let built_tx = trusted_tx.built_transaction();
317 let value = built_tx.transaction.output[output_idx as usize].value;
318 let justice_tx = trusted_tx.build_to_local_justice_tx(
319 FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
320 let commitment_number = counterparty_commitment_tx.commitment_number();
321 Some(JusticeTxData { justice_tx, value, commitment_number })
325 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
326 fn persist_new_channel(&self, funding_txo: OutPoint,
327 data: &channelmonitor::ChannelMonitor<Signer>, id: MonitorUpdateId
328 ) -> chain::ChannelMonitorUpdateStatus {
329 let res = self.persister.persist_new_channel(funding_txo, data, id);
331 assert!(self.unsigned_justice_tx_data.lock().unwrap()
332 .insert(funding_txo, VecDeque::new()).is_none());
333 assert!(self.watchtower_state.lock().unwrap()
334 .insert(funding_txo, HashMap::new()).is_none());
336 let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
337 .expect("First and only call expects Some");
338 if let Some(justice_data)
339 = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
340 self.unsigned_justice_tx_data.lock().unwrap()
341 .get_mut(&funding_txo).unwrap()
342 .push_back(justice_data);
347 fn update_persisted_channel(
348 &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
349 data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId
350 ) -> chain::ChannelMonitorUpdateStatus {
351 let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id);
353 if let Some(update) = update {
354 let commitment_txs = data.counterparty_commitment_txs_from_update(update);
355 let justice_datas = commitment_txs.into_iter()
356 .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
357 let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
358 let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
359 channel_state.extend(justice_datas);
361 while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
363 let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
364 match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) {
365 Ok(signed_justice_tx) => {
366 let dup = self.watchtower_state.lock().unwrap()
367 .get_mut(&funding_txo).unwrap()
368 .insert(commitment_txid, signed_justice_tx);
369 assert!(dup.is_none());
370 channel_state.pop_front();
380 pub struct TestPersister {
381 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
383 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
384 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
385 /// MonitorUpdateId here.
386 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
387 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
388 /// MonitorUpdateId here.
389 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
392 pub fn new() -> Self {
394 update_rets: Mutex::new(VecDeque::new()),
395 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
396 offchain_monitor_updates: Mutex::new(HashMap::new()),
400 /// Queue an update status to return.
401 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
402 self.update_rets.lock().unwrap().push_back(next_ret);
405 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
406 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
407 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
410 chain::ChannelMonitorUpdateStatus::Completed
413 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
414 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
415 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
418 if update.is_none() {
419 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
421 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
427 pub struct TestBroadcaster {
428 pub txn_broadcasted: Mutex<Vec<Transaction>>,
429 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
432 impl TestBroadcaster {
433 pub fn new(network: Network) -> Self {
435 txn_broadcasted: Mutex::new(Vec::new()),
436 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
440 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
441 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
444 pub fn txn_broadcast(&self) -> Vec<Transaction> {
445 self.txn_broadcasted.lock().unwrap().split_off(0)
448 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
449 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
450 let mut seen = HashSet::new();
451 txn.retain(|tx| seen.insert(tx.txid()));
456 impl chaininterface::BroadcasterInterface for TestBroadcaster {
457 fn broadcast_transactions(&self, txs: &[&Transaction]) {
459 let lock_time = tx.lock_time.0;
460 assert!(lock_time < 1_500_000_000);
461 if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
462 for inp in tx.input.iter() {
463 if inp.sequence != Sequence::MAX {
464 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
469 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
470 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
474 pub struct TestChannelMessageHandler {
475 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
476 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
477 connected_peers: Mutex<HashSet<PublicKey>>,
478 pub message_fetch_counter: AtomicUsize,
479 genesis_hash: ChainHash,
482 impl TestChannelMessageHandler {
483 pub fn new(genesis_hash: ChainHash) -> Self {
484 TestChannelMessageHandler {
485 pending_events: Mutex::new(Vec::new()),
486 expected_recv_msgs: Mutex::new(None),
487 connected_peers: Mutex::new(HashSet::new()),
488 message_fetch_counter: AtomicUsize::new(0),
494 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
495 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
496 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
497 expected_msgs.as_mut().unwrap().push(ev);
500 fn received_msg(&self, _ev: wire::Message<()>) {
501 let mut msgs = self.expected_recv_msgs.lock().unwrap();
502 if msgs.is_none() { return; }
503 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
505 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
506 msgs.as_mut().unwrap().remove(0);
510 impl Drop for TestChannelMessageHandler {
512 #[cfg(feature = "std")]
514 let l = self.expected_recv_msgs.lock().unwrap();
515 if !std::thread::panicking() {
516 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
522 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
523 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
524 self.received_msg(wire::Message::OpenChannel(msg.clone()));
526 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
527 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
529 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
530 self.received_msg(wire::Message::FundingCreated(msg.clone()));
532 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
533 self.received_msg(wire::Message::FundingSigned(msg.clone()));
535 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
536 self.received_msg(wire::Message::ChannelReady(msg.clone()));
538 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
539 self.received_msg(wire::Message::Shutdown(msg.clone()));
541 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
542 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
544 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
545 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
547 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
548 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
550 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
551 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
553 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
554 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
556 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
557 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
559 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
560 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
562 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
563 self.received_msg(wire::Message::UpdateFee(msg.clone()));
565 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
566 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
568 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
569 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
571 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
572 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
574 fn peer_disconnected(&self, their_node_id: &PublicKey) {
575 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
577 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
578 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
579 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
580 // bother re-generating the expected Init message in all tests.
583 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
584 self.received_msg(wire::Message::Error(msg.clone()));
586 fn provided_node_features(&self) -> NodeFeatures {
587 channelmanager::provided_node_features(&UserConfig::default())
589 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
590 channelmanager::provided_init_features(&UserConfig::default())
593 fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
594 Some(vec![self.genesis_hash])
597 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
598 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
601 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
602 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
605 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
606 self.received_msg(wire::Message::TxAddInput(msg.clone()));
609 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
610 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
613 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
614 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
617 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
618 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
621 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
622 self.received_msg(wire::Message::TxComplete(msg.clone()));
625 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
626 self.received_msg(wire::Message::TxSignatures(msg.clone()));
629 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
630 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
633 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
634 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
637 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
638 self.received_msg(wire::Message::TxAbort(msg.clone()));
642 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
643 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
644 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
645 let mut pending_events = self.pending_events.lock().unwrap();
646 let mut ret = Vec::new();
647 mem::swap(&mut ret, &mut *pending_events);
652 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
653 use bitcoin::secp256k1::ffi::Signature as FFISignature;
654 let secp_ctx = Secp256k1::new();
655 let network = Network::Testnet;
656 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
657 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
658 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
659 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
660 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
661 features: ChannelFeatures::empty(),
662 chain_hash: genesis_block(network).header.block_hash(),
663 short_channel_id: short_chan_id,
664 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
665 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
666 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
667 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
668 excess_data: Vec::new(),
672 msgs::ChannelAnnouncement {
673 node_signature_1: Signature::from(FFISignature::new()),
674 node_signature_2: Signature::from(FFISignature::new()),
675 bitcoin_signature_1: Signature::from(FFISignature::new()),
676 bitcoin_signature_2: Signature::from(FFISignature::new()),
677 contents: unsigned_ann,
682 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
683 use bitcoin::secp256k1::ffi::Signature as FFISignature;
684 let network = Network::Testnet;
685 msgs::ChannelUpdate {
686 signature: Signature::from(unsafe { FFISignature::new() }),
687 contents: msgs::UnsignedChannelUpdate {
688 chain_hash: genesis_block(network).header.block_hash(),
689 short_channel_id: short_chan_id,
692 cltv_expiry_delta: 0,
693 htlc_minimum_msat: 0,
694 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
696 fee_proportional_millionths: 0,
702 pub struct TestRoutingMessageHandler {
703 pub chan_upds_recvd: AtomicUsize,
704 pub chan_anns_recvd: AtomicUsize,
705 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
706 pub request_full_sync: AtomicBool,
709 impl TestRoutingMessageHandler {
710 pub fn new() -> Self {
711 TestRoutingMessageHandler {
712 chan_upds_recvd: AtomicUsize::new(0),
713 chan_anns_recvd: AtomicUsize::new(0),
714 pending_events: Mutex::new(vec![]),
715 request_full_sync: AtomicBool::new(false),
719 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
720 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
721 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
723 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
724 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
725 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
727 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
728 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
729 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
731 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
732 let chan_upd_1 = get_dummy_channel_update(starting_point);
733 let chan_upd_2 = get_dummy_channel_update(starting_point);
734 let chan_ann = get_dummy_channel_announcement(starting_point);
736 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
739 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
743 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
744 if !init_msg.features.supports_gossip_queries() {
748 #[allow(unused_mut, unused_assignments)]
749 let mut gossip_start_time = 0;
750 #[cfg(feature = "std")]
752 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
753 if self.request_full_sync.load(Ordering::Acquire) {
754 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
756 gossip_start_time -= 60 * 60; // an hour ago
760 let mut pending_events = self.pending_events.lock().unwrap();
761 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
762 node_id: their_node_id.clone(),
763 msg: msgs::GossipTimestampFilter {
764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
765 first_timestamp: gossip_start_time as u32,
766 timestamp_range: u32::max_value(),
772 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
776 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
780 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
784 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
788 fn provided_node_features(&self) -> NodeFeatures {
789 let mut features = NodeFeatures::empty();
790 features.set_gossip_queries_optional();
794 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
795 let mut features = InitFeatures::empty();
796 features.set_gossip_queries_optional();
800 fn processing_queue_high(&self) -> bool { false }
803 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
804 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
805 let mut ret = Vec::new();
806 let mut pending_events = self.pending_events.lock().unwrap();
807 core::mem::swap(&mut ret, &mut pending_events);
812 pub struct TestLogger {
814 pub(crate) id: String,
815 pub lines: Mutex<HashMap<(String, String), usize>>,
819 pub fn new() -> TestLogger {
820 Self::with_id("".to_owned())
822 pub fn with_id(id: String) -> TestLogger {
826 lines: Mutex::new(HashMap::new())
829 pub fn enable(&mut self, level: Level) {
832 pub fn assert_log(&self, module: String, line: String, count: usize) {
833 let log_entries = self.lines.lock().unwrap();
834 assert_eq!(log_entries.get(&(module, line)), Some(&count));
837 /// Search for the number of occurrence of the logged lines which
838 /// 1. belongs to the specified module and
839 /// 2. contains `line` in it.
840 /// And asserts if the number of occurrences is the same with the given `count`
841 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
842 let log_entries = self.lines.lock().unwrap();
843 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
844 m == module && l.contains(line)
845 }).map(|(_, c) | { c }).sum();
849 /// Search for the number of occurrences of logged lines which
850 /// 1. belong to the specified module and
851 /// 2. match the given regex pattern.
852 /// Assert that the number of occurrences equals the given `count`
853 #[cfg(any(test, feature = "_test_utils"))]
854 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
855 let log_entries = self.lines.lock().unwrap();
856 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
857 m == module && pattern.is_match(&l)
858 }).map(|(_, c) | { c }).sum();
863 impl Logger for TestLogger {
864 fn log(&self, record: &Record) {
865 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
866 if record.level >= self.level {
867 #[cfg(all(not(ldk_bench), feature = "std"))]
868 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
873 pub struct TestNodeSigner {
874 node_secret: SecretKey,
877 impl TestNodeSigner {
878 pub fn new(node_secret: SecretKey) -> Self {
883 impl NodeSigner for TestNodeSigner {
884 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
888 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
889 let node_secret = match recipient {
890 Recipient::Node => Ok(&self.node_secret),
891 Recipient::PhantomNode => Err(())
893 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
896 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
897 let mut node_secret = match recipient {
898 Recipient::Node => Ok(self.node_secret.clone()),
899 Recipient::PhantomNode => Err(())
901 if let Some(tweak) = tweak {
902 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
904 Ok(SharedSecret::new(other_key, &node_secret))
907 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
911 fn sign_bolt12_invoice_request(
912 &self, _invoice_request: &UnsignedInvoiceRequest
913 ) -> Result<schnorr::Signature, ()> {
917 fn sign_bolt12_invoice(
918 &self, _invoice: &UnsignedBolt12Invoice,
919 ) -> Result<schnorr::Signature, ()> {
923 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
928 pub struct TestKeysInterface {
929 pub backing: sign::PhantomKeysManager,
930 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
931 pub disable_revocation_policy_check: bool,
932 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
933 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
936 impl EntropySource for TestKeysInterface {
937 fn get_secure_random_bytes(&self) -> [u8; 32] {
938 let override_random_bytes = self.override_random_bytes.lock().unwrap();
939 if let Some(bytes) = &*override_random_bytes {
942 self.backing.get_secure_random_bytes()
946 impl NodeSigner for TestKeysInterface {
947 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
948 self.backing.get_node_id(recipient)
951 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
952 self.backing.ecdh(recipient, other_key, tweak)
955 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
956 self.backing.get_inbound_payment_key_material()
959 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
960 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
963 fn sign_bolt12_invoice_request(
964 &self, invoice_request: &UnsignedInvoiceRequest
965 ) -> Result<schnorr::Signature, ()> {
966 self.backing.sign_bolt12_invoice_request(invoice_request)
969 fn sign_bolt12_invoice(
970 &self, invoice: &UnsignedBolt12Invoice,
971 ) -> Result<schnorr::Signature, ()> {
972 self.backing.sign_bolt12_invoice(invoice)
975 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
976 self.backing.sign_gossip_message(msg)
980 impl SignerProvider for TestKeysInterface {
981 type Signer = EnforcingSigner;
983 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
984 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
987 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
988 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
989 let state = self.make_enforcement_state_cell(keys.commitment_seed);
990 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
993 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
994 let mut reader = io::Cursor::new(buffer);
996 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
997 let state = self.make_enforcement_state_cell(inner.commitment_seed);
999 Ok(EnforcingSigner::new_with_revoked(
1002 self.disable_revocation_policy_check
1006 fn get_destination_script(&self) -> Result<Script, ()> { self.backing.get_destination_script() }
1008 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1009 match &mut *self.expectations.lock().unwrap() {
1010 None => self.backing.get_shutdown_scriptpubkey(),
1011 Some(expectations) => match expectations.pop_front() {
1012 None => panic!("Unexpected get_shutdown_scriptpubkey"),
1013 Some(expectation) => Ok(expectation.returns),
1019 impl TestKeysInterface {
1020 pub fn new(seed: &[u8; 32], network: Network) -> Self {
1021 let now = Duration::from_secs(genesis_block(network).header.time as u64);
1023 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1024 override_random_bytes: Mutex::new(None),
1025 disable_revocation_policy_check: false,
1026 enforcement_states: Mutex::new(HashMap::new()),
1027 expectations: Mutex::new(None),
1031 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
1033 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
1034 self.expectations.lock().unwrap()
1035 .get_or_insert_with(|| VecDeque::new())
1036 .push_back(expectation);
1040 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
1041 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
1042 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1043 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
1046 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
1047 let mut states = self.enforcement_states.lock().unwrap();
1048 if !states.contains_key(&commitment_seed) {
1049 let state = EnforcementState::new();
1050 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1052 let cell = states.get(&commitment_seed).unwrap();
1057 pub(crate) fn panicking() -> bool {
1058 #[cfg(feature = "std")]
1059 let panicking = ::std::thread::panicking();
1060 #[cfg(not(feature = "std"))]
1061 let panicking = false;
1065 impl Drop for TestKeysInterface {
1066 fn drop(&mut self) {
1071 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1072 if !expectations.is_empty() {
1073 panic!("Unsatisfied expectations: {:?}", expectations);
1079 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1080 /// returns a [`ShutdownScript`].
1081 pub struct OnGetShutdownScriptpubkey {
1082 /// A shutdown script used to close a channel.
1083 pub returns: ShutdownScript,
1086 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1087 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1088 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1092 pub struct TestChainSource {
1093 pub genesis_hash: BlockHash,
1094 pub utxo_ret: Mutex<UtxoResult>,
1095 pub get_utxo_call_count: AtomicUsize,
1096 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
1097 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
1100 impl TestChainSource {
1101 pub fn new(network: Network) -> Self {
1102 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1104 genesis_hash: genesis_block(network).block_hash(),
1105 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1106 get_utxo_call_count: AtomicUsize::new(0),
1107 watched_txn: Mutex::new(HashSet::new()),
1108 watched_outputs: Mutex::new(HashSet::new()),
1113 impl UtxoLookup for TestChainSource {
1114 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
1115 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1116 if self.genesis_hash != *genesis_hash {
1117 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1120 self.utxo_ret.lock().unwrap().clone()
1124 impl chain::Filter for TestChainSource {
1125 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1126 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
1129 fn register_output(&self, output: WatchedOutput) {
1130 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1134 impl Drop for TestChainSource {
1135 fn drop(&mut self) {
1142 pub struct TestScorer {
1143 /// Stores a tuple of (scid, ChannelUsage)
1144 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1148 pub fn new() -> Self {
1150 scorer_expectations: RefCell::new(None),
1154 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1155 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1160 impl crate::util::ser::Writeable for TestScorer {
1161 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1164 impl Score for TestScorer {
1165 type ScoreParams = ();
1166 fn channel_penalty_msat(
1167 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams
1169 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1170 match scorer_expectations.pop_front() {
1171 Some((scid, expectation)) => {
1172 assert_eq!(expectation, usage);
1173 assert_eq!(scid, short_channel_id);
1181 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {}
1183 fn payment_path_successful(&mut self, _actual_path: &Path) {}
1185 fn probe_failed(&mut self, _actual_path: &Path, _: u64) {}
1187 fn probe_successful(&mut self, _actual_path: &Path) {}
1190 impl Drop for TestScorer {
1191 fn drop(&mut self) {
1192 #[cfg(feature = "std")] {
1193 if std::thread::panicking() {
1198 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1199 if !scorer_expectations.is_empty() {
1200 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1206 pub struct TestWalletSource {
1207 secret_key: SecretKey,
1208 utxos: RefCell<Vec<Utxo>>,
1209 secp: Secp256k1<bitcoin::secp256k1::All>,
1212 impl TestWalletSource {
1213 pub fn new(secret_key: SecretKey) -> Self {
1216 utxos: RefCell::new(Vec::new()),
1217 secp: Secp256k1::new(),
1221 pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1222 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1223 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1224 self.utxos.borrow_mut().push(utxo.clone());
1228 pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1229 let output = utxo.output.clone();
1230 self.utxos.borrow_mut().push(utxo);
1234 pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1235 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1239 impl WalletSource for TestWalletSource {
1240 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1241 Ok(self.utxos.borrow().clone())
1244 fn get_change_script(&self) -> Result<Script, ()> {
1245 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1246 Ok(Script::new_p2pkh(&public_key.pubkey_hash()))
1249 fn sign_tx(&self, mut tx: Transaction) -> Result<Transaction, ()> {
1250 let utxos = self.utxos.borrow();
1251 for i in 0..tx.input.len() {
1252 if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1253 let sighash = SighashCache::new(&tx)
1254 .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1256 let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key);
1257 let bitcoin_sig = bitcoin::EcdsaSig { sig, hash_ty: EcdsaSighashType::All }.to_vec();
1258 tx.input[i].script_sig = Builder::new()
1259 .push_slice(&bitcoin_sig)
1260 .push_slice(&self.secret_key.public_key(&self.secp).serialize())