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