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