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