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