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