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