Merge pull request #3128 from TheBlueMatt/2024-06-no-claim-ret
[rust-lightning] / lightning / src / util / test_utils.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 use crate::blinded_path::BlindedPath;
11 use crate::blinded_path::message::ForwardNode;
12 use crate::blinded_path::payment::ReceiveTlvs;
13 use crate::chain;
14 use crate::chain::WatchedOutput;
15 use crate::chain::chaininterface;
16 use crate::chain::chaininterface::ConfirmationTarget;
17 #[cfg(test)]
18 use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW;
19 use crate::chain::chainmonitor;
20 use crate::chain::channelmonitor;
21 use crate::chain::channelmonitor::MonitorEvent;
22 use crate::chain::transaction::OutPoint;
23 use crate::routing::router::{CandidateRouteHop, FirstHopCandidate, PublicHopCandidate, PrivateHopCandidate};
24 use crate::sign;
25 use crate::events;
26 use crate::events::bump_transaction::{WalletSource, Utxo};
27 use crate::ln::types::ChannelId;
28 use crate::ln::channel_state::ChannelDetails;
29 use crate::ln::channelmanager;
30 #[cfg(test)]
31 use crate::ln::chan_utils::CommitmentTransaction;
32 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
33 use crate::ln::{msgs, wire};
34 use crate::ln::msgs::LightningError;
35 use crate::ln::script::ShutdownScript;
36 use crate::offers::invoice::{BlindedPayInfo, UnsignedBolt12Invoice};
37 use crate::offers::invoice_request::UnsignedInvoiceRequest;
38 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
39 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId, RoutingFees};
40 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
41 use crate::routing::router::{DefaultRouter, InFlightHtlcs, Path, Route, RouteParameters, RouteHintHop, Router, ScorerAccountingForInFlightHtlcs};
42 use crate::routing::scoring::{ChannelUsage, ScoreUpdate, ScoreLookUp};
43 use crate::sync::RwLock;
44 use crate::util::config::UserConfig;
45 use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState};
46 use crate::util::logger::{Logger, Level, Record};
47 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
48 use crate::util::persist::KVStore;
49
50 use bitcoin::amount::Amount;
51 use bitcoin::blockdata::constants::ChainHash;
52 use bitcoin::blockdata::constants::genesis_block;
53 use bitcoin::blockdata::transaction::{Transaction, TxOut};
54 use bitcoin::blockdata::script::{Builder, Script, ScriptBuf};
55 use bitcoin::blockdata::opcodes;
56 use bitcoin::blockdata::block::Block;
57 use bitcoin::network::Network;
58 use bitcoin::hash_types::{BlockHash, Txid};
59 use bitcoin::hashes::Hash;
60 use bitcoin::sighash::{SighashCache, EcdsaSighashType};
61
62 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, self};
63 use bitcoin::secp256k1::ecdh::SharedSecret;
64 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
65 use bitcoin::secp256k1::schnorr;
66
67 use crate::io;
68 use crate::prelude::*;
69 use core::cell::RefCell;
70 use core::time::Duration;
71 use crate::sync::{Mutex, Arc};
72 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
73 use core::mem;
74 use bech32::u5;
75 use crate::sign::{InMemorySigner, RandomBytes, Recipient, EntropySource, NodeSigner, SignerProvider};
76
77 #[cfg(feature = "std")]
78 use std::time::{SystemTime, UNIX_EPOCH};
79 use bitcoin::psbt::Psbt;
80 use bitcoin::Sequence;
81
82 pub fn pubkey(byte: u8) -> PublicKey {
83         let secp_ctx = Secp256k1::new();
84         PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
85 }
86
87 pub fn privkey(byte: u8) -> SecretKey {
88         SecretKey::from_slice(&[byte; 32]).unwrap()
89 }
90
91 pub struct TestVecWriter(pub Vec<u8>);
92 impl Writer for TestVecWriter {
93         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
94                 self.0.extend_from_slice(buf);
95                 Ok(())
96         }
97 }
98
99 pub struct TestFeeEstimator {
100         pub sat_per_kw: Mutex<u32>,
101 }
102 impl chaininterface::FeeEstimator for TestFeeEstimator {
103         fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
104                 *self.sat_per_kw.lock().unwrap()
105         }
106 }
107
108 pub struct TestRouter<'a> {
109         pub router: DefaultRouter<
110                 Arc<NetworkGraph<&'a TestLogger>>,
111                 &'a TestLogger,
112                 Arc<RandomBytes>,
113                 &'a RwLock<TestScorer>,
114                 (),
115                 TestScorer,
116         >,
117         //pub entropy_source: &'a RandomBytes,
118         pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
119         pub next_routes: Mutex<VecDeque<(RouteParameters, Option<Result<Route, LightningError>>)>>,
120         pub scorer: &'a RwLock<TestScorer>,
121 }
122
123 impl<'a> TestRouter<'a> {
124         pub fn new(
125                 network_graph: Arc<NetworkGraph<&'a TestLogger>>, logger: &'a TestLogger,
126                 scorer: &'a RwLock<TestScorer>,
127         ) -> Self {
128                 let entropy_source = Arc::new(RandomBytes::new([42; 32]));
129                 Self {
130                         router: DefaultRouter::new(network_graph.clone(), logger, entropy_source, scorer, ()),
131                         network_graph,
132                         next_routes: Mutex::new(VecDeque::new()),
133                         scorer,
134                 }
135         }
136
137         pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
138                 let mut expected_routes = self.next_routes.lock().unwrap();
139                 expected_routes.push_back((query, Some(result)));
140         }
141
142         pub fn expect_find_route_query(&self, query: RouteParameters) {
143                 let mut expected_routes = self.next_routes.lock().unwrap();
144                 expected_routes.push_back((query, None));
145         }
146 }
147
148 impl<'a> Router for TestRouter<'a> {
149         fn find_route(
150                 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
151                 inflight_htlcs: InFlightHtlcs
152         ) -> Result<Route, msgs::LightningError> {
153                 let route_res;
154                 let next_route_opt = self.next_routes.lock().unwrap().pop_front();
155                 if let Some((find_route_query, find_route_res)) = next_route_opt {
156                         assert_eq!(find_route_query, *params);
157                         if let Some(res) = find_route_res {
158                                 if let Ok(ref route) = res {
159                                         assert_eq!(route.route_params, Some(find_route_query));
160                                         let scorer = self.scorer.read().unwrap();
161                                         let scorer = ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs);
162                                         for path in &route.paths {
163                                                 let mut aggregate_msat = 0u64;
164                                                 let mut prev_hop_node = payer;
165                                                 for (idx, hop) in path.hops.iter().rev().enumerate() {
166                                                         aggregate_msat += hop.fee_msat;
167                                                         let usage = ChannelUsage {
168                                                                 amount_msat: aggregate_msat,
169                                                                 inflight_htlc_msat: 0,
170                                                                 effective_capacity: EffectiveCapacity::Unknown,
171                                                         };
172
173                                                         if idx == path.hops.len() - 1 {
174                                                                 if let Some(first_hops) = first_hops {
175                                                                         if let Some(idx) = first_hops.iter().position(|h| h.get_outbound_payment_scid() == Some(hop.short_channel_id)) {
176                                                                                 let node_id = NodeId::from_pubkey(payer);
177                                                                                 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
178                                                                                         details: first_hops[idx],
179                                                                                         payer_node_id: &node_id,
180                                                                                 });
181                                                                                 scorer.channel_penalty_msat(&candidate, usage, &Default::default());
182                                                                                 continue;
183                                                                         }
184                                                                 }
185                                                         }
186                                                         let network_graph = self.network_graph.read_only();
187                                                         if let Some(channel) = network_graph.channel(hop.short_channel_id) {
188                                                                 let (directed, _) = channel.as_directed_to(&NodeId::from_pubkey(&hop.pubkey)).unwrap();
189                                                                 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
190                                                                         info: directed,
191                                                                         short_channel_id: hop.short_channel_id,
192                                                                 });
193                                                                 scorer.channel_penalty_msat(&candidate, usage, &Default::default());
194                                                         } else {
195                                                                 let target_node_id = NodeId::from_pubkey(&hop.pubkey);
196                                                                 let route_hint = RouteHintHop {
197                                                                         src_node_id: *prev_hop_node,
198                                                                         short_channel_id: hop.short_channel_id,
199                                                                         fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
200                                                                         cltv_expiry_delta: 0,
201                                                                         htlc_minimum_msat: None,
202                                                                         htlc_maximum_msat: None,
203                                                                 };
204                                                                 let candidate = CandidateRouteHop::PrivateHop(PrivateHopCandidate {
205                                                                         hint: &route_hint,
206                                                                         target_node_id: &target_node_id,
207                                                                 });
208                                                                 scorer.channel_penalty_msat(&candidate, usage, &Default::default());
209                                                         }
210                                                         prev_hop_node = &hop.pubkey;
211                                                 }
212                                         }
213                                 }
214                                 route_res = res;
215                         } else {
216                                 route_res = self.router.find_route(payer, params, first_hops, inflight_htlcs);
217                         }
218                 } else {
219                         route_res = self.router.find_route(payer, params, first_hops, inflight_htlcs);
220                 };
221
222                 if let Ok(route) = &route_res {
223                         // Previously, `Route`s failed to round-trip through serialization due to a write/read
224                         // mismatch. Thus, here we test all test-generated routes round-trip:
225                         let ser = route.encode();
226                         assert_eq!(Route::read(&mut &ser[..]).unwrap(), *route);
227                 }
228                 route_res
229         }
230
231         fn create_blinded_payment_paths<
232                 T: secp256k1::Signing + secp256k1::Verification
233         >(
234                 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
235                 amount_msats: u64, secp_ctx: &Secp256k1<T>,
236         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
237                 self.router.create_blinded_payment_paths(
238                         recipient, first_hops, tlvs, amount_msats, secp_ctx
239                 )
240         }
241 }
242
243 impl<'a> MessageRouter for TestRouter<'a> {
244         fn find_path(
245                 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
246         ) -> Result<OnionMessagePath, ()> {
247                 self.router.find_path(sender, peers, destination)
248         }
249
250         fn create_blinded_paths<
251                 T: secp256k1::Signing + secp256k1::Verification
252         >(
253                 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
254         ) -> Result<Vec<BlindedPath>, ()> {
255                 self.router.create_blinded_paths(recipient, peers, secp_ctx)
256         }
257
258         fn create_compact_blinded_paths<
259                 T: secp256k1::Signing + secp256k1::Verification
260         >(
261                 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
262         ) -> Result<Vec<BlindedPath>, ()> {
263                 self.router.create_compact_blinded_paths(recipient, peers, secp_ctx)
264         }
265 }
266
267 impl<'a> Drop for TestRouter<'a> {
268         fn drop(&mut self) {
269                 #[cfg(feature = "std")] {
270                         if std::thread::panicking() {
271                                 return;
272                         }
273                 }
274                 assert!(self.next_routes.lock().unwrap().is_empty());
275         }
276 }
277
278 pub struct TestMessageRouter<'a> {
279         inner: DefaultMessageRouter<Arc<NetworkGraph<&'a TestLogger>>, &'a TestLogger, &'a TestKeysInterface>,
280 }
281
282 impl<'a> TestMessageRouter<'a> {
283         pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, entropy_source: &'a TestKeysInterface) -> Self {
284                 Self { inner: DefaultMessageRouter::new(network_graph, entropy_source) }
285         }
286 }
287
288 impl<'a> MessageRouter for TestMessageRouter<'a> {
289         fn find_path(
290                 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
291         ) -> Result<OnionMessagePath, ()> {
292                 self.inner.find_path(sender, peers, destination)
293         }
294
295         fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
296                 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
297         ) -> Result<Vec<BlindedPath>, ()> {
298                 self.inner.create_blinded_paths(recipient, peers, secp_ctx)
299         }
300
301         fn create_compact_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
302                 &self, recipient: PublicKey, peers: Vec<ForwardNode>, secp_ctx: &Secp256k1<T>,
303         ) -> Result<Vec<BlindedPath>, ()> {
304                 self.inner.create_compact_blinded_paths(recipient, peers, secp_ctx)
305         }
306 }
307
308 pub struct OnlyReadsKeysInterface {}
309
310 impl EntropySource for OnlyReadsKeysInterface {
311         fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
312
313 impl SignerProvider for OnlyReadsKeysInterface {
314         type EcdsaSigner = TestChannelSigner;
315         #[cfg(taproot)]
316         type TaprootSigner = TestChannelSigner;
317
318         fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
319
320         fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::EcdsaSigner { unreachable!(); }
321
322         fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::EcdsaSigner, msgs::DecodeError> {
323                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
324                 let state = Arc::new(Mutex::new(EnforcementState::new()));
325
326                 Ok(TestChannelSigner::new_with_revoked(
327                         inner,
328                         state,
329                         false
330                 ))
331         }
332
333         fn get_destination_script(&self, _channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> { Err(()) }
334         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
335 }
336
337 pub struct TestChainMonitor<'a> {
338         pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<TestChannelSigner>)>>,
339         pub monitor_updates: Mutex<HashMap<ChannelId, Vec<channelmonitor::ChannelMonitorUpdate>>>,
340         pub latest_monitor_update_id: Mutex<HashMap<ChannelId, (OutPoint, u64, u64)>>,
341         pub chain_monitor: chainmonitor::ChainMonitor<TestChannelSigner, &'a TestChainSource, &'a dyn chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a dyn chainmonitor::Persist<TestChannelSigner>>,
342         pub keys_manager: &'a TestKeysInterface,
343         /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
344         /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
345         /// boolean.
346         pub expect_channel_force_closed: Mutex<Option<(ChannelId, bool)>>,
347         /// If this is set to Some(), the next round trip serialization check will not hold after an
348         /// update_channel call (not watch_channel) for the given channel_id.
349         pub expect_monitor_round_trip_fail: Mutex<Option<ChannelId>>,
350 }
351 impl<'a> TestChainMonitor<'a> {
352         pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a dyn chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a dyn chainmonitor::Persist<TestChannelSigner>, keys_manager: &'a TestKeysInterface) -> Self {
353                 Self {
354                         added_monitors: Mutex::new(Vec::new()),
355                         monitor_updates: Mutex::new(new_hash_map()),
356                         latest_monitor_update_id: Mutex::new(new_hash_map()),
357                         chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
358                         keys_manager,
359                         expect_channel_force_closed: Mutex::new(None),
360                         expect_monitor_round_trip_fail: Mutex::new(None),
361                 }
362         }
363
364         pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) {
365                 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
366                 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
367         }
368 }
369 impl<'a> chain::Watch<TestChannelSigner> for TestChainMonitor<'a> {
370         fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<TestChannelSigner>) -> Result<chain::ChannelMonitorUpdateStatus, ()> {
371                 // At every point where we get a monitor update, we should be able to send a useful monitor
372                 // to a watchtower and disk...
373                 let mut w = TestVecWriter(Vec::new());
374                 monitor.write(&mut w).unwrap();
375                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
376                         &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
377                 assert!(new_monitor == monitor);
378                 self.latest_monitor_update_id.lock().unwrap().insert(monitor.channel_id(),
379                         (funding_txo, monitor.get_latest_update_id(), monitor.get_latest_update_id()));
380                 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
381                 self.chain_monitor.watch_channel(funding_txo, new_monitor)
382         }
383
384         fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
385                 // Every monitor update should survive roundtrip
386                 let mut w = TestVecWriter(Vec::new());
387                 update.write(&mut w).unwrap();
388                 assert!(channelmonitor::ChannelMonitorUpdate::read(
389                                 &mut io::Cursor::new(&w.0)).unwrap() == *update);
390                 let channel_id = update.channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(funding_txo));
391
392                 self.monitor_updates.lock().unwrap().entry(channel_id).or_insert(Vec::new()).push(update.clone());
393
394                 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
395                         assert_eq!(channel_id, exp.0);
396                         assert_eq!(update.updates.len(), 1);
397                         if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
398                                 assert_eq!(should_broadcast, exp.1);
399                         } else { panic!(); }
400                 }
401
402                 self.latest_monitor_update_id.lock().unwrap().insert(channel_id,
403                         (funding_txo, update.update_id, update.update_id));
404                 let update_res = self.chain_monitor.update_channel(funding_txo, update);
405                 // At every point where we get a monitor update, we should be able to send a useful monitor
406                 // to a watchtower and disk...
407                 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
408                 w.0.clear();
409                 monitor.write(&mut w).unwrap();
410                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
411                         &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
412                 if let Some(chan_id) = self.expect_monitor_round_trip_fail.lock().unwrap().take() {
413                         assert_eq!(chan_id, channel_id);
414                         assert!(new_monitor != *monitor);
415                 } else {
416                         assert!(new_monitor == *monitor);
417                 }
418                 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
419                 update_res
420         }
421
422         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, Option<PublicKey>)> {
423                 return self.chain_monitor.release_pending_monitor_events();
424         }
425 }
426
427 #[cfg(test)]
428 struct JusticeTxData {
429         justice_tx: Transaction,
430         value: Amount,
431         commitment_number: u64,
432 }
433
434 #[cfg(test)]
435 pub(crate) struct WatchtowerPersister {
436         persister: TestPersister,
437         /// Upon a new commitment_signed, we'll get a
438         /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx
439         /// amount, and commitment number so we can build the justice tx after our counterparty
440         /// revokes it.
441         unsigned_justice_tx_data: Mutex<HashMap<OutPoint, VecDeque<JusticeTxData>>>,
442         /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice
443         /// tx which would be used to provide a watchtower with the data it needs.
444         watchtower_state: Mutex<HashMap<OutPoint, HashMap<Txid, Transaction>>>,
445         destination_script: ScriptBuf,
446 }
447
448 #[cfg(test)]
449 impl WatchtowerPersister {
450         #[cfg(test)]
451         pub(crate) fn new(destination_script: ScriptBuf) -> Self {
452                 WatchtowerPersister {
453                         persister: TestPersister::new(),
454                         unsigned_justice_tx_data: Mutex::new(new_hash_map()),
455                         watchtower_state: Mutex::new(new_hash_map()),
456                         destination_script,
457                 }
458         }
459
460         #[cfg(test)]
461         pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid)
462         -> Option<Transaction> {
463                 self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned()
464         }
465
466         fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction)
467         -> Option<JusticeTxData> {
468                 let trusted_tx = counterparty_commitment_tx.trust();
469                 let output_idx = trusted_tx.revokeable_output_index()?;
470                 let built_tx = trusted_tx.built_transaction();
471                 let value = built_tx.transaction.output[output_idx as usize].value;
472                 let justice_tx = trusted_tx.build_to_local_justice_tx(
473                         FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?;
474                 let commitment_number = counterparty_commitment_tx.commitment_number();
475                 Some(JusticeTxData { justice_tx, value, commitment_number })
476         }
477 }
478
479 #[cfg(test)]
480 impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer> for WatchtowerPersister {
481         fn persist_new_channel(&self, funding_txo: OutPoint,
482                 data: &channelmonitor::ChannelMonitor<Signer>
483         ) -> chain::ChannelMonitorUpdateStatus {
484                 let res = self.persister.persist_new_channel(funding_txo, data);
485
486                 assert!(self.unsigned_justice_tx_data.lock().unwrap()
487                         .insert(funding_txo, VecDeque::new()).is_none());
488                 assert!(self.watchtower_state.lock().unwrap()
489                         .insert(funding_txo, new_hash_map()).is_none());
490
491                 let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx()
492                         .expect("First and only call expects Some");
493                 if let Some(justice_data)
494                         = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) {
495                         self.unsigned_justice_tx_data.lock().unwrap()
496                                 .get_mut(&funding_txo).unwrap()
497                                 .push_back(justice_data);
498                 }
499                 res
500         }
501
502         fn update_persisted_channel(
503                 &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>,
504                 data: &channelmonitor::ChannelMonitor<Signer>
505         ) -> chain::ChannelMonitorUpdateStatus {
506                 let res = self.persister.update_persisted_channel(funding_txo, update, data);
507
508                 if let Some(update) = update {
509                         let commitment_txs = data.counterparty_commitment_txs_from_update(update);
510                         let justice_datas = commitment_txs.into_iter()
511                                 .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx));
512                         let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap();
513                         let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap();
514                         channel_state.extend(justice_datas);
515
516                         while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() {
517                                 let input_idx = 0;
518                                 let commitment_txid = justice_tx.input[input_idx].previous_output.txid;
519                                 match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, value.to_sat(), *commitment_number) {
520                                         Ok(signed_justice_tx) => {
521                                                 let dup = self.watchtower_state.lock().unwrap()
522                                                         .get_mut(&funding_txo).unwrap()
523                                                         .insert(commitment_txid, signed_justice_tx);
524                                                 assert!(dup.is_none());
525                                                 channel_state.pop_front();
526                                         },
527                                         Err(_) => break,
528                                 }
529                         }
530                 }
531                 res
532         }
533
534         fn archive_persisted_channel(&self, funding_txo: OutPoint) {
535                 <TestPersister as chainmonitor::Persist<TestChannelSigner>>::archive_persisted_channel(&self.persister, funding_txo);
536         }
537 }
538
539 pub struct TestPersister {
540         /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
541         /// returned.
542         pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
543         /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
544         /// [`ChannelMonitor::get_latest_update_id`] here.
545         ///
546         /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
547         pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<u64>>>,
548 }
549 impl TestPersister {
550         pub fn new() -> Self {
551                 Self {
552                         update_rets: Mutex::new(VecDeque::new()),
553                         offchain_monitor_updates: Mutex::new(new_hash_map()),
554                 }
555         }
556
557         /// Queue an update status to return.
558         pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
559                 self.update_rets.lock().unwrap().push_back(next_ret);
560         }
561 }
562 impl<Signer: sign::ecdsa::EcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
563         fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>) -> chain::ChannelMonitorUpdateStatus {
564                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
565                         return update_ret
566                 }
567                 chain::ChannelMonitorUpdateStatus::Completed
568         }
569
570         fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>) -> chain::ChannelMonitorUpdateStatus {
571                 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
572                 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
573                         ret = update_ret;
574                 }
575
576                 if let Some(update) = update  {
577                         self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(new_hash_set()).insert(update.update_id);
578                 }
579                 ret
580         }
581
582         fn archive_persisted_channel(&self, funding_txo: OutPoint) {
583                 // remove the channel from the offchain_monitor_updates map
584                 self.offchain_monitor_updates.lock().unwrap().remove(&funding_txo);
585         }
586 }
587
588 pub struct TestStore {
589         persisted_bytes: Mutex<HashMap<String, HashMap<String, Vec<u8>>>>,
590         read_only: bool,
591 }
592
593 impl TestStore {
594         pub fn new(read_only: bool) -> Self {
595                 let persisted_bytes = Mutex::new(new_hash_map());
596                 Self { persisted_bytes, read_only }
597         }
598 }
599
600 impl KVStore for TestStore {
601         fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> io::Result<Vec<u8>> {
602                 let persisted_lock = self.persisted_bytes.lock().unwrap();
603                 let prefixed = if secondary_namespace.is_empty() {
604                         primary_namespace.to_string()
605                 } else {
606                         format!("{}/{}", primary_namespace, secondary_namespace)
607                 };
608
609                 if let Some(outer_ref) = persisted_lock.get(&prefixed) {
610                         if let Some(inner_ref) = outer_ref.get(key) {
611                                 let bytes = inner_ref.clone();
612                                 Ok(bytes)
613                         } else {
614                                 Err(io::Error::new(io::ErrorKind::NotFound, "Key not found"))
615                         }
616                 } else {
617                         Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found"))
618                 }
619         }
620
621         fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> {
622                 if self.read_only {
623                         return Err(io::Error::new(
624                                 io::ErrorKind::PermissionDenied,
625                                 "Cannot modify read-only store",
626                         ));
627                 }
628                 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
629
630                 let prefixed = if secondary_namespace.is_empty() {
631                         primary_namespace.to_string()
632                 } else {
633                         format!("{}/{}", primary_namespace, secondary_namespace)
634                 };
635                 let outer_e = persisted_lock.entry(prefixed).or_insert(new_hash_map());
636                 let mut bytes = Vec::new();
637                 bytes.write_all(buf)?;
638                 outer_e.insert(key.to_string(), bytes);
639                 Ok(())
640         }
641
642         fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> {
643                 if self.read_only {
644                         return Err(io::Error::new(
645                                 io::ErrorKind::PermissionDenied,
646                                 "Cannot modify read-only store",
647                         ));
648                 }
649
650                 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
651
652                 let prefixed = if secondary_namespace.is_empty() {
653                         primary_namespace.to_string()
654                 } else {
655                         format!("{}/{}", primary_namespace, secondary_namespace)
656                 };
657                 if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) {
658                                 outer_ref.remove(&key.to_string());
659                 }
660
661                 Ok(())
662         }
663
664         fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> io::Result<Vec<String>> {
665                 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
666
667                 let prefixed = if secondary_namespace.is_empty() {
668                         primary_namespace.to_string()
669                 } else {
670                         format!("{}/{}", primary_namespace, secondary_namespace)
671                 };
672                 match persisted_lock.entry(prefixed) {
673                         hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()),
674                         hash_map::Entry::Vacant(_) => Ok(Vec::new()),
675                 }
676         }
677 }
678
679 unsafe impl Sync for TestStore {}
680 unsafe impl Send for TestStore {}
681
682 pub struct TestBroadcaster {
683         pub txn_broadcasted: Mutex<Vec<Transaction>>,
684         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
685 }
686
687 impl TestBroadcaster {
688         pub fn new(network: Network) -> Self {
689                 Self {
690                         txn_broadcasted: Mutex::new(Vec::new()),
691                         blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
692                 }
693         }
694
695         pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
696                 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
697         }
698
699         pub fn txn_broadcast(&self) -> Vec<Transaction> {
700                 self.txn_broadcasted.lock().unwrap().split_off(0)
701         }
702
703         pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
704                 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
705                 let mut seen = new_hash_set();
706                 txn.retain(|tx| seen.insert(tx.txid()));
707                 txn
708         }
709 }
710
711 impl chaininterface::BroadcasterInterface for TestBroadcaster {
712         fn broadcast_transactions(&self, txs: &[&Transaction]) {
713                 for tx in txs {
714                         let lock_time = tx.lock_time.to_consensus_u32();
715                         assert!(lock_time < 1_500_000_000);
716                         if tx.lock_time.is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
717                                 for inp in tx.input.iter() {
718                                         if inp.sequence != Sequence::MAX {
719                                                 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
720                                         }
721                                 }
722                         }
723                 }
724                 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
725                 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
726         }
727 }
728
729 pub struct TestChannelMessageHandler {
730         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
731         expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
732         connected_peers: Mutex<HashSet<PublicKey>>,
733         pub message_fetch_counter: AtomicUsize,
734         chain_hash: ChainHash,
735 }
736
737 impl TestChannelMessageHandler {
738         pub fn new(chain_hash: ChainHash) -> Self {
739                 TestChannelMessageHandler {
740                         pending_events: Mutex::new(Vec::new()),
741                         expected_recv_msgs: Mutex::new(None),
742                         connected_peers: Mutex::new(new_hash_set()),
743                         message_fetch_counter: AtomicUsize::new(0),
744                         chain_hash,
745                 }
746         }
747
748         #[cfg(test)]
749         pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
750                 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
751                 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
752                 expected_msgs.as_mut().unwrap().push(ev);
753         }
754
755         fn received_msg(&self, _ev: wire::Message<()>) {
756                 let mut msgs = self.expected_recv_msgs.lock().unwrap();
757                 if msgs.is_none() { return; }
758                 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
759                 #[cfg(test)]
760                 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
761                 msgs.as_mut().unwrap().remove(0);
762         }
763 }
764
765 impl Drop for TestChannelMessageHandler {
766         fn drop(&mut self) {
767                 #[cfg(feature = "std")]
768                 {
769                         let l = self.expected_recv_msgs.lock().unwrap();
770                         if !std::thread::panicking() {
771                                 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
772                         }
773                 }
774         }
775 }
776
777 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
778         fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
779                 self.received_msg(wire::Message::OpenChannel(msg.clone()));
780         }
781         fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
782                 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
783         }
784         fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
785                 self.received_msg(wire::Message::FundingCreated(msg.clone()));
786         }
787         fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
788                 self.received_msg(wire::Message::FundingSigned(msg.clone()));
789         }
790         fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
791                 self.received_msg(wire::Message::ChannelReady(msg.clone()));
792         }
793         fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
794                 self.received_msg(wire::Message::Shutdown(msg.clone()));
795         }
796         fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
797                 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
798         }
799         fn handle_stfu(&self, _their_node_id: &PublicKey, msg: &msgs::Stfu) {
800                 self.received_msg(wire::Message::Stfu(msg.clone()));
801         }
802         #[cfg(splicing)]
803         fn handle_splice(&self, _their_node_id: &PublicKey, msg: &msgs::Splice) {
804                 self.received_msg(wire::Message::Splice(msg.clone()));
805         }
806         #[cfg(splicing)]
807         fn handle_splice_ack(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceAck) {
808                 self.received_msg(wire::Message::SpliceAck(msg.clone()));
809         }
810         #[cfg(splicing)]
811         fn handle_splice_locked(&self, _their_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
812                 self.received_msg(wire::Message::SpliceLocked(msg.clone()));
813         }
814         fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
815                 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
816         }
817         fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
818                 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
819         }
820         fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
821                 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
822         }
823         fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
824                 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
825         }
826         fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
827                 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
828         }
829         fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
830                 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
831         }
832         fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
833                 self.received_msg(wire::Message::UpdateFee(msg.clone()));
834         }
835         fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
836                 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
837         }
838         fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
839                 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
840         }
841         fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
842                 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
843         }
844         fn peer_disconnected(&self, their_node_id: &PublicKey) {
845                 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
846         }
847         fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
848                 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
849                 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
850                 // bother re-generating the expected Init message in all tests.
851                 Ok(())
852         }
853         fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
854                 self.received_msg(wire::Message::Error(msg.clone()));
855         }
856         fn provided_node_features(&self) -> NodeFeatures {
857                 channelmanager::provided_node_features(&UserConfig::default())
858         }
859         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
860                 channelmanager::provided_init_features(&UserConfig::default())
861         }
862
863         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
864                 Some(vec![self.chain_hash])
865         }
866
867         fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
868                 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
869         }
870
871         fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
872                 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
873         }
874
875         fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
876                 self.received_msg(wire::Message::TxAddInput(msg.clone()));
877         }
878
879         fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
880                 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
881         }
882
883         fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
884                 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
885         }
886
887         fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
888                 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
889         }
890
891         fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
892                 self.received_msg(wire::Message::TxComplete(msg.clone()));
893         }
894
895         fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
896                 self.received_msg(wire::Message::TxSignatures(msg.clone()));
897         }
898
899         fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
900                 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
901         }
902
903         fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
904                 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
905         }
906
907         fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
908                 self.received_msg(wire::Message::TxAbort(msg.clone()));
909         }
910 }
911
912 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
913         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
914                 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
915                 let mut pending_events = self.pending_events.lock().unwrap();
916                 let mut ret = Vec::new();
917                 mem::swap(&mut ret, &mut *pending_events);
918                 ret
919         }
920 }
921
922 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
923         use bitcoin::secp256k1::ffi::Signature as FFISignature;
924         let secp_ctx = Secp256k1::new();
925         let network = Network::Testnet;
926         let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
927         let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
928         let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
929         let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
930         let unsigned_ann = msgs::UnsignedChannelAnnouncement {
931                 features: ChannelFeatures::empty(),
932                 chain_hash: ChainHash::using_genesis_block(network),
933                 short_channel_id: short_chan_id,
934                 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
935                 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
936                 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
937                 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
938                 excess_data: Vec::new(),
939         };
940
941         unsafe {
942                 msgs::ChannelAnnouncement {
943                         node_signature_1: Signature::from(FFISignature::new()),
944                         node_signature_2: Signature::from(FFISignature::new()),
945                         bitcoin_signature_1: Signature::from(FFISignature::new()),
946                         bitcoin_signature_2: Signature::from(FFISignature::new()),
947                         contents: unsigned_ann,
948                 }
949         }
950 }
951
952 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
953         use bitcoin::secp256k1::ffi::Signature as FFISignature;
954         let network = Network::Testnet;
955         msgs::ChannelUpdate {
956                 signature: Signature::from(unsafe { FFISignature::new() }),
957                 contents: msgs::UnsignedChannelUpdate {
958                         chain_hash: ChainHash::using_genesis_block(network),
959                         short_channel_id: short_chan_id,
960                         timestamp: 0,
961                         flags: 0,
962                         cltv_expiry_delta: 0,
963                         htlc_minimum_msat: 0,
964                         htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
965                         fee_base_msat: 0,
966                         fee_proportional_millionths: 0,
967                         excess_data: vec![],
968                 }
969         }
970 }
971
972 pub struct TestRoutingMessageHandler {
973         pub chan_upds_recvd: AtomicUsize,
974         pub chan_anns_recvd: AtomicUsize,
975         pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
976         pub request_full_sync: AtomicBool,
977 }
978
979 impl TestRoutingMessageHandler {
980         pub fn new() -> Self {
981                 TestRoutingMessageHandler {
982                         chan_upds_recvd: AtomicUsize::new(0),
983                         chan_anns_recvd: AtomicUsize::new(0),
984                         pending_events: Mutex::new(vec![]),
985                         request_full_sync: AtomicBool::new(false),
986                 }
987         }
988 }
989 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
990         fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
991                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
992         }
993         fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
994                 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
995                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
996         }
997         fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
998                 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
999                 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
1000         }
1001         fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
1002                 let chan_upd_1 = get_dummy_channel_update(starting_point);
1003                 let chan_upd_2 = get_dummy_channel_update(starting_point);
1004                 let chan_ann = get_dummy_channel_announcement(starting_point);
1005
1006                 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
1007         }
1008
1009         fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
1010                 None
1011         }
1012
1013         fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
1014                 if !init_msg.features.supports_gossip_queries() {
1015                         return Ok(());
1016                 }
1017
1018                 #[allow(unused_mut, unused_assignments)]
1019                 let mut gossip_start_time = 0;
1020                 #[cfg(feature = "std")]
1021                 {
1022                         gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
1023                         if self.request_full_sync.load(Ordering::Acquire) {
1024                                 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
1025                         } else {
1026                                 gossip_start_time -= 60 * 60; // an hour ago
1027                         }
1028                 }
1029
1030                 let mut pending_events = self.pending_events.lock().unwrap();
1031                 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
1032                         node_id: their_node_id.clone(),
1033                         msg: msgs::GossipTimestampFilter {
1034                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
1035                                 first_timestamp: gossip_start_time as u32,
1036                                 timestamp_range: u32::max_value(),
1037                         },
1038                 });
1039                 Ok(())
1040         }
1041
1042         fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
1043                 Ok(())
1044         }
1045
1046         fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
1047                 Ok(())
1048         }
1049
1050         fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
1051                 Ok(())
1052         }
1053
1054         fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
1055                 Ok(())
1056         }
1057
1058         fn provided_node_features(&self) -> NodeFeatures {
1059                 let mut features = NodeFeatures::empty();
1060                 features.set_gossip_queries_optional();
1061                 features
1062         }
1063
1064         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
1065                 let mut features = InitFeatures::empty();
1066                 features.set_gossip_queries_optional();
1067                 features
1068         }
1069
1070         fn processing_queue_high(&self) -> bool { false }
1071 }
1072
1073 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
1074         fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
1075                 let mut ret = Vec::new();
1076                 let mut pending_events = self.pending_events.lock().unwrap();
1077                 core::mem::swap(&mut ret, &mut pending_events);
1078                 ret
1079         }
1080 }
1081
1082 pub struct TestLogger {
1083         level: Level,
1084         pub(crate) id: String,
1085         pub lines: Mutex<HashMap<(&'static str, String), usize>>,
1086         pub context: Mutex<HashMap<(&'static str, Option<PublicKey>, Option<ChannelId>), usize>>,
1087 }
1088
1089 impl TestLogger {
1090         pub fn new() -> TestLogger {
1091                 Self::with_id("".to_owned())
1092         }
1093         pub fn with_id(id: String) -> TestLogger {
1094                 TestLogger {
1095                         level: Level::Trace,
1096                         id,
1097                         lines: Mutex::new(new_hash_map()),
1098                         context: Mutex::new(new_hash_map()),
1099                 }
1100         }
1101         pub fn enable(&mut self, level: Level) {
1102                 self.level = level;
1103         }
1104         pub fn assert_log(&self, module: &str, line: String, count: usize) {
1105                 let log_entries = self.lines.lock().unwrap();
1106                 assert_eq!(log_entries.get(&(module, line)), Some(&count));
1107         }
1108
1109         /// Search for the number of occurrence of the logged lines which
1110         /// 1. belongs to the specified module and
1111         /// 2. contains `line` in it.
1112         /// And asserts if the number of occurrences is the same with the given `count`
1113         pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
1114                 let log_entries = self.lines.lock().unwrap();
1115                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
1116                         *m == module && l.contains(line)
1117                 }).map(|(_, c) | { c }).sum();
1118                 assert_eq!(l, count)
1119         }
1120
1121         /// Search for the number of occurrences of logged lines which
1122         /// 1. belong to the specified module and
1123         /// 2. match the given regex pattern.
1124         /// Assert that the number of occurrences equals the given `count`
1125         #[cfg(any(test, feature = "_test_utils"))]
1126         pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
1127                 let log_entries = self.lines.lock().unwrap();
1128                 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
1129                         *m == module && pattern.is_match(&l)
1130                 }).map(|(_, c) | { c }).sum();
1131                 assert_eq!(l, count)
1132         }
1133
1134         pub fn assert_log_context_contains(
1135                 &self, module: &str, peer_id: Option<PublicKey>, channel_id: Option<ChannelId>, count: usize
1136         ) {
1137                 let context_entries = self.context.lock().unwrap();
1138                 let l = context_entries.get(&(module, peer_id, channel_id)).unwrap();
1139                 assert_eq!(*l, count)
1140         }
1141 }
1142
1143 impl Logger for TestLogger {
1144         fn log(&self, record: Record) {
1145                 *self.lines.lock().unwrap().entry((record.module_path, format!("{}", record.args))).or_insert(0) += 1;
1146                 *self.context.lock().unwrap().entry((record.module_path, record.peer_id, record.channel_id)).or_insert(0) += 1;
1147                 if record.level >= self.level {
1148                         #[cfg(all(not(ldk_bench), feature = "std"))] {
1149                                 let pfx = format!("{} {} [{}:{}]", self.id, record.level.to_string(), record.module_path, record.line);
1150                                 println!("{:<55}{}", pfx, record.args);
1151                         }
1152                 }
1153         }
1154 }
1155
1156 pub struct TestNodeSigner {
1157         node_secret: SecretKey,
1158 }
1159
1160 impl TestNodeSigner {
1161         pub fn new(node_secret: SecretKey) -> Self {
1162                 Self { node_secret }
1163         }
1164 }
1165
1166 impl NodeSigner for TestNodeSigner {
1167         fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
1168                 unreachable!()
1169         }
1170
1171         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1172                 let node_secret = match recipient {
1173                         Recipient::Node => Ok(&self.node_secret),
1174                         Recipient::PhantomNode => Err(())
1175                 }?;
1176                 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
1177         }
1178
1179         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
1180                 let mut node_secret = match recipient {
1181                         Recipient::Node => Ok(self.node_secret.clone()),
1182                         Recipient::PhantomNode => Err(())
1183                 }?;
1184                 if let Some(tweak) = tweak {
1185                         node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
1186                 }
1187                 Ok(SharedSecret::new(other_key, &node_secret))
1188         }
1189
1190         fn sign_invoice(&self, _: &[u8], _: &[bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
1191                 unreachable!()
1192         }
1193
1194         fn sign_bolt12_invoice_request(
1195                 &self, _invoice_request: &UnsignedInvoiceRequest
1196         ) -> Result<schnorr::Signature, ()> {
1197                 unreachable!()
1198         }
1199
1200         fn sign_bolt12_invoice(
1201                 &self, _invoice: &UnsignedBolt12Invoice,
1202         ) -> Result<schnorr::Signature, ()> {
1203                 unreachable!()
1204         }
1205
1206         fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1207                 unreachable!()
1208         }
1209 }
1210
1211 pub struct TestKeysInterface {
1212         pub backing: sign::PhantomKeysManager,
1213         pub override_random_bytes: Mutex<Option<[u8; 32]>>,
1214         pub disable_revocation_policy_check: bool,
1215         enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
1216         expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
1217         pub unavailable_signers: Mutex<HashSet<[u8; 32]>>,
1218 }
1219
1220 impl EntropySource for TestKeysInterface {
1221         fn get_secure_random_bytes(&self) -> [u8; 32] {
1222                 let override_random_bytes = self.override_random_bytes.lock().unwrap();
1223                 if let Some(bytes) = &*override_random_bytes {
1224                         return *bytes;
1225                 }
1226                 self.backing.get_secure_random_bytes()
1227         }
1228 }
1229
1230 impl NodeSigner for TestKeysInterface {
1231         fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
1232                 self.backing.get_node_id(recipient)
1233         }
1234
1235         fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
1236                 self.backing.ecdh(recipient, other_key, tweak)
1237         }
1238
1239         fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
1240                 self.backing.get_inbound_payment_key_material()
1241         }
1242
1243         fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
1244                 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
1245         }
1246
1247         fn sign_bolt12_invoice_request(
1248                 &self, invoice_request: &UnsignedInvoiceRequest
1249         ) -> Result<schnorr::Signature, ()> {
1250                 self.backing.sign_bolt12_invoice_request(invoice_request)
1251         }
1252
1253         fn sign_bolt12_invoice(
1254                 &self, invoice: &UnsignedBolt12Invoice,
1255         ) -> Result<schnorr::Signature, ()> {
1256                 self.backing.sign_bolt12_invoice(invoice)
1257         }
1258
1259         fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
1260                 self.backing.sign_gossip_message(msg)
1261         }
1262 }
1263
1264 impl SignerProvider for TestKeysInterface {
1265         type EcdsaSigner = TestChannelSigner;
1266         #[cfg(taproot)]
1267         type TaprootSigner = TestChannelSigner;
1268
1269         fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
1270                 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
1271         }
1272
1273         fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner {
1274                 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
1275                 let state = self.make_enforcement_state_cell(keys.commitment_seed);
1276                 let signer = TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check);
1277                 if self.unavailable_signers.lock().unwrap().contains(&channel_keys_id) {
1278                         signer.set_available(false);
1279                 }
1280                 signer
1281         }
1282
1283         fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::EcdsaSigner, msgs::DecodeError> {
1284                 let mut reader = io::Cursor::new(buffer);
1285
1286                 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
1287                 let state = self.make_enforcement_state_cell(inner.commitment_seed);
1288
1289                 Ok(TestChannelSigner::new_with_revoked(
1290                         inner,
1291                         state,
1292                         self.disable_revocation_policy_check
1293                 ))
1294         }
1295
1296         fn get_destination_script(&self, channel_keys_id: [u8; 32]) -> Result<ScriptBuf, ()> { self.backing.get_destination_script(channel_keys_id) }
1297
1298         fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
1299                 match &mut *self.expectations.lock().unwrap() {
1300                         None => self.backing.get_shutdown_scriptpubkey(),
1301                         Some(expectations) => match expectations.pop_front() {
1302                                 None => panic!("Unexpected get_shutdown_scriptpubkey"),
1303                                 Some(expectation) => Ok(expectation.returns),
1304                         },
1305                 }
1306         }
1307 }
1308
1309 impl TestKeysInterface {
1310         pub fn new(seed: &[u8; 32], network: Network) -> Self {
1311                 let now = Duration::from_secs(genesis_block(network).header.time as u64);
1312                 Self {
1313                         backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
1314                         override_random_bytes: Mutex::new(None),
1315                         disable_revocation_policy_check: false,
1316                         enforcement_states: Mutex::new(new_hash_map()),
1317                         expectations: Mutex::new(None),
1318                         unavailable_signers: Mutex::new(new_hash_set()),
1319                 }
1320         }
1321
1322         /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
1323         /// called.
1324         pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
1325                 self.expectations.lock().unwrap()
1326                         .get_or_insert_with(|| VecDeque::new())
1327                         .push_back(expectation);
1328                 self
1329         }
1330
1331         pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner {
1332                 self.derive_channel_signer(channel_value_satoshis, *id)
1333         }
1334
1335         fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
1336                 let mut states = self.enforcement_states.lock().unwrap();
1337                 if !states.contains_key(&commitment_seed) {
1338                         let state = EnforcementState::new();
1339                         states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1340                 }
1341                 let cell = states.get(&commitment_seed).unwrap();
1342                 Arc::clone(cell)
1343         }
1344 }
1345
1346 pub(crate) fn panicking() -> bool {
1347         #[cfg(feature = "std")]
1348         let panicking = ::std::thread::panicking();
1349         #[cfg(not(feature = "std"))]
1350         let panicking = false;
1351         return panicking;
1352 }
1353
1354 impl Drop for TestKeysInterface {
1355         fn drop(&mut self) {
1356                 if panicking() {
1357                         return;
1358                 }
1359
1360                 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1361                         if !expectations.is_empty() {
1362                                 panic!("Unsatisfied expectations: {:?}", expectations);
1363                         }
1364                 }
1365         }
1366 }
1367
1368 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1369 /// returns a [`ShutdownScript`].
1370 pub struct OnGetShutdownScriptpubkey {
1371         /// A shutdown script used to close a channel.
1372         pub returns: ShutdownScript,
1373 }
1374
1375 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1376         fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1377                 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1378         }
1379 }
1380
1381 pub struct TestChainSource {
1382         pub chain_hash: ChainHash,
1383         pub utxo_ret: Mutex<UtxoResult>,
1384         pub get_utxo_call_count: AtomicUsize,
1385         pub watched_txn: Mutex<HashSet<(Txid, ScriptBuf)>>,
1386         pub watched_outputs: Mutex<HashSet<(OutPoint, ScriptBuf)>>,
1387 }
1388
1389 impl TestChainSource {
1390         pub fn new(network: Network) -> Self {
1391                 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1392                 Self {
1393                         chain_hash: ChainHash::using_genesis_block(network),
1394                         utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: Amount::MAX, script_pubkey }))),
1395                         get_utxo_call_count: AtomicUsize::new(0),
1396                         watched_txn: Mutex::new(new_hash_set()),
1397                         watched_outputs: Mutex::new(new_hash_set()),
1398                 }
1399         }
1400         pub fn remove_watched_txn_and_outputs(&self, outpoint: OutPoint, script_pubkey: ScriptBuf) {
1401                 self.watched_outputs.lock().unwrap().remove(&(outpoint, script_pubkey.clone()));
1402                 self.watched_txn.lock().unwrap().remove(&(outpoint.txid, script_pubkey));
1403         }
1404 }
1405
1406 impl UtxoLookup for TestChainSource {
1407         fn get_utxo(&self, chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
1408                 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1409                 if self.chain_hash != *chain_hash {
1410                         return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1411                 }
1412
1413                 self.utxo_ret.lock().unwrap().clone()
1414         }
1415 }
1416
1417 impl chain::Filter for TestChainSource {
1418         fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1419                 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.into()));
1420         }
1421
1422         fn register_output(&self, output: WatchedOutput) {
1423                 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1424         }
1425 }
1426
1427 impl Drop for TestChainSource {
1428         fn drop(&mut self) {
1429                 if panicking() {
1430                         return;
1431                 }
1432         }
1433 }
1434
1435 pub struct TestScorer {
1436         /// Stores a tuple of (scid, ChannelUsage)
1437         scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1438 }
1439
1440 impl TestScorer {
1441         pub fn new() -> Self {
1442                 Self {
1443                         scorer_expectations: RefCell::new(None),
1444                 }
1445         }
1446
1447         pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1448                 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1449         }
1450 }
1451
1452 #[cfg(c_bindings)]
1453 impl crate::util::ser::Writeable for TestScorer {
1454         fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1455 }
1456
1457 impl ScoreLookUp for TestScorer {
1458         type ScoreParams = ();
1459         fn channel_penalty_msat(
1460                 &self, candidate: &CandidateRouteHop, usage: ChannelUsage, _score_params: &Self::ScoreParams
1461         ) -> u64 {
1462                 let short_channel_id = match candidate.globally_unique_short_channel_id() {
1463                         Some(scid) => scid,
1464                         None => return 0,
1465                 };
1466                 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1467                         match scorer_expectations.pop_front() {
1468                                 Some((scid, expectation)) => {
1469                                         assert_eq!(expectation, usage);
1470                                         assert_eq!(scid, short_channel_id);
1471                                 },
1472                                 None => {},
1473                         }
1474                 }
1475                 0
1476         }
1477 }
1478
1479 impl ScoreUpdate for TestScorer {
1480         fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64, _duration_since_epoch: Duration) {}
1481
1482         fn payment_path_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {}
1483
1484         fn probe_failed(&mut self, _actual_path: &Path, _: u64, _duration_since_epoch: Duration) {}
1485
1486         fn probe_successful(&mut self, _actual_path: &Path, _duration_since_epoch: Duration) {}
1487
1488         fn time_passed(&mut self, _duration_since_epoch: Duration) {}
1489 }
1490
1491 #[cfg(c_bindings)]
1492 impl crate::routing::scoring::Score for TestScorer {}
1493
1494 impl Drop for TestScorer {
1495         fn drop(&mut self) {
1496                 #[cfg(feature = "std")] {
1497                         if std::thread::panicking() {
1498                                 return;
1499                         }
1500                 }
1501
1502                 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1503                         if !scorer_expectations.is_empty() {
1504                                 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1505                         }
1506                 }
1507         }
1508 }
1509
1510 pub struct TestWalletSource {
1511         secret_key: SecretKey,
1512         utxos: RefCell<Vec<Utxo>>,
1513         secp: Secp256k1<bitcoin::secp256k1::All>,
1514 }
1515
1516 impl TestWalletSource {
1517         pub fn new(secret_key: SecretKey) -> Self {
1518                 Self {
1519                         secret_key,
1520                         utxos: RefCell::new(Vec::new()),
1521                         secp: Secp256k1::new(),
1522                 }
1523         }
1524
1525         pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: Amount) -> TxOut {
1526                 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1527                 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1528                 self.utxos.borrow_mut().push(utxo.clone());
1529                 utxo.output
1530         }
1531
1532         pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1533                 let output = utxo.output.clone();
1534                 self.utxos.borrow_mut().push(utxo);
1535                 output
1536         }
1537
1538         pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1539                 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1540         }
1541 }
1542
1543 impl WalletSource for TestWalletSource {
1544         fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1545                 Ok(self.utxos.borrow().clone())
1546         }
1547
1548         fn get_change_script(&self) -> Result<ScriptBuf, ()> {
1549                 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1550                 Ok(ScriptBuf::new_p2pkh(&public_key.pubkey_hash()))
1551         }
1552
1553         fn sign_psbt(&self, psbt: Psbt) -> Result<Transaction, ()> {
1554                 let mut tx = psbt.extract_tx_unchecked_fee_rate();
1555                 let utxos = self.utxos.borrow();
1556                 for i in 0..tx.input.len() {
1557                         if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1558                                 let sighash = SighashCache::new(&tx)
1559                                         .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1560                                         .map_err(|_| ())?;
1561                                 let sig = self.secp.sign_ecdsa(&secp256k1::Message::from_digest(sighash.to_byte_array()), &self.secret_key);
1562                                 let bitcoin_sig = bitcoin::ecdsa::Signature { sig, hash_ty: EcdsaSighashType::All };
1563                                 tx.input[i].script_sig = Builder::new()
1564                                         .push_slice(&bitcoin_sig.serialize())
1565                                         .push_slice(&self.secret_key.public_key(&self.secp).serialize())
1566                                         .into_script();
1567                         }
1568                 }
1569                 Ok(tx)
1570         }
1571 }