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