1 // This file is Copyright its original authors, visible in version control
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
11 use crate::chain::WatchedOutput;
12 use crate::chain::chaininterface;
13 use crate::chain::chaininterface::ConfirmationTarget;
14 use crate::chain::chainmonitor;
15 use crate::chain::chainmonitor::MonitorUpdateId;
16 use crate::chain::channelmonitor;
17 use crate::chain::channelmonitor::MonitorEvent;
18 use crate::chain::transaction::OutPoint;
21 use crate::events::bump_transaction::{WalletSource, Utxo};
22 use crate::ln::channelmanager;
23 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
24 use crate::ln::{msgs, wire};
25 use crate::ln::msgs::LightningError;
26 use crate::ln::script::ShutdownScript;
27 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
28 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
29 use crate::routing::router::{find_route, InFlightHtlcs, Path, Route, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
30 use crate::routing::scoring::{ChannelUsage, Score};
31 use crate::util::config::UserConfig;
32 use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
33 use crate::util::logger::{Logger, Level, Record};
34 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
35 use crate::util::persist::KVStore;
37 use bitcoin::EcdsaSighashType;
38 use bitcoin::blockdata::constants::ChainHash;
39 use bitcoin::blockdata::constants::genesis_block;
40 use bitcoin::blockdata::transaction::{Transaction, TxOut};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::block::Block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::hash_types::{BlockHash, Txid};
46 use bitcoin::util::sighash::SighashCache;
48 use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature, Scalar};
49 use bitcoin::secp256k1::ecdh::SharedSecret;
50 use bitcoin::secp256k1::ecdsa::RecoverableSignature;
52 #[cfg(any(test, feature = "_test_utils"))]
56 use crate::prelude::*;
57 use core::cell::RefCell;
58 use core::ops::DerefMut;
59 use core::time::Duration;
60 use crate::sync::{Mutex, Arc};
61 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
63 use bitcoin::bech32::u5;
64 use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
66 #[cfg(feature = "std")]
67 use std::time::{SystemTime, UNIX_EPOCH};
68 use bitcoin::Sequence;
70 pub fn pubkey(byte: u8) -> PublicKey {
71 let secp_ctx = Secp256k1::new();
72 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
75 pub fn privkey(byte: u8) -> SecretKey {
76 SecretKey::from_slice(&[byte; 32]).unwrap()
79 pub struct TestVecWriter(pub Vec<u8>);
80 impl Writer for TestVecWriter {
81 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
82 self.0.extend_from_slice(buf);
87 pub struct TestFeeEstimator {
88 pub sat_per_kw: Mutex<u32>,
90 impl chaininterface::FeeEstimator for TestFeeEstimator {
91 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
92 *self.sat_per_kw.lock().unwrap()
96 pub struct TestRouter<'a> {
97 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
98 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
99 pub scorer: &'a Mutex<TestScorer>,
102 impl<'a> TestRouter<'a> {
103 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a Mutex<TestScorer>) -> Self {
104 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
107 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
108 let mut expected_routes = self.next_routes.lock().unwrap();
109 expected_routes.push_back((query, result));
113 impl<'a> Router for TestRouter<'a> {
115 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
116 inflight_htlcs: InFlightHtlcs
117 ) -> Result<Route, msgs::LightningError> {
118 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
119 assert_eq!(find_route_query, *params);
120 if let Ok(ref route) = find_route_res {
121 let mut binding = self.scorer.lock().unwrap();
122 let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), &inflight_htlcs);
123 for path in &route.paths {
124 let mut aggregate_msat = 0u64;
125 for (idx, hop) in path.hops.iter().rev().enumerate() {
126 aggregate_msat += hop.fee_msat;
127 let usage = ChannelUsage {
128 amount_msat: aggregate_msat,
129 inflight_htlc_msat: 0,
130 effective_capacity: EffectiveCapacity::Unknown,
133 // Since the path is reversed, the last element in our iteration is the first
135 if idx == path.hops.len() - 1 {
136 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &());
138 let curr_hop_path_idx = path.hops.len() - 1 - idx;
139 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path.hops[curr_hop_path_idx - 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage, &());
144 return find_route_res;
146 let logger = TestLogger::new();
148 payer, params, &self.network_graph, first_hops, &logger,
149 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().unwrap().deref_mut(), &inflight_htlcs), &(),
155 impl<'a> Drop for TestRouter<'a> {
157 #[cfg(feature = "std")] {
158 if std::thread::panicking() {
162 assert!(self.next_routes.lock().unwrap().is_empty());
166 pub struct OnlyReadsKeysInterface {}
168 impl EntropySource for OnlyReadsKeysInterface {
169 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
171 impl SignerProvider for OnlyReadsKeysInterface {
172 type Signer = EnforcingSigner;
174 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
176 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
178 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
179 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
180 let state = Arc::new(Mutex::new(EnforcementState::new()));
182 Ok(EnforcingSigner::new_with_revoked(
189 fn get_destination_script(&self) -> Result<Script, ()> { Err(()) }
190 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
193 pub struct TestChainMonitor<'a> {
194 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
195 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
196 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
197 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
198 pub keys_manager: &'a TestKeysInterface,
199 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
200 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
202 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
204 impl<'a> TestChainMonitor<'a> {
205 pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist<EnforcingSigner>, keys_manager: &'a TestKeysInterface) -> Self {
207 added_monitors: Mutex::new(Vec::new()),
208 monitor_updates: Mutex::new(HashMap::new()),
209 latest_monitor_update_id: Mutex::new(HashMap::new()),
210 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
212 expect_channel_force_closed: Mutex::new(None),
216 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
217 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
218 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
221 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
222 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
223 // At every point where we get a monitor update, we should be able to send a useful monitor
224 // to a watchtower and disk...
225 let mut w = TestVecWriter(Vec::new());
226 monitor.write(&mut w).unwrap();
227 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
228 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
229 assert!(new_monitor == monitor);
230 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
231 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
232 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
233 self.chain_monitor.watch_channel(funding_txo, new_monitor)
236 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
237 // Every monitor update should survive roundtrip
238 let mut w = TestVecWriter(Vec::new());
239 update.write(&mut w).unwrap();
240 assert!(channelmonitor::ChannelMonitorUpdate::read(
241 &mut io::Cursor::new(&w.0)).unwrap() == *update);
243 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
245 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
246 assert_eq!(funding_txo.to_channel_id(), exp.0);
247 assert_eq!(update.updates.len(), 1);
248 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
249 assert_eq!(should_broadcast, exp.1);
253 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
254 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
255 let update_res = self.chain_monitor.update_channel(funding_txo, update);
256 // At every point where we get a monitor update, we should be able to send a useful monitor
257 // to a watchtower and disk...
258 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
260 monitor.write(&mut w).unwrap();
261 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
262 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
263 assert!(new_monitor == *monitor);
264 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
268 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
269 return self.chain_monitor.release_pending_monitor_events();
273 pub struct TestPersister {
274 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
276 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
277 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
278 /// MonitorUpdateId here.
279 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
280 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
281 /// MonitorUpdateId here.
282 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
285 pub fn new() -> Self {
287 update_rets: Mutex::new(VecDeque::new()),
288 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
289 offchain_monitor_updates: Mutex::new(HashMap::new()),
293 /// Queue an update status to return.
294 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
295 self.update_rets.lock().unwrap().push_back(next_ret);
298 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
299 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
300 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
303 chain::ChannelMonitorUpdateStatus::Completed
306 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
307 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
308 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
311 if update.is_none() {
312 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
314 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
320 pub(crate) struct TestStore {
321 persisted_bytes: Mutex<HashMap<String, HashMap<String, Vec<u8>>>>,
322 did_persist: Arc<AtomicBool>,
327 pub fn new(read_only: bool) -> Self {
328 let persisted_bytes = Mutex::new(HashMap::new());
329 let did_persist = Arc::new(AtomicBool::new(false));
330 Self { persisted_bytes, did_persist, read_only }
333 pub fn get_persisted_bytes(&self, namespace: &str, key: &str) -> Option<Vec<u8>> {
334 let persisted_lock = self.persisted_bytes.lock().unwrap();
335 persisted_lock.get(namespace).and_then(|e| e.get(key).cloned())
338 pub fn get_and_clear_did_persist(&self) -> bool {
339 self.did_persist.swap(false, Ordering::Relaxed)
343 impl KVStore for TestStore {
344 type Reader = io::Cursor<Vec<u8>>;
346 fn read(&self, namespace: &str, key: &str) -> io::Result<Self::Reader> {
347 let persisted_lock = self.persisted_bytes.lock().unwrap();
348 if let Some(outer_ref) = persisted_lock.get(namespace) {
349 if let Some(inner_ref) = outer_ref.get(key) {
350 let bytes = inner_ref.clone();
351 Ok(io::Cursor::new(bytes))
353 Err(io::Error::new(io::ErrorKind::NotFound, "Key not found"))
356 Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found"))
360 fn write(&self, namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> {
362 return Err(io::Error::new(
363 io::ErrorKind::PermissionDenied,
367 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
368 let outer_e = persisted_lock.entry(namespace.to_string()).or_insert(HashMap::new());
369 let mut bytes = Vec::new();
370 bytes.write_all(buf)?;
371 outer_e.insert(key.to_string(), bytes);
372 self.did_persist.store(true, Ordering::SeqCst);
376 fn remove(&self, namespace: &str, key: &str) -> io::Result<()> {
378 return Err(io::Error::new(
379 io::ErrorKind::PermissionDenied,
384 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
385 if let Some(outer_ref) = persisted_lock.get_mut(namespace) {
386 outer_ref.remove(&key.to_string());
387 self.did_persist.store(true, Ordering::SeqCst);
393 fn list(&self, namespace: &str) -> io::Result<Vec<String>> {
394 let mut persisted_lock = self.persisted_bytes.lock().unwrap();
395 match persisted_lock.entry(namespace.to_string()) {
396 hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()),
397 hash_map::Entry::Vacant(_) => Ok(Vec::new()),
402 pub struct TestBroadcaster {
403 pub txn_broadcasted: Mutex<Vec<Transaction>>,
404 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
407 impl TestBroadcaster {
408 pub fn new(network: Network) -> Self {
410 txn_broadcasted: Mutex::new(Vec::new()),
411 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
415 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
416 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
419 pub fn txn_broadcast(&self) -> Vec<Transaction> {
420 self.txn_broadcasted.lock().unwrap().split_off(0)
423 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
424 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
425 let mut seen = HashSet::new();
426 txn.retain(|tx| seen.insert(tx.txid()));
431 impl chaininterface::BroadcasterInterface for TestBroadcaster {
432 fn broadcast_transactions(&self, txs: &[&Transaction]) {
434 let lock_time = tx.lock_time.0;
435 assert!(lock_time < 1_500_000_000);
436 if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
437 for inp in tx.input.iter() {
438 if inp.sequence != Sequence::MAX {
439 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
444 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
445 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
449 pub struct TestChannelMessageHandler {
450 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
451 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
452 connected_peers: Mutex<HashSet<PublicKey>>,
453 pub message_fetch_counter: AtomicUsize,
454 genesis_hash: ChainHash,
457 impl TestChannelMessageHandler {
458 pub fn new(genesis_hash: ChainHash) -> Self {
459 TestChannelMessageHandler {
460 pending_events: Mutex::new(Vec::new()),
461 expected_recv_msgs: Mutex::new(None),
462 connected_peers: Mutex::new(HashSet::new()),
463 message_fetch_counter: AtomicUsize::new(0),
469 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
470 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
471 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
472 expected_msgs.as_mut().unwrap().push(ev);
475 fn received_msg(&self, _ev: wire::Message<()>) {
476 let mut msgs = self.expected_recv_msgs.lock().unwrap();
477 if msgs.is_none() { return; }
478 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
480 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
481 msgs.as_mut().unwrap().remove(0);
485 impl Drop for TestChannelMessageHandler {
487 #[cfg(feature = "std")]
489 let l = self.expected_recv_msgs.lock().unwrap();
490 if !std::thread::panicking() {
491 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
497 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
498 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
499 self.received_msg(wire::Message::OpenChannel(msg.clone()));
501 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
502 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
504 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
505 self.received_msg(wire::Message::FundingCreated(msg.clone()));
507 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
508 self.received_msg(wire::Message::FundingSigned(msg.clone()));
510 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
511 self.received_msg(wire::Message::ChannelReady(msg.clone()));
513 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
514 self.received_msg(wire::Message::Shutdown(msg.clone()));
516 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
517 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
519 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
520 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
522 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
523 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
525 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
526 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
528 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
529 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
531 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
532 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
534 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
535 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
537 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
538 self.received_msg(wire::Message::UpdateFee(msg.clone()));
540 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
541 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
543 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
544 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
546 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
547 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
549 fn peer_disconnected(&self, their_node_id: &PublicKey) {
550 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
552 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
553 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
554 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
555 // bother re-generating the expected Init message in all tests.
558 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
559 self.received_msg(wire::Message::Error(msg.clone()));
561 fn provided_node_features(&self) -> NodeFeatures {
562 channelmanager::provided_node_features(&UserConfig::default())
564 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
565 channelmanager::provided_init_features(&UserConfig::default())
568 fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
569 Some(vec![self.genesis_hash])
572 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
573 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
576 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
577 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
580 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
581 self.received_msg(wire::Message::TxAddInput(msg.clone()));
584 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
585 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
588 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
589 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
592 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
593 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
596 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
597 self.received_msg(wire::Message::TxComplete(msg.clone()));
600 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
601 self.received_msg(wire::Message::TxSignatures(msg.clone()));
604 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
605 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
608 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
609 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
612 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
613 self.received_msg(wire::Message::TxAbort(msg.clone()));
617 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
618 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
619 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
620 let mut pending_events = self.pending_events.lock().unwrap();
621 let mut ret = Vec::new();
622 mem::swap(&mut ret, &mut *pending_events);
627 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
628 use bitcoin::secp256k1::ffi::Signature as FFISignature;
629 let secp_ctx = Secp256k1::new();
630 let network = Network::Testnet;
631 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
632 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
633 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
634 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
635 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
636 features: ChannelFeatures::empty(),
637 chain_hash: genesis_block(network).header.block_hash(),
638 short_channel_id: short_chan_id,
639 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
640 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
641 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
642 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
643 excess_data: Vec::new(),
647 msgs::ChannelAnnouncement {
648 node_signature_1: Signature::from(FFISignature::new()),
649 node_signature_2: Signature::from(FFISignature::new()),
650 bitcoin_signature_1: Signature::from(FFISignature::new()),
651 bitcoin_signature_2: Signature::from(FFISignature::new()),
652 contents: unsigned_ann,
657 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
658 use bitcoin::secp256k1::ffi::Signature as FFISignature;
659 let network = Network::Testnet;
660 msgs::ChannelUpdate {
661 signature: Signature::from(unsafe { FFISignature::new() }),
662 contents: msgs::UnsignedChannelUpdate {
663 chain_hash: genesis_block(network).header.block_hash(),
664 short_channel_id: short_chan_id,
667 cltv_expiry_delta: 0,
668 htlc_minimum_msat: 0,
669 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
671 fee_proportional_millionths: 0,
677 pub struct TestRoutingMessageHandler {
678 pub chan_upds_recvd: AtomicUsize,
679 pub chan_anns_recvd: AtomicUsize,
680 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
681 pub request_full_sync: AtomicBool,
684 impl TestRoutingMessageHandler {
685 pub fn new() -> Self {
686 TestRoutingMessageHandler {
687 chan_upds_recvd: AtomicUsize::new(0),
688 chan_anns_recvd: AtomicUsize::new(0),
689 pending_events: Mutex::new(vec![]),
690 request_full_sync: AtomicBool::new(false),
694 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
695 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
696 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
698 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
699 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
700 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
702 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
703 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
704 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
706 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
707 let chan_upd_1 = get_dummy_channel_update(starting_point);
708 let chan_upd_2 = get_dummy_channel_update(starting_point);
709 let chan_ann = get_dummy_channel_announcement(starting_point);
711 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
714 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
718 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
719 if !init_msg.features.supports_gossip_queries() {
723 #[allow(unused_mut, unused_assignments)]
724 let mut gossip_start_time = 0;
725 #[cfg(feature = "std")]
727 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
728 if self.request_full_sync.load(Ordering::Acquire) {
729 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
731 gossip_start_time -= 60 * 60; // an hour ago
735 let mut pending_events = self.pending_events.lock().unwrap();
736 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
737 node_id: their_node_id.clone(),
738 msg: msgs::GossipTimestampFilter {
739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
740 first_timestamp: gossip_start_time as u32,
741 timestamp_range: u32::max_value(),
747 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
751 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
755 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
759 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
763 fn provided_node_features(&self) -> NodeFeatures {
764 let mut features = NodeFeatures::empty();
765 features.set_gossip_queries_optional();
769 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
770 let mut features = InitFeatures::empty();
771 features.set_gossip_queries_optional();
775 fn processing_queue_high(&self) -> bool { false }
778 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
779 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
780 let mut ret = Vec::new();
781 let mut pending_events = self.pending_events.lock().unwrap();
782 core::mem::swap(&mut ret, &mut pending_events);
787 pub struct TestLogger {
789 pub(crate) id: String,
790 pub lines: Mutex<HashMap<(String, String), usize>>,
794 pub fn new() -> TestLogger {
795 Self::with_id("".to_owned())
797 pub fn with_id(id: String) -> TestLogger {
801 lines: Mutex::new(HashMap::new())
804 pub fn enable(&mut self, level: Level) {
807 pub fn assert_log(&self, module: String, line: String, count: usize) {
808 let log_entries = self.lines.lock().unwrap();
809 assert_eq!(log_entries.get(&(module, line)), Some(&count));
812 /// Search for the number of occurrence of the logged lines which
813 /// 1. belongs to the specified module and
814 /// 2. contains `line` in it.
815 /// And asserts if the number of occurrences is the same with the given `count`
816 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
817 let log_entries = self.lines.lock().unwrap();
818 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
819 m == module && l.contains(line)
820 }).map(|(_, c) | { c }).sum();
824 /// Search for the number of occurrences of logged lines which
825 /// 1. belong to the specified module and
826 /// 2. match the given regex pattern.
827 /// Assert that the number of occurrences equals the given `count`
828 #[cfg(any(test, feature = "_test_utils"))]
829 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
830 let log_entries = self.lines.lock().unwrap();
831 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
832 m == module && pattern.is_match(&l)
833 }).map(|(_, c) | { c }).sum();
838 impl Logger for TestLogger {
839 fn log(&self, record: &Record) {
840 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
841 if record.level >= self.level {
842 #[cfg(all(not(ldk_bench), feature = "std"))]
843 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
848 pub struct TestNodeSigner {
849 node_secret: SecretKey,
852 impl TestNodeSigner {
853 pub fn new(node_secret: SecretKey) -> Self {
858 impl NodeSigner for TestNodeSigner {
859 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
863 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
864 let node_secret = match recipient {
865 Recipient::Node => Ok(&self.node_secret),
866 Recipient::PhantomNode => Err(())
868 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
871 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
872 let mut node_secret = match recipient {
873 Recipient::Node => Ok(self.node_secret.clone()),
874 Recipient::PhantomNode => Err(())
876 if let Some(tweak) = tweak {
877 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
879 Ok(SharedSecret::new(other_key, &node_secret))
882 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
886 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
891 pub struct TestKeysInterface {
892 pub backing: sign::PhantomKeysManager,
893 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
894 pub disable_revocation_policy_check: bool,
895 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
896 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
899 impl EntropySource for TestKeysInterface {
900 fn get_secure_random_bytes(&self) -> [u8; 32] {
901 let override_random_bytes = self.override_random_bytes.lock().unwrap();
902 if let Some(bytes) = &*override_random_bytes {
905 self.backing.get_secure_random_bytes()
909 impl NodeSigner for TestKeysInterface {
910 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
911 self.backing.get_node_id(recipient)
914 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
915 self.backing.ecdh(recipient, other_key, tweak)
918 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
919 self.backing.get_inbound_payment_key_material()
922 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
923 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
926 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
927 self.backing.sign_gossip_message(msg)
931 impl SignerProvider for TestKeysInterface {
932 type Signer = EnforcingSigner;
934 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
935 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
938 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
939 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
940 let state = self.make_enforcement_state_cell(keys.commitment_seed);
941 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
944 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
945 let mut reader = io::Cursor::new(buffer);
947 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
948 let state = self.make_enforcement_state_cell(inner.commitment_seed);
950 Ok(EnforcingSigner::new_with_revoked(
953 self.disable_revocation_policy_check
957 fn get_destination_script(&self) -> Result<Script, ()> { self.backing.get_destination_script() }
959 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
960 match &mut *self.expectations.lock().unwrap() {
961 None => self.backing.get_shutdown_scriptpubkey(),
962 Some(expectations) => match expectations.pop_front() {
963 None => panic!("Unexpected get_shutdown_scriptpubkey"),
964 Some(expectation) => Ok(expectation.returns),
970 impl TestKeysInterface {
971 pub fn new(seed: &[u8; 32], network: Network) -> Self {
972 let now = Duration::from_secs(genesis_block(network).header.time as u64);
974 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
975 override_random_bytes: Mutex::new(None),
976 disable_revocation_policy_check: false,
977 enforcement_states: Mutex::new(HashMap::new()),
978 expectations: Mutex::new(None),
982 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
984 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
985 self.expectations.lock().unwrap()
986 .get_or_insert_with(|| VecDeque::new())
987 .push_back(expectation);
991 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
992 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
993 let state = self.make_enforcement_state_cell(keys.commitment_seed);
994 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
997 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
998 let mut states = self.enforcement_states.lock().unwrap();
999 if !states.contains_key(&commitment_seed) {
1000 let state = EnforcementState::new();
1001 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
1003 let cell = states.get(&commitment_seed).unwrap();
1008 pub(crate) fn panicking() -> bool {
1009 #[cfg(feature = "std")]
1010 let panicking = ::std::thread::panicking();
1011 #[cfg(not(feature = "std"))]
1012 let panicking = false;
1016 impl Drop for TestKeysInterface {
1017 fn drop(&mut self) {
1022 if let Some(expectations) = &*self.expectations.lock().unwrap() {
1023 if !expectations.is_empty() {
1024 panic!("Unsatisfied expectations: {:?}", expectations);
1030 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
1031 /// returns a [`ShutdownScript`].
1032 pub struct OnGetShutdownScriptpubkey {
1033 /// A shutdown script used to close a channel.
1034 pub returns: ShutdownScript,
1037 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
1038 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1039 f.debug_struct("OnGetShutdownScriptpubkey").finish()
1043 pub struct TestChainSource {
1044 pub genesis_hash: BlockHash,
1045 pub utxo_ret: Mutex<UtxoResult>,
1046 pub get_utxo_call_count: AtomicUsize,
1047 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
1048 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
1051 impl TestChainSource {
1052 pub fn new(network: Network) -> Self {
1053 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
1055 genesis_hash: genesis_block(network).block_hash(),
1056 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1057 get_utxo_call_count: AtomicUsize::new(0),
1058 watched_txn: Mutex::new(HashSet::new()),
1059 watched_outputs: Mutex::new(HashSet::new()),
1064 impl UtxoLookup for TestChainSource {
1065 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
1066 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1067 if self.genesis_hash != *genesis_hash {
1068 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1071 self.utxo_ret.lock().unwrap().clone()
1075 impl chain::Filter for TestChainSource {
1076 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1077 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
1080 fn register_output(&self, output: WatchedOutput) {
1081 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1085 impl Drop for TestChainSource {
1086 fn drop(&mut self) {
1093 pub struct TestScorer {
1094 /// Stores a tuple of (scid, ChannelUsage)
1095 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1099 pub fn new() -> Self {
1101 scorer_expectations: RefCell::new(None),
1105 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1106 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1111 impl crate::util::ser::Writeable for TestScorer {
1112 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1115 impl Score for TestScorer {
1116 type ScoreParams = ();
1117 fn channel_penalty_msat(
1118 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams
1120 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1121 match scorer_expectations.pop_front() {
1122 Some((scid, expectation)) => {
1123 assert_eq!(expectation, usage);
1124 assert_eq!(scid, short_channel_id);
1132 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {}
1134 fn payment_path_successful(&mut self, _actual_path: &Path) {}
1136 fn probe_failed(&mut self, _actual_path: &Path, _: u64) {}
1138 fn probe_successful(&mut self, _actual_path: &Path) {}
1141 impl Drop for TestScorer {
1142 fn drop(&mut self) {
1143 #[cfg(feature = "std")] {
1144 if std::thread::panicking() {
1149 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1150 if !scorer_expectations.is_empty() {
1151 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1157 pub struct TestWalletSource {
1158 secret_key: SecretKey,
1159 utxos: RefCell<Vec<Utxo>>,
1160 secp: Secp256k1<bitcoin::secp256k1::All>,
1163 impl TestWalletSource {
1164 pub fn new(secret_key: SecretKey) -> Self {
1167 utxos: RefCell::new(Vec::new()),
1168 secp: Secp256k1::new(),
1172 pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1173 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1174 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1175 self.utxos.borrow_mut().push(utxo.clone());
1179 pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1180 let output = utxo.output.clone();
1181 self.utxos.borrow_mut().push(utxo);
1185 pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1186 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1190 impl WalletSource for TestWalletSource {
1191 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1192 Ok(self.utxos.borrow().clone())
1195 fn get_change_script(&self) -> Result<Script, ()> {
1196 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1197 Ok(Script::new_p2pkh(&public_key.pubkey_hash()))
1200 fn sign_tx(&self, mut tx: Transaction) -> Result<Transaction, ()> {
1201 let utxos = self.utxos.borrow();
1202 for i in 0..tx.input.len() {
1203 if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1204 let sighash = SighashCache::new(&tx)
1205 .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1207 let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key);
1208 let bitcoin_sig = bitcoin::EcdsaSig { sig, hash_ty: EcdsaSighashType::All }.to_vec();
1209 tx.input[i].script_sig = Builder::new()
1210 .push_slice(&bitcoin_sig)
1211 .push_slice(&self.secret_key.public_key(&self.secp).serialize())