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::offers::invoice::UnsignedBolt12Invoice;
28 use crate::offers::invoice_request::UnsignedInvoiceRequest;
29 use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
30 use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult};
31 use crate::routing::router::{find_route, InFlightHtlcs, Path, Route, RouteParameters, Router, ScorerAccountingForInFlightHtlcs};
32 use crate::routing::scoring::{ChannelUsage, Score};
33 use crate::util::config::UserConfig;
34 use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState};
35 use crate::util::logger::{Logger, Level, Record};
36 use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable};
38 use bitcoin::EcdsaSighashType;
39 use bitcoin::blockdata::constants::ChainHash;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::blockdata::transaction::{Transaction, TxOut};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::block::Block;
45 use bitcoin::network::constants::Network;
46 use bitcoin::hash_types::{BlockHash, Txid};
47 use bitcoin::util::sighash::SighashCache;
49 use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
50 use bitcoin::secp256k1::ecdh::SharedSecret;
51 use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
52 use bitcoin::secp256k1::schnorr;
54 #[cfg(any(test, feature = "_test_utils"))]
58 use crate::prelude::*;
59 use core::cell::RefCell;
60 use core::ops::DerefMut;
61 use core::time::Duration;
62 use crate::sync::{Mutex, Arc};
63 use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
65 use bitcoin::bech32::u5;
66 use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider};
68 #[cfg(feature = "std")]
69 use std::time::{SystemTime, UNIX_EPOCH};
70 use bitcoin::Sequence;
72 pub fn pubkey(byte: u8) -> PublicKey {
73 let secp_ctx = Secp256k1::new();
74 PublicKey::from_secret_key(&secp_ctx, &privkey(byte))
77 pub fn privkey(byte: u8) -> SecretKey {
78 SecretKey::from_slice(&[byte; 32]).unwrap()
81 pub struct TestVecWriter(pub Vec<u8>);
82 impl Writer for TestVecWriter {
83 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
84 self.0.extend_from_slice(buf);
89 pub struct TestFeeEstimator {
90 pub sat_per_kw: Mutex<u32>,
92 impl chaininterface::FeeEstimator for TestFeeEstimator {
93 fn get_est_sat_per_1000_weight(&self, _confirmation_target: ConfirmationTarget) -> u32 {
94 *self.sat_per_kw.lock().unwrap()
98 pub struct TestRouter<'a> {
99 pub network_graph: Arc<NetworkGraph<&'a TestLogger>>,
100 pub next_routes: Mutex<VecDeque<(RouteParameters, Result<Route, LightningError>)>>,
101 pub scorer: &'a Mutex<TestScorer>,
104 impl<'a> TestRouter<'a> {
105 pub fn new(network_graph: Arc<NetworkGraph<&'a TestLogger>>, scorer: &'a Mutex<TestScorer>) -> Self {
106 Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer }
109 pub fn expect_find_route(&self, query: RouteParameters, result: Result<Route, LightningError>) {
110 let mut expected_routes = self.next_routes.lock().unwrap();
111 expected_routes.push_back((query, result));
115 impl<'a> Router for TestRouter<'a> {
117 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
118 inflight_htlcs: InFlightHtlcs
119 ) -> Result<Route, msgs::LightningError> {
120 if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
121 assert_eq!(find_route_query, *params);
122 if let Ok(ref route) = find_route_res {
123 let mut binding = self.scorer.lock().unwrap();
124 let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), &inflight_htlcs);
125 for path in &route.paths {
126 let mut aggregate_msat = 0u64;
127 for (idx, hop) in path.hops.iter().rev().enumerate() {
128 aggregate_msat += hop.fee_msat;
129 let usage = ChannelUsage {
130 amount_msat: aggregate_msat,
131 inflight_htlc_msat: 0,
132 effective_capacity: EffectiveCapacity::Unknown,
135 // Since the path is reversed, the last element in our iteration is the first
137 if idx == path.hops.len() - 1 {
138 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &());
140 let curr_hop_path_idx = path.hops.len() - 1 - idx;
141 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, &());
146 return find_route_res;
148 let logger = TestLogger::new();
150 payer, params, &self.network_graph, first_hops, &logger,
151 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().unwrap().deref_mut(), &inflight_htlcs), &(),
157 impl<'a> Drop for TestRouter<'a> {
159 #[cfg(feature = "std")] {
160 if std::thread::panicking() {
164 assert!(self.next_routes.lock().unwrap().is_empty());
168 pub struct OnlyReadsKeysInterface {}
170 impl EntropySource for OnlyReadsKeysInterface {
171 fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }}
173 impl SignerProvider for OnlyReadsKeysInterface {
174 type Signer = EnforcingSigner;
176 fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); }
178 fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); }
180 fn read_chan_signer(&self, mut reader: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
181 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
182 let state = Arc::new(Mutex::new(EnforcementState::new()));
184 Ok(EnforcingSigner::new_with_revoked(
191 fn get_destination_script(&self) -> Result<Script, ()> { Err(()) }
192 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> { Err(()) }
195 pub struct TestChainMonitor<'a> {
196 pub added_monitors: Mutex<Vec<(OutPoint, channelmonitor::ChannelMonitor<EnforcingSigner>)>>,
197 pub monitor_updates: Mutex<HashMap<[u8; 32], Vec<channelmonitor::ChannelMonitorUpdate>>>,
198 pub latest_monitor_update_id: Mutex<HashMap<[u8; 32], (OutPoint, u64, MonitorUpdateId)>>,
199 pub chain_monitor: chainmonitor::ChainMonitor<EnforcingSigner, &'a TestChainSource, &'a chaininterface::BroadcasterInterface, &'a TestFeeEstimator, &'a TestLogger, &'a chainmonitor::Persist<EnforcingSigner>>,
200 pub keys_manager: &'a TestKeysInterface,
201 /// If this is set to Some(), the next update_channel call (not watch_channel) must be a
202 /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given
204 pub expect_channel_force_closed: Mutex<Option<([u8; 32], bool)>>,
206 impl<'a> TestChainMonitor<'a> {
207 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 {
209 added_monitors: Mutex::new(Vec::new()),
210 monitor_updates: Mutex::new(HashMap::new()),
211 latest_monitor_update_id: Mutex::new(HashMap::new()),
212 chain_monitor: chainmonitor::ChainMonitor::new(chain_source, broadcaster, logger, fee_estimator, persister),
214 expect_channel_force_closed: Mutex::new(None),
218 pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) {
219 let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone();
220 self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap();
223 impl<'a> chain::Watch<EnforcingSigner> for TestChainMonitor<'a> {
224 fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor<EnforcingSigner>) -> chain::ChannelMonitorUpdateStatus {
225 // At every point where we get a monitor update, we should be able to send a useful monitor
226 // to a watchtower and disk...
227 let mut w = TestVecWriter(Vec::new());
228 monitor.write(&mut w).unwrap();
229 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
230 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
231 assert!(new_monitor == monitor);
232 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
233 (funding_txo, monitor.get_latest_update_id(), MonitorUpdateId::from_new_monitor(&monitor)));
234 self.added_monitors.lock().unwrap().push((funding_txo, monitor));
235 self.chain_monitor.watch_channel(funding_txo, new_monitor)
238 fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus {
239 // Every monitor update should survive roundtrip
240 let mut w = TestVecWriter(Vec::new());
241 update.write(&mut w).unwrap();
242 assert!(channelmonitor::ChannelMonitorUpdate::read(
243 &mut io::Cursor::new(&w.0)).unwrap() == *update);
245 self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone());
247 if let Some(exp) = self.expect_channel_force_closed.lock().unwrap().take() {
248 assert_eq!(funding_txo.to_channel_id(), exp.0);
249 assert_eq!(update.updates.len(), 1);
250 if let channelmonitor::ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
251 assert_eq!(should_broadcast, exp.1);
255 self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(),
256 (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update)));
257 let update_res = self.chain_monitor.update_channel(funding_txo, update);
258 // At every point where we get a monitor update, we should be able to send a useful monitor
259 // to a watchtower and disk...
260 let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap();
262 monitor.write(&mut w).unwrap();
263 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
264 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1;
265 assert!(new_monitor == *monitor);
266 self.added_monitors.lock().unwrap().push((funding_txo, new_monitor));
270 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)> {
271 return self.chain_monitor.release_pending_monitor_events();
275 pub struct TestPersister {
276 /// The queue of update statuses we'll return. If none are queued, ::Completed will always be
278 pub update_rets: Mutex<VecDeque<chain::ChannelMonitorUpdateStatus>>,
279 /// When we get an update_persisted_channel call with no ChannelMonitorUpdate, we insert the
280 /// MonitorUpdateId here.
281 pub chain_sync_monitor_persistences: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
282 /// When we get an update_persisted_channel call *with* a ChannelMonitorUpdate, we insert the
283 /// MonitorUpdateId here.
284 pub offchain_monitor_updates: Mutex<HashMap<OutPoint, HashSet<MonitorUpdateId>>>,
287 pub fn new() -> Self {
289 update_rets: Mutex::new(VecDeque::new()),
290 chain_sync_monitor_persistences: Mutex::new(HashMap::new()),
291 offchain_monitor_updates: Mutex::new(HashMap::new()),
295 /// Queue an update status to return.
296 pub fn set_update_ret(&self, next_ret: chain::ChannelMonitorUpdateStatus) {
297 self.update_rets.lock().unwrap().push_back(next_ret);
300 impl<Signer: sign::WriteableEcdsaChannelSigner> chainmonitor::Persist<Signer> for TestPersister {
301 fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor<Signer>, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
302 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
305 chain::ChannelMonitorUpdateStatus::Completed
308 fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor<Signer>, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
309 let mut ret = chain::ChannelMonitorUpdateStatus::Completed;
310 if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() {
313 if update.is_none() {
314 self.chain_sync_monitor_persistences.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
316 self.offchain_monitor_updates.lock().unwrap().entry(funding_txo).or_insert(HashSet::new()).insert(update_id);
322 pub struct TestBroadcaster {
323 pub txn_broadcasted: Mutex<Vec<Transaction>>,
324 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
327 impl TestBroadcaster {
328 pub fn new(network: Network) -> Self {
330 txn_broadcasted: Mutex::new(Vec::new()),
331 blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])),
335 pub fn with_blocks(blocks: Arc<Mutex<Vec<(Block, u32)>>>) -> Self {
336 Self { txn_broadcasted: Mutex::new(Vec::new()), blocks }
339 pub fn txn_broadcast(&self) -> Vec<Transaction> {
340 self.txn_broadcasted.lock().unwrap().split_off(0)
343 pub fn unique_txn_broadcast(&self) -> Vec<Transaction> {
344 let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0);
345 let mut seen = HashSet::new();
346 txn.retain(|tx| seen.insert(tx.txid()));
351 impl chaininterface::BroadcasterInterface for TestBroadcaster {
352 fn broadcast_transactions(&self, txs: &[&Transaction]) {
354 let lock_time = tx.lock_time.0;
355 assert!(lock_time < 1_500_000_000);
356 if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 {
357 for inp in tx.input.iter() {
358 if inp.sequence != Sequence::MAX {
359 panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time);
364 let owned_txs: Vec<Transaction> = txs.iter().map(|tx| (*tx).clone()).collect();
365 self.txn_broadcasted.lock().unwrap().extend(owned_txs);
369 pub struct TestChannelMessageHandler {
370 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
371 expected_recv_msgs: Mutex<Option<Vec<wire::Message<()>>>>,
372 connected_peers: Mutex<HashSet<PublicKey>>,
373 pub message_fetch_counter: AtomicUsize,
374 genesis_hash: ChainHash,
377 impl TestChannelMessageHandler {
378 pub fn new(genesis_hash: ChainHash) -> Self {
379 TestChannelMessageHandler {
380 pending_events: Mutex::new(Vec::new()),
381 expected_recv_msgs: Mutex::new(None),
382 connected_peers: Mutex::new(HashSet::new()),
383 message_fetch_counter: AtomicUsize::new(0),
389 pub(crate) fn expect_receive_msg(&self, ev: wire::Message<()>) {
390 let mut expected_msgs = self.expected_recv_msgs.lock().unwrap();
391 if expected_msgs.is_none() { *expected_msgs = Some(Vec::new()); }
392 expected_msgs.as_mut().unwrap().push(ev);
395 fn received_msg(&self, _ev: wire::Message<()>) {
396 let mut msgs = self.expected_recv_msgs.lock().unwrap();
397 if msgs.is_none() { return; }
398 assert!(!msgs.as_ref().unwrap().is_empty(), "Received message when we weren't expecting one");
400 assert_eq!(msgs.as_ref().unwrap()[0], _ev);
401 msgs.as_mut().unwrap().remove(0);
405 impl Drop for TestChannelMessageHandler {
407 #[cfg(feature = "std")]
409 let l = self.expected_recv_msgs.lock().unwrap();
410 if !std::thread::panicking() {
411 assert!(l.is_none() || l.as_ref().unwrap().is_empty());
417 impl msgs::ChannelMessageHandler for TestChannelMessageHandler {
418 fn handle_open_channel(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannel) {
419 self.received_msg(wire::Message::OpenChannel(msg.clone()));
421 fn handle_accept_channel(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
422 self.received_msg(wire::Message::AcceptChannel(msg.clone()));
424 fn handle_funding_created(&self, _their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
425 self.received_msg(wire::Message::FundingCreated(msg.clone()));
427 fn handle_funding_signed(&self, _their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
428 self.received_msg(wire::Message::FundingSigned(msg.clone()));
430 fn handle_channel_ready(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReady) {
431 self.received_msg(wire::Message::ChannelReady(msg.clone()));
433 fn handle_shutdown(&self, _their_node_id: &PublicKey, msg: &msgs::Shutdown) {
434 self.received_msg(wire::Message::Shutdown(msg.clone()));
436 fn handle_closing_signed(&self, _their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
437 self.received_msg(wire::Message::ClosingSigned(msg.clone()));
439 fn handle_update_add_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
440 self.received_msg(wire::Message::UpdateAddHTLC(msg.clone()));
442 fn handle_update_fulfill_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
443 self.received_msg(wire::Message::UpdateFulfillHTLC(msg.clone()));
445 fn handle_update_fail_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
446 self.received_msg(wire::Message::UpdateFailHTLC(msg.clone()));
448 fn handle_update_fail_malformed_htlc(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
449 self.received_msg(wire::Message::UpdateFailMalformedHTLC(msg.clone()));
451 fn handle_commitment_signed(&self, _their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
452 self.received_msg(wire::Message::CommitmentSigned(msg.clone()));
454 fn handle_revoke_and_ack(&self, _their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
455 self.received_msg(wire::Message::RevokeAndACK(msg.clone()));
457 fn handle_update_fee(&self, _their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
458 self.received_msg(wire::Message::UpdateFee(msg.clone()));
460 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {
461 // Don't call `received_msg` here as `TestRoutingMessageHandler` generates these sometimes
463 fn handle_announcement_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
464 self.received_msg(wire::Message::AnnouncementSignatures(msg.clone()));
466 fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
467 self.received_msg(wire::Message::ChannelReestablish(msg.clone()));
469 fn peer_disconnected(&self, their_node_id: &PublicKey) {
470 assert!(self.connected_peers.lock().unwrap().remove(their_node_id));
472 fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
473 assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone()));
474 // Don't bother with `received_msg` for Init as its auto-generated and we don't want to
475 // bother re-generating the expected Init message in all tests.
478 fn handle_error(&self, _their_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
479 self.received_msg(wire::Message::Error(msg.clone()));
481 fn provided_node_features(&self) -> NodeFeatures {
482 channelmanager::provided_node_features(&UserConfig::default())
484 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
485 channelmanager::provided_init_features(&UserConfig::default())
488 fn get_genesis_hashes(&self) -> Option<Vec<ChainHash>> {
489 Some(vec![self.genesis_hash])
492 fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
493 self.received_msg(wire::Message::OpenChannelV2(msg.clone()));
496 fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
497 self.received_msg(wire::Message::AcceptChannelV2(msg.clone()));
500 fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) {
501 self.received_msg(wire::Message::TxAddInput(msg.clone()));
504 fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
505 self.received_msg(wire::Message::TxAddOutput(msg.clone()));
508 fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
509 self.received_msg(wire::Message::TxRemoveInput(msg.clone()));
512 fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
513 self.received_msg(wire::Message::TxRemoveOutput(msg.clone()));
516 fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) {
517 self.received_msg(wire::Message::TxComplete(msg.clone()));
520 fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) {
521 self.received_msg(wire::Message::TxSignatures(msg.clone()));
524 fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
525 self.received_msg(wire::Message::TxInitRbf(msg.clone()));
528 fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
529 self.received_msg(wire::Message::TxAckRbf(msg.clone()));
532 fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) {
533 self.received_msg(wire::Message::TxAbort(msg.clone()));
537 impl events::MessageSendEventsProvider for TestChannelMessageHandler {
538 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
539 self.message_fetch_counter.fetch_add(1, Ordering::AcqRel);
540 let mut pending_events = self.pending_events.lock().unwrap();
541 let mut ret = Vec::new();
542 mem::swap(&mut ret, &mut *pending_events);
547 fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnouncement {
548 use bitcoin::secp256k1::ffi::Signature as FFISignature;
549 let secp_ctx = Secp256k1::new();
550 let network = Network::Testnet;
551 let node_1_privkey = SecretKey::from_slice(&[42; 32]).unwrap();
552 let node_2_privkey = SecretKey::from_slice(&[41; 32]).unwrap();
553 let node_1_btckey = SecretKey::from_slice(&[40; 32]).unwrap();
554 let node_2_btckey = SecretKey::from_slice(&[39; 32]).unwrap();
555 let unsigned_ann = msgs::UnsignedChannelAnnouncement {
556 features: ChannelFeatures::empty(),
557 chain_hash: genesis_block(network).header.block_hash(),
558 short_channel_id: short_chan_id,
559 node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)),
560 node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)),
561 bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)),
562 bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)),
563 excess_data: Vec::new(),
567 msgs::ChannelAnnouncement {
568 node_signature_1: Signature::from(FFISignature::new()),
569 node_signature_2: Signature::from(FFISignature::new()),
570 bitcoin_signature_1: Signature::from(FFISignature::new()),
571 bitcoin_signature_2: Signature::from(FFISignature::new()),
572 contents: unsigned_ann,
577 fn get_dummy_channel_update(short_chan_id: u64) -> msgs::ChannelUpdate {
578 use bitcoin::secp256k1::ffi::Signature as FFISignature;
579 let network = Network::Testnet;
580 msgs::ChannelUpdate {
581 signature: Signature::from(unsafe { FFISignature::new() }),
582 contents: msgs::UnsignedChannelUpdate {
583 chain_hash: genesis_block(network).header.block_hash(),
584 short_channel_id: short_chan_id,
587 cltv_expiry_delta: 0,
588 htlc_minimum_msat: 0,
589 htlc_maximum_msat: msgs::MAX_VALUE_MSAT,
591 fee_proportional_millionths: 0,
597 pub struct TestRoutingMessageHandler {
598 pub chan_upds_recvd: AtomicUsize,
599 pub chan_anns_recvd: AtomicUsize,
600 pub pending_events: Mutex<Vec<events::MessageSendEvent>>,
601 pub request_full_sync: AtomicBool,
604 impl TestRoutingMessageHandler {
605 pub fn new() -> Self {
606 TestRoutingMessageHandler {
607 chan_upds_recvd: AtomicUsize::new(0),
608 chan_anns_recvd: AtomicUsize::new(0),
609 pending_events: Mutex::new(vec![]),
610 request_full_sync: AtomicBool::new(false),
614 impl msgs::RoutingMessageHandler for TestRoutingMessageHandler {
615 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, msgs::LightningError> {
616 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
618 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, msgs::LightningError> {
619 self.chan_anns_recvd.fetch_add(1, Ordering::AcqRel);
620 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
622 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, msgs::LightningError> {
623 self.chan_upds_recvd.fetch_add(1, Ordering::AcqRel);
624 Err(msgs::LightningError { err: "".to_owned(), action: msgs::ErrorAction::IgnoreError })
626 fn get_next_channel_announcement(&self, starting_point: u64) -> Option<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> {
627 let chan_upd_1 = get_dummy_channel_update(starting_point);
628 let chan_upd_2 = get_dummy_channel_update(starting_point);
629 let chan_ann = get_dummy_channel_announcement(starting_point);
631 Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2)))
634 fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option<msgs::NodeAnnouncement> {
638 fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> {
639 if !init_msg.features.supports_gossip_queries() {
643 #[allow(unused_mut, unused_assignments)]
644 let mut gossip_start_time = 0;
645 #[cfg(feature = "std")]
647 gossip_start_time = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time must be > 1970").as_secs();
648 if self.request_full_sync.load(Ordering::Acquire) {
649 gossip_start_time -= 60 * 60 * 24 * 7 * 2; // 2 weeks ago
651 gossip_start_time -= 60 * 60; // an hour ago
655 let mut pending_events = self.pending_events.lock().unwrap();
656 pending_events.push(events::MessageSendEvent::SendGossipTimestampFilter {
657 node_id: their_node_id.clone(),
658 msg: msgs::GossipTimestampFilter {
659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
660 first_timestamp: gossip_start_time as u32,
661 timestamp_range: u32::max_value(),
667 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), msgs::LightningError> {
671 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), msgs::LightningError> {
675 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), msgs::LightningError> {
679 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), msgs::LightningError> {
683 fn provided_node_features(&self) -> NodeFeatures {
684 let mut features = NodeFeatures::empty();
685 features.set_gossip_queries_optional();
689 fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
690 let mut features = InitFeatures::empty();
691 features.set_gossip_queries_optional();
695 fn processing_queue_high(&self) -> bool { false }
698 impl events::MessageSendEventsProvider for TestRoutingMessageHandler {
699 fn get_and_clear_pending_msg_events(&self) -> Vec<events::MessageSendEvent> {
700 let mut ret = Vec::new();
701 let mut pending_events = self.pending_events.lock().unwrap();
702 core::mem::swap(&mut ret, &mut pending_events);
707 pub struct TestLogger {
709 pub(crate) id: String,
710 pub lines: Mutex<HashMap<(String, String), usize>>,
714 pub fn new() -> TestLogger {
715 Self::with_id("".to_owned())
717 pub fn with_id(id: String) -> TestLogger {
721 lines: Mutex::new(HashMap::new())
724 pub fn enable(&mut self, level: Level) {
727 pub fn assert_log(&self, module: String, line: String, count: usize) {
728 let log_entries = self.lines.lock().unwrap();
729 assert_eq!(log_entries.get(&(module, line)), Some(&count));
732 /// Search for the number of occurrence of the logged lines which
733 /// 1. belongs to the specified module and
734 /// 2. contains `line` in it.
735 /// And asserts if the number of occurrences is the same with the given `count`
736 pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) {
737 let log_entries = self.lines.lock().unwrap();
738 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
739 m == module && l.contains(line)
740 }).map(|(_, c) | { c }).sum();
744 /// Search for the number of occurrences of logged lines which
745 /// 1. belong to the specified module and
746 /// 2. match the given regex pattern.
747 /// Assert that the number of occurrences equals the given `count`
748 #[cfg(any(test, feature = "_test_utils"))]
749 pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) {
750 let log_entries = self.lines.lock().unwrap();
751 let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| {
752 m == module && pattern.is_match(&l)
753 }).map(|(_, c) | { c }).sum();
758 impl Logger for TestLogger {
759 fn log(&self, record: &Record) {
760 *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1;
761 if record.level >= self.level {
762 #[cfg(all(not(ldk_bench), feature = "std"))]
763 println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args);
768 pub struct TestNodeSigner {
769 node_secret: SecretKey,
772 impl TestNodeSigner {
773 pub fn new(node_secret: SecretKey) -> Self {
778 impl NodeSigner for TestNodeSigner {
779 fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial {
783 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
784 let node_secret = match recipient {
785 Recipient::Node => Ok(&self.node_secret),
786 Recipient::PhantomNode => Err(())
788 Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret))
791 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result<SharedSecret, ()> {
792 let mut node_secret = match recipient {
793 Recipient::Node => Ok(self.node_secret.clone()),
794 Recipient::PhantomNode => Err(())
796 if let Some(tweak) = tweak {
797 node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?;
799 Ok(SharedSecret::new(other_key, &node_secret))
802 fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result<bitcoin::secp256k1::ecdsa::RecoverableSignature, ()> {
806 fn sign_bolt12_invoice_request(
807 &self, _invoice_request: &UnsignedInvoiceRequest
808 ) -> Result<schnorr::Signature, ()> {
812 fn sign_bolt12_invoice(
813 &self, _invoice: &UnsignedBolt12Invoice,
814 ) -> Result<schnorr::Signature, ()> {
818 fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
823 pub struct TestKeysInterface {
824 pub backing: sign::PhantomKeysManager,
825 pub override_random_bytes: Mutex<Option<[u8; 32]>>,
826 pub disable_revocation_policy_check: bool,
827 enforcement_states: Mutex<HashMap<[u8;32], Arc<Mutex<EnforcementState>>>>,
828 expectations: Mutex<Option<VecDeque<OnGetShutdownScriptpubkey>>>,
831 impl EntropySource for TestKeysInterface {
832 fn get_secure_random_bytes(&self) -> [u8; 32] {
833 let override_random_bytes = self.override_random_bytes.lock().unwrap();
834 if let Some(bytes) = &*override_random_bytes {
837 self.backing.get_secure_random_bytes()
841 impl NodeSigner for TestKeysInterface {
842 fn get_node_id(&self, recipient: Recipient) -> Result<PublicKey, ()> {
843 self.backing.get_node_id(recipient)
846 fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&Scalar>) -> Result<SharedSecret, ()> {
847 self.backing.ecdh(recipient, other_key, tweak)
850 fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial {
851 self.backing.get_inbound_payment_key_material()
854 fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result<RecoverableSignature, ()> {
855 self.backing.sign_invoice(hrp_bytes, invoice_data, recipient)
858 fn sign_bolt12_invoice_request(
859 &self, invoice_request: &UnsignedInvoiceRequest
860 ) -> Result<schnorr::Signature, ()> {
861 self.backing.sign_bolt12_invoice_request(invoice_request)
864 fn sign_bolt12_invoice(
865 &self, invoice: &UnsignedBolt12Invoice,
866 ) -> Result<schnorr::Signature, ()> {
867 self.backing.sign_bolt12_invoice(invoice)
870 fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result<Signature, ()> {
871 self.backing.sign_gossip_message(msg)
875 impl SignerProvider for TestKeysInterface {
876 type Signer = EnforcingSigner;
878 fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] {
879 self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id)
882 fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner {
883 let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id);
884 let state = self.make_enforcement_state_cell(keys.commitment_seed);
885 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
888 fn read_chan_signer(&self, buffer: &[u8]) -> Result<Self::Signer, msgs::DecodeError> {
889 let mut reader = io::Cursor::new(buffer);
891 let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?;
892 let state = self.make_enforcement_state_cell(inner.commitment_seed);
894 Ok(EnforcingSigner::new_with_revoked(
897 self.disable_revocation_policy_check
901 fn get_destination_script(&self) -> Result<Script, ()> { self.backing.get_destination_script() }
903 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
904 match &mut *self.expectations.lock().unwrap() {
905 None => self.backing.get_shutdown_scriptpubkey(),
906 Some(expectations) => match expectations.pop_front() {
907 None => panic!("Unexpected get_shutdown_scriptpubkey"),
908 Some(expectation) => Ok(expectation.returns),
914 impl TestKeysInterface {
915 pub fn new(seed: &[u8; 32], network: Network) -> Self {
916 let now = Duration::from_secs(genesis_block(network).header.time as u64);
918 backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed),
919 override_random_bytes: Mutex::new(None),
920 disable_revocation_policy_check: false,
921 enforcement_states: Mutex::new(HashMap::new()),
922 expectations: Mutex::new(None),
926 /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is
928 pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self {
929 self.expectations.lock().unwrap()
930 .get_or_insert_with(|| VecDeque::new())
931 .push_back(expectation);
935 pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner {
936 let keys = self.backing.derive_channel_keys(channel_value_satoshis, id);
937 let state = self.make_enforcement_state_cell(keys.commitment_seed);
938 EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check)
941 fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc<Mutex<EnforcementState>> {
942 let mut states = self.enforcement_states.lock().unwrap();
943 if !states.contains_key(&commitment_seed) {
944 let state = EnforcementState::new();
945 states.insert(commitment_seed, Arc::new(Mutex::new(state)));
947 let cell = states.get(&commitment_seed).unwrap();
952 pub(crate) fn panicking() -> bool {
953 #[cfg(feature = "std")]
954 let panicking = ::std::thread::panicking();
955 #[cfg(not(feature = "std"))]
956 let panicking = false;
960 impl Drop for TestKeysInterface {
966 if let Some(expectations) = &*self.expectations.lock().unwrap() {
967 if !expectations.is_empty() {
968 panic!("Unsatisfied expectations: {:?}", expectations);
974 /// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and
975 /// returns a [`ShutdownScript`].
976 pub struct OnGetShutdownScriptpubkey {
977 /// A shutdown script used to close a channel.
978 pub returns: ShutdownScript,
981 impl core::fmt::Debug for OnGetShutdownScriptpubkey {
982 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
983 f.debug_struct("OnGetShutdownScriptpubkey").finish()
987 pub struct TestChainSource {
988 pub genesis_hash: BlockHash,
989 pub utxo_ret: Mutex<UtxoResult>,
990 pub get_utxo_call_count: AtomicUsize,
991 pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
992 pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
995 impl TestChainSource {
996 pub fn new(network: Network) -> Self {
997 let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script();
999 genesis_hash: genesis_block(network).block_hash(),
1000 utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))),
1001 get_utxo_call_count: AtomicUsize::new(0),
1002 watched_txn: Mutex::new(HashSet::new()),
1003 watched_outputs: Mutex::new(HashSet::new()),
1008 impl UtxoLookup for TestChainSource {
1009 fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
1010 self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed);
1011 if self.genesis_hash != *genesis_hash {
1012 return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain));
1015 self.utxo_ret.lock().unwrap().clone()
1019 impl chain::Filter for TestChainSource {
1020 fn register_tx(&self, txid: &Txid, script_pubkey: &Script) {
1021 self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
1024 fn register_output(&self, output: WatchedOutput) {
1025 self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
1029 impl Drop for TestChainSource {
1030 fn drop(&mut self) {
1037 pub struct TestScorer {
1038 /// Stores a tuple of (scid, ChannelUsage)
1039 scorer_expectations: RefCell<Option<VecDeque<(u64, ChannelUsage)>>>,
1043 pub fn new() -> Self {
1045 scorer_expectations: RefCell::new(None),
1049 pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) {
1050 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation));
1055 impl crate::util::ser::Writeable for TestScorer {
1056 fn write<W: crate::util::ser::Writer>(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); }
1059 impl Score for TestScorer {
1060 type ScoreParams = ();
1061 fn channel_penalty_msat(
1062 &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams
1064 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1065 match scorer_expectations.pop_front() {
1066 Some((scid, expectation)) => {
1067 assert_eq!(expectation, usage);
1068 assert_eq!(scid, short_channel_id);
1076 fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {}
1078 fn payment_path_successful(&mut self, _actual_path: &Path) {}
1080 fn probe_failed(&mut self, _actual_path: &Path, _: u64) {}
1082 fn probe_successful(&mut self, _actual_path: &Path) {}
1085 impl Drop for TestScorer {
1086 fn drop(&mut self) {
1087 #[cfg(feature = "std")] {
1088 if std::thread::panicking() {
1093 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1094 if !scorer_expectations.is_empty() {
1095 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1101 pub struct TestWalletSource {
1102 secret_key: SecretKey,
1103 utxos: RefCell<Vec<Utxo>>,
1104 secp: Secp256k1<bitcoin::secp256k1::All>,
1107 impl TestWalletSource {
1108 pub fn new(secret_key: SecretKey) -> Self {
1111 utxos: RefCell::new(Vec::new()),
1112 secp: Secp256k1::new(),
1116 pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut {
1117 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1118 let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash());
1119 self.utxos.borrow_mut().push(utxo.clone());
1123 pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut {
1124 let output = utxo.output.clone();
1125 self.utxos.borrow_mut().push(utxo);
1129 pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) {
1130 self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint);
1134 impl WalletSource for TestWalletSource {
1135 fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1136 Ok(self.utxos.borrow().clone())
1139 fn get_change_script(&self) -> Result<Script, ()> {
1140 let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
1141 Ok(Script::new_p2pkh(&public_key.pubkey_hash()))
1144 fn sign_tx(&self, mut tx: Transaction) -> Result<Transaction, ()> {
1145 let utxos = self.utxos.borrow();
1146 for i in 0..tx.input.len() {
1147 if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1148 let sighash = SighashCache::new(&tx)
1149 .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
1151 let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key);
1152 let bitcoin_sig = bitcoin::EcdsaSig { sig, hash_ty: EcdsaSighashType::All }.to_vec();
1153 tx.input[i].script_sig = Builder::new()
1154 .push_slice(&bitcoin_sig)
1155 .push_slice(&self.secret_key.public_key(&self.secp).serialize())