X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Futil%2Ftest_utils.rs;h=96d934daad4f1d52bc3fe3e89df87913dc0c16f5;hb=286d1db2cd36e287ebc518b7253b2cd7a62513dd;hp=1838b1078a98d42adbd96f15af3ab93cd01f9426;hpb=01fe9badc034fdc16a4450a2ce9ba5552560329f;p=rust-lightning diff --git a/lightning/src/util/test_utils.rs b/lightning/src/util/test_utils.rs index 1838b107..09c99815 100644 --- a/lightning/src/util/test_utils.rs +++ b/lightning/src/util/test_utils.rs @@ -11,25 +11,37 @@ use crate::chain; use crate::chain::WatchedOutput; use crate::chain::chaininterface; use crate::chain::chaininterface::ConfirmationTarget; +use crate::chain::chaininterface::FEERATE_FLOOR_SATS_PER_KW; use crate::chain::chainmonitor; use crate::chain::chainmonitor::MonitorUpdateId; use crate::chain::channelmonitor; use crate::chain::channelmonitor::MonitorEvent; use crate::chain::transaction::OutPoint; -use crate::chain::keysinterface; +use crate::sign; +use crate::events; +use crate::events::bump_transaction::{WalletSource, Utxo}; +use crate::ln::ChannelId; use crate::ln::channelmanager; +use crate::ln::chan_utils::CommitmentTransaction; use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures}; use crate::ln::{msgs, wire}; +use crate::ln::msgs::LightningError; use crate::ln::script::ShutdownScript; -use crate::routing::gossip::NetworkGraph; -use crate::routing::router::{find_route, InFlightHtlcs, Route, RouteHop, RouteParameters, Router, ScorerAccountingForInFlightHtlcs}; -use crate::routing::scoring::FixedPenaltyScorer; +use crate::offers::invoice::UnsignedBolt12Invoice; +use crate::offers::invoice_request::UnsignedInvoiceRequest; +use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId}; +use crate::routing::utxo::{UtxoLookup, UtxoLookupError, UtxoResult}; +use crate::routing::router::{find_route, InFlightHtlcs, Path, Route, RouteParameters, Router, ScorerAccountingForInFlightHtlcs}; +use crate::routing::scoring::{ChannelUsage, ScoreUpdate, ScoreLookUp}; +use crate::sync::RwLock; use crate::util::config::UserConfig; -use crate::util::enforcing_trait_impls::{EnforcingSigner, EnforcementState}; -use crate::util::events; +use crate::util::test_channel_signer::{TestChannelSigner, EnforcementState}; use crate::util::logger::{Logger, Level, Record}; use crate::util::ser::{Readable, ReadableArgs, Writer, Writeable}; +use crate::util::persist::KVStore; +use bitcoin::EcdsaSighashType; +use bitcoin::blockdata::constants::ChainHash; use bitcoin::blockdata::constants::genesis_block; use bitcoin::blockdata::transaction::{Transaction, TxOut}; use bitcoin::blockdata::script::{Builder, Script}; @@ -37,26 +49,39 @@ use bitcoin::blockdata::opcodes; use bitcoin::blockdata::block::Block; use bitcoin::network::constants::Network; use bitcoin::hash_types::{BlockHash, Txid}; +use bitcoin::util::sighash::SighashCache; -use bitcoin::secp256k1::{SecretKey, PublicKey, Secp256k1, ecdsa::Signature, Scalar}; +use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey}; use bitcoin::secp256k1::ecdh::SharedSecret; -use bitcoin::secp256k1::ecdsa::RecoverableSignature; +use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; +use bitcoin::secp256k1::schnorr; +#[cfg(any(test, feature = "_test_utils"))] use regex; use crate::io; use crate::prelude::*; +use core::cell::RefCell; use core::time::Duration; use crate::sync::{Mutex, Arc}; use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use core::mem; use bitcoin::bech32::u5; -use crate::chain::keysinterface::{InMemorySigner, Recipient, KeyMaterial, EntropySource, NodeSigner, SignerProvider}; +use crate::sign::{InMemorySigner, Recipient, EntropySource, NodeSigner, SignerProvider}; #[cfg(feature = "std")] use std::time::{SystemTime, UNIX_EPOCH}; use bitcoin::Sequence; +pub fn pubkey(byte: u8) -> PublicKey { + let secp_ctx = Secp256k1::new(); + PublicKey::from_secret_key(&secp_ctx, &privkey(byte)) +} + +pub fn privkey(byte: u8) -> SecretKey { + SecretKey::from_slice(&[byte; 32]).unwrap() +} + pub struct TestVecWriter(pub Vec); impl Writer for TestVecWriter { fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> { @@ -76,30 +101,72 @@ impl chaininterface::FeeEstimator for TestFeeEstimator { pub struct TestRouter<'a> { pub network_graph: Arc>, + pub next_routes: Mutex)>>, + pub scorer: &'a RwLock, } impl<'a> TestRouter<'a> { - pub fn new(network_graph: Arc>) -> Self { - Self { network_graph } + pub fn new(network_graph: Arc>, scorer: &'a RwLock) -> Self { + Self { network_graph, next_routes: Mutex::new(VecDeque::new()), scorer } + } + + pub fn expect_find_route(&self, query: RouteParameters, result: Result) { + let mut expected_routes = self.next_routes.lock().unwrap(); + expected_routes.push_back((query, result)); } } impl<'a> Router for TestRouter<'a> { fn find_route( &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>, - inflight_htlcs: &InFlightHtlcs + inflight_htlcs: InFlightHtlcs ) -> Result { + if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() { + assert_eq!(find_route_query, *params); + if let Ok(ref route) = find_route_res { + let scorer = self.scorer.read().unwrap(); + let scorer = ScorerAccountingForInFlightHtlcs::new(scorer, &inflight_htlcs); + for path in &route.paths { + let mut aggregate_msat = 0u64; + for (idx, hop) in path.hops.iter().rev().enumerate() { + aggregate_msat += hop.fee_msat; + let usage = ChannelUsage { + amount_msat: aggregate_msat, + inflight_htlc_msat: 0, + effective_capacity: EffectiveCapacity::Unknown, + }; + + // Since the path is reversed, the last element in our iteration is the first + // hop. + if idx == path.hops.len() - 1 { + scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage, &()); + } else { + let curr_hop_path_idx = path.hops.len() - 1 - idx; + 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, &()); + } + } + } + } + return find_route_res; + } let logger = TestLogger::new(); find_route( payer, params, &self.network_graph, first_hops, &logger, - &ScorerAccountingForInFlightHtlcs::new(TestScorer::with_penalty(0), &inflight_htlcs), + &ScorerAccountingForInFlightHtlcs::new(self.scorer.read().unwrap(), &inflight_htlcs), &(), &[42; 32] ) } - fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {} - fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {} - fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {} - fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {} +} + +impl<'a> Drop for TestRouter<'a> { + fn drop(&mut self) { + #[cfg(feature = "std")] { + if std::thread::panicking() { + return; + } + } + assert!(self.next_routes.lock().unwrap().is_empty()); + } } pub struct OnlyReadsKeysInterface {} @@ -107,53 +174,41 @@ pub struct OnlyReadsKeysInterface {} impl EntropySource for OnlyReadsKeysInterface { fn get_secure_random_bytes(&self) -> [u8; 32] { [0; 32] }} -impl NodeSigner for OnlyReadsKeysInterface { - fn get_node_secret(&self, _recipient: Recipient) -> Result { unreachable!(); } - fn get_node_id(&self, recipient: Recipient) -> Result { - let secp_ctx = Secp256k1::signing_only(); - Ok(PublicKey::from_secret_key(&secp_ctx, &self.get_node_secret(recipient)?)) - } - fn ecdh(&self, _recipient: Recipient, _other_key: &PublicKey, _tweak: Option<&Scalar>) -> Result { unreachable!(); } - fn get_inbound_payment_key_material(&self) -> KeyMaterial { unreachable!(); } - fn sign_invoice(&self, _hrp_bytes: &[u8], _invoice_data: &[u5], _recipient: Recipient) -> Result { unreachable!(); } -} - impl SignerProvider for OnlyReadsKeysInterface { - type Signer = EnforcingSigner; + type Signer = TestChannelSigner; fn generate_channel_keys_id(&self, _inbound: bool, _channel_value_satoshis: u64, _user_channel_id: u128) -> [u8; 32] { unreachable!(); } fn derive_channel_signer(&self, _channel_value_satoshis: u64, _channel_keys_id: [u8; 32]) -> Self::Signer { unreachable!(); } fn read_chan_signer(&self, mut reader: &[u8]) -> Result { - let dummy_sk = SecretKey::from_slice(&[42; 32]).unwrap(); - let inner: InMemorySigner = ReadableArgs::read(&mut reader, dummy_sk)?; + let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?; let state = Arc::new(Mutex::new(EnforcementState::new())); - Ok(EnforcingSigner::new_with_revoked( + Ok(TestChannelSigner::new_with_revoked( inner, state, false )) } - fn get_destination_script(&self) -> Script { unreachable!(); } - fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { unreachable!(); } + fn get_destination_script(&self) -> Result { Err(()) } + fn get_shutdown_scriptpubkey(&self) -> Result { Err(()) } } pub struct TestChainMonitor<'a> { - pub added_monitors: Mutex)>>, - pub monitor_updates: Mutex>>, - pub latest_monitor_update_id: Mutex>, - pub chain_monitor: chainmonitor::ChainMonitor>, + pub added_monitors: Mutex)>>, + pub monitor_updates: Mutex>>, + pub latest_monitor_update_id: Mutex>, + pub chain_monitor: chainmonitor::ChainMonitor>, pub keys_manager: &'a TestKeysInterface, /// If this is set to Some(), the next update_channel call (not watch_channel) must be a /// ChannelForceClosed event for the given channel_id with should_broadcast set to the given /// boolean. - pub expect_channel_force_closed: Mutex>, + pub expect_channel_force_closed: Mutex>, } impl<'a> TestChainMonitor<'a> { - pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist, keys_manager: &'a TestKeysInterface) -> Self { + pub fn new(chain_source: Option<&'a TestChainSource>, broadcaster: &'a chaininterface::BroadcasterInterface, logger: &'a TestLogger, fee_estimator: &'a TestFeeEstimator, persister: &'a chainmonitor::Persist, keys_manager: &'a TestKeysInterface) -> Self { Self { added_monitors: Mutex::new(Vec::new()), monitor_updates: Mutex::new(HashMap::new()), @@ -164,18 +219,18 @@ impl<'a> TestChainMonitor<'a> { } } - pub fn complete_sole_pending_chan_update(&self, channel_id: &[u8; 32]) { + pub fn complete_sole_pending_chan_update(&self, channel_id: &ChannelId) { let (outpoint, _, latest_update) = self.latest_monitor_update_id.lock().unwrap().get(channel_id).unwrap().clone(); self.chain_monitor.channel_monitor_updated(outpoint, latest_update).unwrap(); } } -impl<'a> chain::Watch for TestChainMonitor<'a> { - fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> chain::ChannelMonitorUpdateStatus { +impl<'a> chain::Watch for TestChainMonitor<'a> { + fn watch_channel(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> chain::ChannelMonitorUpdateStatus { // At every point where we get a monitor update, we should be able to send a useful monitor // to a watchtower and disk... let mut w = TestVecWriter(Vec::new()); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1; assert!(new_monitor == monitor); self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), @@ -184,12 +239,12 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { self.chain_monitor.watch_channel(funding_txo, new_monitor) } - fn update_channel(&self, funding_txo: OutPoint, update: channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus { + fn update_channel(&self, funding_txo: OutPoint, update: &channelmonitor::ChannelMonitorUpdate) -> chain::ChannelMonitorUpdateStatus { // Every monitor update should survive roundtrip let mut w = TestVecWriter(Vec::new()); update.write(&mut w).unwrap(); assert!(channelmonitor::ChannelMonitorUpdate::read( - &mut io::Cursor::new(&w.0)).unwrap() == update); + &mut io::Cursor::new(&w.0)).unwrap() == *update); self.monitor_updates.lock().unwrap().entry(funding_txo.to_channel_id()).or_insert(Vec::new()).push(update.clone()); @@ -202,14 +257,14 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { } self.latest_monitor_update_id.lock().unwrap().insert(funding_txo.to_channel_id(), - (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(&update))); + (funding_txo, update.update_id, MonitorUpdateId::from_monitor_update(update))); let update_res = self.chain_monitor.update_channel(funding_txo, update); // At every point where we get a monitor update, we should be able to send a useful monitor // to a watchtower and disk... let monitor = self.chain_monitor.get_monitor(funding_txo).unwrap(); w.0.clear(); monitor.write(&mut w).unwrap(); - let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( + let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor)>::read( &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap().1; assert!(new_monitor == *monitor); self.added_monitors.lock().unwrap().push((funding_txo, new_monitor)); @@ -221,6 +276,110 @@ impl<'a> chain::Watch for TestChainMonitor<'a> { } } +struct JusticeTxData { + justice_tx: Transaction, + value: u64, + commitment_number: u64, +} + +pub(crate) struct WatchtowerPersister { + persister: TestPersister, + /// Upon a new commitment_signed, we'll get a + /// ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTxInfo. We'll store the justice tx + /// amount, and commitment number so we can build the justice tx after our counterparty + /// revokes it. + unsigned_justice_tx_data: Mutex>>, + /// After receiving a revoke_and_ack for a commitment number, we'll form and store the justice + /// tx which would be used to provide a watchtower with the data it needs. + watchtower_state: Mutex>>, + destination_script: Script, +} + +impl WatchtowerPersister { + #[cfg(test)] + pub(crate) fn new(destination_script: Script) -> Self { + WatchtowerPersister { + persister: TestPersister::new(), + unsigned_justice_tx_data: Mutex::new(HashMap::new()), + watchtower_state: Mutex::new(HashMap::new()), + destination_script, + } + } + + #[cfg(test)] + pub(crate) fn justice_tx(&self, funding_txo: OutPoint, commitment_txid: &Txid) + -> Option { + self.watchtower_state.lock().unwrap().get(&funding_txo).unwrap().get(commitment_txid).cloned() + } + + fn form_justice_data_from_commitment(&self, counterparty_commitment_tx: &CommitmentTransaction) + -> Option { + let trusted_tx = counterparty_commitment_tx.trust(); + let output_idx = trusted_tx.revokeable_output_index()?; + let built_tx = trusted_tx.built_transaction(); + let value = built_tx.transaction.output[output_idx as usize].value; + let justice_tx = trusted_tx.build_to_local_justice_tx( + FEERATE_FLOOR_SATS_PER_KW as u64, self.destination_script.clone()).ok()?; + let commitment_number = counterparty_commitment_tx.commitment_number(); + Some(JusticeTxData { justice_tx, value, commitment_number }) + } +} + +impl chainmonitor::Persist for WatchtowerPersister { + fn persist_new_channel(&self, funding_txo: OutPoint, + data: &channelmonitor::ChannelMonitor, id: MonitorUpdateId + ) -> chain::ChannelMonitorUpdateStatus { + let res = self.persister.persist_new_channel(funding_txo, data, id); + + assert!(self.unsigned_justice_tx_data.lock().unwrap() + .insert(funding_txo, VecDeque::new()).is_none()); + assert!(self.watchtower_state.lock().unwrap() + .insert(funding_txo, HashMap::new()).is_none()); + + let initial_counterparty_commitment_tx = data.initial_counterparty_commitment_tx() + .expect("First and only call expects Some"); + if let Some(justice_data) + = self.form_justice_data_from_commitment(&initial_counterparty_commitment_tx) { + self.unsigned_justice_tx_data.lock().unwrap() + .get_mut(&funding_txo).unwrap() + .push_back(justice_data); + } + res + } + + fn update_persisted_channel( + &self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, + data: &channelmonitor::ChannelMonitor, update_id: MonitorUpdateId + ) -> chain::ChannelMonitorUpdateStatus { + let res = self.persister.update_persisted_channel(funding_txo, update, data, update_id); + + if let Some(update) = update { + let commitment_txs = data.counterparty_commitment_txs_from_update(update); + let justice_datas = commitment_txs.into_iter() + .filter_map(|commitment_tx| self.form_justice_data_from_commitment(&commitment_tx)); + let mut channels_justice_txs = self.unsigned_justice_tx_data.lock().unwrap(); + let channel_state = channels_justice_txs.get_mut(&funding_txo).unwrap(); + channel_state.extend(justice_datas); + + while let Some(JusticeTxData { justice_tx, value, commitment_number }) = channel_state.front() { + let input_idx = 0; + let commitment_txid = justice_tx.input[input_idx].previous_output.txid; + match data.sign_to_local_justice_tx(justice_tx.clone(), input_idx, *value, *commitment_number) { + Ok(signed_justice_tx) => { + let dup = self.watchtower_state.lock().unwrap() + .get_mut(&funding_txo).unwrap() + .insert(commitment_txid, signed_justice_tx); + assert!(dup.is_none()); + channel_state.pop_front(); + }, + Err(_) => break, + } + } + } + res + } +} + pub struct TestPersister { /// The queue of update statuses we'll return. If none are queued, ::Completed will always be /// returned. @@ -246,7 +405,7 @@ impl TestPersister { self.update_rets.lock().unwrap().push_back(next_ret); } } -impl chainmonitor::Persist for TestPersister { +impl chainmonitor::Persist for TestPersister { fn persist_new_channel(&self, _funding_txo: OutPoint, _data: &channelmonitor::ChannelMonitor, _id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus { if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() { return update_ret @@ -254,7 +413,7 @@ impl chainmonitor::Persist for TestPersiste chain::ChannelMonitorUpdateStatus::Completed } - fn update_persisted_channel(&self, funding_txo: OutPoint, update: &Option, _data: &channelmonitor::ChannelMonitor, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus { + fn update_persisted_channel(&self, funding_txo: OutPoint, update: Option<&channelmonitor::ChannelMonitorUpdate>, _data: &channelmonitor::ChannelMonitor, update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus { let mut ret = chain::ChannelMonitorUpdateStatus::Completed; if let Some(update_ret) = self.update_rets.lock().unwrap().pop_front() { ret = update_ret; @@ -268,42 +427,160 @@ impl chainmonitor::Persist for TestPersiste } } +pub(crate) struct TestStore { + persisted_bytes: Mutex>>>, + read_only: bool, +} + +impl TestStore { + pub fn new(read_only: bool) -> Self { + let persisted_bytes = Mutex::new(HashMap::new()); + Self { persisted_bytes, read_only } + } +} + +impl KVStore for TestStore { + fn read(&self, namespace: &str, sub_namespace: &str, key: &str) -> io::Result> { + let persisted_lock = self.persisted_bytes.lock().unwrap(); + let prefixed = if sub_namespace.is_empty() { + namespace.to_string() + } else { + format!("{}/{}", namespace, sub_namespace) + }; + + if let Some(outer_ref) = persisted_lock.get(&prefixed) { + if let Some(inner_ref) = outer_ref.get(key) { + let bytes = inner_ref.clone(); + Ok(bytes) + } else { + Err(io::Error::new(io::ErrorKind::NotFound, "Key not found")) + } + } else { + Err(io::Error::new(io::ErrorKind::NotFound, "Namespace not found")) + } + } + + fn write(&self, namespace: &str, sub_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()> { + if self.read_only { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Cannot modify read-only store", + )); + } + let mut persisted_lock = self.persisted_bytes.lock().unwrap(); + + let prefixed = if sub_namespace.is_empty() { + namespace.to_string() + } else { + format!("{}/{}", namespace, sub_namespace) + }; + let outer_e = persisted_lock.entry(prefixed).or_insert(HashMap::new()); + let mut bytes = Vec::new(); + bytes.write_all(buf)?; + outer_e.insert(key.to_string(), bytes); + Ok(()) + } + + fn remove(&self, namespace: &str, sub_namespace: &str, key: &str, _lazy: bool) -> io::Result<()> { + if self.read_only { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Cannot modify read-only store", + )); + } + + let mut persisted_lock = self.persisted_bytes.lock().unwrap(); + + let prefixed = if sub_namespace.is_empty() { + namespace.to_string() + } else { + format!("{}/{}", namespace, sub_namespace) + }; + if let Some(outer_ref) = persisted_lock.get_mut(&prefixed) { + outer_ref.remove(&key.to_string()); + } + + Ok(()) + } + + fn list(&self, namespace: &str, sub_namespace: &str) -> io::Result> { + let mut persisted_lock = self.persisted_bytes.lock().unwrap(); + + let prefixed = if sub_namespace.is_empty() { + namespace.to_string() + } else { + format!("{}/{}", namespace, sub_namespace) + }; + match persisted_lock.entry(prefixed) { + hash_map::Entry::Occupied(e) => Ok(e.get().keys().cloned().collect()), + hash_map::Entry::Vacant(_) => Ok(Vec::new()), + } + } +} + pub struct TestBroadcaster { pub txn_broadcasted: Mutex>, pub blocks: Arc>>, } impl TestBroadcaster { - pub fn new(blocks: Arc>>) -> TestBroadcaster { - TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks } + pub fn new(network: Network) -> Self { + Self { + txn_broadcasted: Mutex::new(Vec::new()), + blocks: Arc::new(Mutex::new(vec![(genesis_block(network), 0)])), + } + } + + pub fn with_blocks(blocks: Arc>>) -> Self { + Self { txn_broadcasted: Mutex::new(Vec::new()), blocks } + } + + pub fn txn_broadcast(&self) -> Vec { + self.txn_broadcasted.lock().unwrap().split_off(0) + } + + pub fn unique_txn_broadcast(&self) -> Vec { + let mut txn = self.txn_broadcasted.lock().unwrap().split_off(0); + let mut seen = HashSet::new(); + txn.retain(|tx| seen.insert(tx.txid())); + txn } } impl chaininterface::BroadcasterInterface for TestBroadcaster { - fn broadcast_transaction(&self, tx: &Transaction) { - let lock_time = tx.lock_time.0; - assert!(lock_time < 1_500_000_000); - if lock_time > self.blocks.lock().unwrap().len() as u32 + 1 && lock_time < 500_000_000 { - for inp in tx.input.iter() { - if inp.sequence != Sequence::MAX { - panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time); + fn broadcast_transactions(&self, txs: &[&Transaction]) { + for tx in txs { + let lock_time = tx.lock_time.0; + assert!(lock_time < 1_500_000_000); + if bitcoin::LockTime::from(tx.lock_time).is_block_height() && lock_time > self.blocks.lock().unwrap().last().unwrap().1 { + for inp in tx.input.iter() { + if inp.sequence != Sequence::MAX { + panic!("We should never broadcast a transaction before its locktime ({})!", tx.lock_time); + } } } } - self.txn_broadcasted.lock().unwrap().push(tx.clone()); + let owned_txs: Vec = txs.iter().map(|tx| (*tx).clone()).collect(); + self.txn_broadcasted.lock().unwrap().extend(owned_txs); } } pub struct TestChannelMessageHandler { pub pending_events: Mutex>, expected_recv_msgs: Mutex>>>, + connected_peers: Mutex>, + pub message_fetch_counter: AtomicUsize, + genesis_hash: ChainHash, } impl TestChannelMessageHandler { - pub fn new() -> Self { + pub fn new(genesis_hash: ChainHash) -> Self { TestChannelMessageHandler { pending_events: Mutex::new(Vec::new()), expected_recv_msgs: Mutex::new(None), + connected_peers: Mutex::new(HashSet::new()), + message_fetch_counter: AtomicUsize::new(0), + genesis_hash, } } @@ -388,8 +665,11 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler { fn handle_channel_reestablish(&self, _their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) { self.received_msg(wire::Message::ChannelReestablish(msg.clone())); } - fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {} - fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) -> Result<(), ()> { + fn peer_disconnected(&self, their_node_id: &PublicKey) { + assert!(self.connected_peers.lock().unwrap().remove(their_node_id)); + } + fn peer_connected(&self, their_node_id: &PublicKey, _msg: &msgs::Init, _inbound: bool) -> Result<(), ()> { + assert!(self.connected_peers.lock().unwrap().insert(their_node_id.clone())); // Don't bother with `received_msg` for Init as its auto-generated and we don't want to // bother re-generating the expected Init message in all tests. Ok(()) @@ -403,10 +683,59 @@ impl msgs::ChannelMessageHandler for TestChannelMessageHandler { fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures { channelmanager::provided_init_features(&UserConfig::default()) } + + fn get_genesis_hashes(&self) -> Option> { + Some(vec![self.genesis_hash]) + } + + fn handle_open_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::OpenChannelV2) { + self.received_msg(wire::Message::OpenChannelV2(msg.clone())); + } + + fn handle_accept_channel_v2(&self, _their_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) { + self.received_msg(wire::Message::AcceptChannelV2(msg.clone())); + } + + fn handle_tx_add_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddInput) { + self.received_msg(wire::Message::TxAddInput(msg.clone())); + } + + fn handle_tx_add_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxAddOutput) { + self.received_msg(wire::Message::TxAddOutput(msg.clone())); + } + + fn handle_tx_remove_input(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveInput) { + self.received_msg(wire::Message::TxRemoveInput(msg.clone())); + } + + fn handle_tx_remove_output(&self, _their_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) { + self.received_msg(wire::Message::TxRemoveOutput(msg.clone())); + } + + fn handle_tx_complete(&self, _their_node_id: &PublicKey, msg: &msgs::TxComplete) { + self.received_msg(wire::Message::TxComplete(msg.clone())); + } + + fn handle_tx_signatures(&self, _their_node_id: &PublicKey, msg: &msgs::TxSignatures) { + self.received_msg(wire::Message::TxSignatures(msg.clone())); + } + + fn handle_tx_init_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxInitRbf) { + self.received_msg(wire::Message::TxInitRbf(msg.clone())); + } + + fn handle_tx_ack_rbf(&self, _their_node_id: &PublicKey, msg: &msgs::TxAckRbf) { + self.received_msg(wire::Message::TxAckRbf(msg.clone())); + } + + fn handle_tx_abort(&self, _their_node_id: &PublicKey, msg: &msgs::TxAbort) { + self.received_msg(wire::Message::TxAbort(msg.clone())); + } } impl events::MessageSendEventsProvider for TestChannelMessageHandler { fn get_and_clear_pending_msg_events(&self) -> Vec { + self.message_fetch_counter.fetch_add(1, Ordering::AcqRel); let mut pending_events = self.pending_events.lock().unwrap(); let mut ret = Vec::new(); mem::swap(&mut ret, &mut *pending_events); @@ -426,10 +755,10 @@ fn get_dummy_channel_announcement(short_chan_id: u64) -> msgs::ChannelAnnounceme features: ChannelFeatures::empty(), chain_hash: genesis_block(network).header.block_hash(), short_channel_id: short_chan_id, - node_id_1: PublicKey::from_secret_key(&secp_ctx, &node_1_privkey), - node_id_2: PublicKey::from_secret_key(&secp_ctx, &node_2_privkey), - bitcoin_key_1: PublicKey::from_secret_key(&secp_ctx, &node_1_btckey), - bitcoin_key_2: PublicKey::from_secret_key(&secp_ctx, &node_2_btckey), + node_id_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_privkey)), + node_id_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_privkey)), + bitcoin_key_1: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_1_btckey)), + bitcoin_key_2: NodeId::from_pubkey(&PublicKey::from_secret_key(&secp_ctx, &node_2_btckey)), excess_data: Vec::new(), }; @@ -501,11 +830,11 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { Some((chan_ann, Some(chan_upd_1), Some(chan_upd_2))) } - fn get_next_node_announcement(&self, _starting_point: Option<&PublicKey>) -> Option { + fn get_next_node_announcement(&self, _starting_point: Option<&NodeId>) -> Option { None } - fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init) -> Result<(), ()> { + fn peer_connected(&self, their_node_id: &PublicKey, init_msg: &msgs::Init, _inbound: bool) -> Result<(), ()> { if !init_msg.features.supports_gossip_queries() { return Ok(()); } @@ -561,6 +890,8 @@ impl msgs::RoutingMessageHandler for TestRoutingMessageHandler { features.set_gossip_queries_optional(); features } + + fn processing_queue_high(&self) -> bool { false } } impl events::MessageSendEventsProvider for TestRoutingMessageHandler { @@ -601,10 +932,10 @@ impl TestLogger { /// 1. belongs to the specified module and /// 2. contains `line` in it. /// And asserts if the number of occurrences is the same with the given `count` - pub fn assert_log_contains(&self, module: String, line: String, count: usize) { + pub fn assert_log_contains(&self, module: &str, line: &str, count: usize) { let log_entries = self.lines.lock().unwrap(); let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| { - m == &module && l.contains(line.as_str()) + m == module && l.contains(line) }).map(|(_, c) | { c }).sum(); assert_eq!(l, count) } @@ -613,10 +944,11 @@ impl TestLogger { /// 1. belong to the specified module and /// 2. match the given regex pattern. /// Assert that the number of occurrences equals the given `count` - pub fn assert_log_regex(&self, module: String, pattern: regex::Regex, count: usize) { + #[cfg(any(test, feature = "_test_utils"))] + pub fn assert_log_regex(&self, module: &str, pattern: regex::Regex, count: usize) { let log_entries = self.lines.lock().unwrap(); let l: usize = log_entries.iter().filter(|&(&(ref m, ref l), _c)| { - m == &module && pattern.is_match(&l) + m == module && pattern.is_match(&l) }).map(|(_, c) | { c }).sum(); assert_eq!(l, count) } @@ -626,14 +958,69 @@ impl Logger for TestLogger { fn log(&self, record: &Record) { *self.lines.lock().unwrap().entry((record.module_path.to_string(), format!("{}", record.args))).or_insert(0) += 1; if record.level >= self.level { - #[cfg(feature = "std")] + #[cfg(all(not(ldk_bench), feature = "std"))] println!("{:<5} {} [{} : {}, {}] {}", record.level.to_string(), self.id, record.module_path, record.file, record.line, record.args); } } } +pub struct TestNodeSigner { + node_secret: SecretKey, +} + +impl TestNodeSigner { + pub fn new(node_secret: SecretKey) -> Self { + Self { node_secret } + } +} + +impl NodeSigner for TestNodeSigner { + fn get_inbound_payment_key_material(&self) -> crate::sign::KeyMaterial { + unreachable!() + } + + fn get_node_id(&self, recipient: Recipient) -> Result { + let node_secret = match recipient { + Recipient::Node => Ok(&self.node_secret), + Recipient::PhantomNode => Err(()) + }?; + Ok(PublicKey::from_secret_key(&Secp256k1::signing_only(), node_secret)) + } + + fn ecdh(&self, recipient: Recipient, other_key: &PublicKey, tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result { + let mut node_secret = match recipient { + Recipient::Node => Ok(self.node_secret.clone()), + Recipient::PhantomNode => Err(()) + }?; + if let Some(tweak) = tweak { + node_secret = node_secret.mul_tweak(tweak).map_err(|_| ())?; + } + Ok(SharedSecret::new(other_key, &node_secret)) + } + + fn sign_invoice(&self, _: &[u8], _: &[bitcoin::bech32::u5], _: Recipient) -> Result { + unreachable!() + } + + fn sign_bolt12_invoice_request( + &self, _invoice_request: &UnsignedInvoiceRequest + ) -> Result { + unreachable!() + } + + fn sign_bolt12_invoice( + &self, _invoice: &UnsignedBolt12Invoice, + ) -> Result { + unreachable!() + } + + fn sign_gossip_message(&self, _msg: msgs::UnsignedGossipMessage) -> Result { + unreachable!() + } +} + pub struct TestKeysInterface { - pub backing: keysinterface::PhantomKeysManager, + pub backing: sign::PhantomKeysManager, pub override_random_bytes: Mutex>, pub disable_revocation_policy_check: bool, enforcement_states: Mutex>>>, @@ -651,10 +1038,6 @@ impl EntropySource for TestKeysInterface { } impl NodeSigner for TestKeysInterface { - fn get_node_secret(&self, recipient: Recipient) -> Result { - self.backing.get_node_secret(recipient) - } - fn get_node_id(&self, recipient: Recipient) -> Result { self.backing.get_node_id(recipient) } @@ -663,49 +1046,65 @@ impl NodeSigner for TestKeysInterface { self.backing.ecdh(recipient, other_key, tweak) } - fn get_inbound_payment_key_material(&self) -> keysinterface::KeyMaterial { + fn get_inbound_payment_key_material(&self) -> sign::KeyMaterial { self.backing.get_inbound_payment_key_material() } fn sign_invoice(&self, hrp_bytes: &[u8], invoice_data: &[u5], recipient: Recipient) -> Result { self.backing.sign_invoice(hrp_bytes, invoice_data, recipient) } + + fn sign_bolt12_invoice_request( + &self, invoice_request: &UnsignedInvoiceRequest + ) -> Result { + self.backing.sign_bolt12_invoice_request(invoice_request) + } + + fn sign_bolt12_invoice( + &self, invoice: &UnsignedBolt12Invoice, + ) -> Result { + self.backing.sign_bolt12_invoice(invoice) + } + + fn sign_gossip_message(&self, msg: msgs::UnsignedGossipMessage) -> Result { + self.backing.sign_gossip_message(msg) + } } impl SignerProvider for TestKeysInterface { - type Signer = EnforcingSigner; + type Signer = TestChannelSigner; fn generate_channel_keys_id(&self, inbound: bool, channel_value_satoshis: u64, user_channel_id: u128) -> [u8; 32] { self.backing.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id) } - fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> EnforcingSigner { + fn derive_channel_signer(&self, channel_value_satoshis: u64, channel_keys_id: [u8; 32]) -> TestChannelSigner { let keys = self.backing.derive_channel_signer(channel_value_satoshis, channel_keys_id); let state = self.make_enforcement_state_cell(keys.commitment_seed); - EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check) + TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check) } fn read_chan_signer(&self, buffer: &[u8]) -> Result { let mut reader = io::Cursor::new(buffer); - let inner: InMemorySigner = ReadableArgs::read(&mut reader, self.get_node_secret(Recipient::Node).unwrap())?; + let inner: InMemorySigner = ReadableArgs::read(&mut reader, self)?; let state = self.make_enforcement_state_cell(inner.commitment_seed); - Ok(EnforcingSigner::new_with_revoked( + Ok(TestChannelSigner::new_with_revoked( inner, state, self.disable_revocation_policy_check )) } - fn get_destination_script(&self) -> Script { self.backing.get_destination_script() } + fn get_destination_script(&self) -> Result { self.backing.get_destination_script() } - fn get_shutdown_scriptpubkey(&self) -> ShutdownScript { + fn get_shutdown_scriptpubkey(&self) -> Result { match &mut *self.expectations.lock().unwrap() { None => self.backing.get_shutdown_scriptpubkey(), Some(expectations) => match expectations.pop_front() { None => panic!("Unexpected get_shutdown_scriptpubkey"), - Some(expectation) => expectation.returns, + Some(expectation) => Ok(expectation.returns), }, } } @@ -715,7 +1114,7 @@ impl TestKeysInterface { pub fn new(seed: &[u8; 32], network: Network) -> Self { let now = Duration::from_secs(genesis_block(network).header.time as u64); Self { - backing: keysinterface::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed), + backing: sign::PhantomKeysManager::new(seed, now.as_secs(), now.subsec_nanos(), seed), override_random_bytes: Mutex::new(None), disable_revocation_policy_check: false, enforcement_states: Mutex::new(HashMap::new()), @@ -723,7 +1122,7 @@ impl TestKeysInterface { } } - /// Sets an expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] is + /// Sets an expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] is /// called. pub fn expect(&self, expectation: OnGetShutdownScriptpubkey) -> &Self { self.expectations.lock().unwrap() @@ -732,10 +1131,10 @@ impl TestKeysInterface { self } - pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> EnforcingSigner { + pub fn derive_channel_keys(&self, channel_value_satoshis: u64, id: &[u8; 32]) -> TestChannelSigner { let keys = self.backing.derive_channel_keys(channel_value_satoshis, id); let state = self.make_enforcement_state_cell(keys.commitment_seed); - EnforcingSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check) + TestChannelSigner::new_with_revoked(keys, state, self.disable_revocation_policy_check) } fn make_enforcement_state_cell(&self, commitment_seed: [u8; 32]) -> Arc> { @@ -771,7 +1170,7 @@ impl Drop for TestKeysInterface { } } -/// An expectation that [`keysinterface::SignerProvider::get_shutdown_scriptpubkey`] was called and +/// An expectation that [`sign::SignerProvider::get_shutdown_scriptpubkey`] was called and /// returns a [`ShutdownScript`]. pub struct OnGetShutdownScriptpubkey { /// A shutdown script used to close a channel. @@ -786,7 +1185,8 @@ impl core::fmt::Debug for OnGetShutdownScriptpubkey { pub struct TestChainSource { pub genesis_hash: BlockHash, - pub utxo_ret: Mutex>, + pub utxo_ret: Mutex, + pub get_utxo_call_count: AtomicUsize, pub watched_txn: Mutex>, pub watched_outputs: Mutex>, } @@ -796,17 +1196,19 @@ impl TestChainSource { let script_pubkey = Builder::new().push_opcode(opcodes::OP_TRUE).into_script(); Self { genesis_hash: genesis_block(network).block_hash(), - utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })), + utxo_ret: Mutex::new(UtxoResult::Sync(Ok(TxOut { value: u64::max_value(), script_pubkey }))), + get_utxo_call_count: AtomicUsize::new(0), watched_txn: Mutex::new(HashSet::new()), watched_outputs: Mutex::new(HashSet::new()), } } } -impl chain::Access for TestChainSource { - fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> Result { +impl UtxoLookup for TestChainSource { + fn get_utxo(&self, genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult { + self.get_utxo_call_count.fetch_add(1, Ordering::Relaxed); if self.genesis_hash != *genesis_hash { - return Err(chain::AccessError::UnknownChain); + return UtxoResult::Sync(Err(UtxoLookupError::UnknownChain)); } self.utxo_ret.lock().unwrap().clone() @@ -831,5 +1233,130 @@ impl Drop for TestChainSource { } } -/// A scorer useful in testing, when the passage of time isn't a concern. -pub type TestScorer = FixedPenaltyScorer; +pub struct TestScorer { + /// Stores a tuple of (scid, ChannelUsage) + scorer_expectations: RefCell>>, +} + +impl TestScorer { + pub fn new() -> Self { + Self { + scorer_expectations: RefCell::new(None), + } + } + + pub fn expect_usage(&self, scid: u64, expectation: ChannelUsage) { + self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back((scid, expectation)); + } +} + +#[cfg(c_bindings)] +impl crate::util::ser::Writeable for TestScorer { + fn write(&self, _: &mut W) -> Result<(), crate::io::Error> { unreachable!(); } +} + +impl ScoreLookUp for TestScorer { + type ScoreParams = (); + fn channel_penalty_msat( + &self, short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage, _score_params: &Self::ScoreParams + ) -> u64 { + if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() { + match scorer_expectations.pop_front() { + Some((scid, expectation)) => { + assert_eq!(expectation, usage); + assert_eq!(scid, short_channel_id); + }, + None => {}, + } + } + 0 + } +} + +impl ScoreUpdate for TestScorer { + fn payment_path_failed(&mut self, _actual_path: &Path, _actual_short_channel_id: u64) {} + + fn payment_path_successful(&mut self, _actual_path: &Path) {} + + fn probe_failed(&mut self, _actual_path: &Path, _: u64) {} + + fn probe_successful(&mut self, _actual_path: &Path) {} +} + +impl Drop for TestScorer { + fn drop(&mut self) { + #[cfg(feature = "std")] { + if std::thread::panicking() { + return; + } + } + + if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() { + if !scorer_expectations.is_empty() { + panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations) + } + } + } +} + +pub struct TestWalletSource { + secret_key: SecretKey, + utxos: RefCell>, + secp: Secp256k1, +} + +impl TestWalletSource { + pub fn new(secret_key: SecretKey) -> Self { + Self { + secret_key, + utxos: RefCell::new(Vec::new()), + secp: Secp256k1::new(), + } + } + + pub fn add_utxo(&self, outpoint: bitcoin::OutPoint, value: u64) -> TxOut { + let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp)); + let utxo = Utxo::new_p2pkh(outpoint, value, &public_key.pubkey_hash()); + self.utxos.borrow_mut().push(utxo.clone()); + utxo.output + } + + pub fn add_custom_utxo(&self, utxo: Utxo) -> TxOut { + let output = utxo.output.clone(); + self.utxos.borrow_mut().push(utxo); + output + } + + pub fn remove_utxo(&self, outpoint: bitcoin::OutPoint) { + self.utxos.borrow_mut().retain(|utxo| utxo.outpoint != outpoint); + } +} + +impl WalletSource for TestWalletSource { + fn list_confirmed_utxos(&self) -> Result, ()> { + Ok(self.utxos.borrow().clone()) + } + + fn get_change_script(&self) -> Result { + let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp)); + Ok(Script::new_p2pkh(&public_key.pubkey_hash())) + } + + fn sign_tx(&self, mut tx: Transaction) -> Result { + let utxos = self.utxos.borrow(); + for i in 0..tx.input.len() { + if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) { + let sighash = SighashCache::new(&tx) + .legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32) + .map_err(|_| ())?; + let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key); + let bitcoin_sig = bitcoin::EcdsaSig { sig, hash_ty: EcdsaSighashType::All }.to_vec(); + tx.input[i].script_sig = Builder::new() + .push_slice(&bitcoin_sig) + .push_slice(&self.secret_key.public_key(&self.secp).serialize()) + .into_script(); + } + } + Ok(tx) + } +}