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