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