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