X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fchain%2Fchannelmonitor.rs;h=ce1ef9128f91efe8327f2f874daca511e7c6e4f1;hb=4ccd7f6d7a8dfc57c0cdb2c3f9c51943152429a3;hp=65b58722762087035cfb43573b87c05050e3abbb;hpb=fa0d015d1f7e597b086e55e9d5652cc17b85b151;p=rust-lightning diff --git a/lightning/src/chain/channelmonitor.rs b/lightning/src/chain/channelmonitor.rs index 65b58722..ce1ef912 100644 --- a/lightning/src/chain/channelmonitor.rs +++ b/lightning/src/chain/channelmonitor.rs @@ -34,20 +34,20 @@ use bitcoin::secp256k1; use bitcoin::sighash::EcdsaSighashType; use crate::ln::channel::INITIAL_COMMITMENT_NUMBER; -use crate::ln::{PaymentHash, PaymentPreimage}; +use crate::ln::{PaymentHash, PaymentPreimage, ChannelId}; use crate::ln::msgs::DecodeError; -use crate::ln::chan_utils; -use crate::ln::chan_utils::{CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys}; +use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint}; +use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys}; use crate::ln::channelmanager::{HTLCSource, SentHTLCId}; use crate::chain; use crate::chain::{BestBlock, WatchedOutput}; use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator}; use crate::chain::transaction::{OutPoint, TransactionData}; -use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, WriteableEcdsaChannelSigner, SignerProvider, EntropySource}; +use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ecdsa::WriteableEcdsaChannelSigner, SignerProvider, EntropySource}; use crate::chain::onchaintx::{ClaimEvent, OnchainTxHandler}; use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput}; use crate::chain::Filter; -use crate::util::logger::Logger; +use crate::util::logger::{Logger, Record}; use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, MaybeReadable, UpgradableRequired, Writer, Writeable, U48}; use crate::util::byte_utils; use crate::events::{Event, EventHandler}; @@ -238,10 +238,10 @@ pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_ struct HolderSignedTx { /// txid of the transaction in tx, just used to make comparison faster txid: Txid, - revocation_key: PublicKey, - a_htlc_key: PublicKey, - b_htlc_key: PublicKey, - delayed_payment_key: PublicKey, + revocation_key: RevocationKey, + a_htlc_key: HtlcKey, + b_htlc_key: HtlcKey, + delayed_payment_key: DelayedPaymentKey, per_commitment_point: PublicKey, htlc_outputs: Vec<(HTLCOutputInCommitment, Option, Option)>, to_self_value_sat: u64, @@ -278,8 +278,8 @@ impl HolderSignedTx { /// justice or 2nd-stage preimage/timeout transactions. #[derive(Clone, PartialEq, Eq)] struct CounterpartyCommitmentParameters { - counterparty_delayed_payment_base_key: PublicKey, - counterparty_htlc_base_key: PublicKey, + counterparty_delayed_payment_base_key: DelayedPaymentBasepoint, + counterparty_htlc_base_key: HtlcBasepoint, on_counterparty_tx_csv: u16, } @@ -752,12 +752,12 @@ pub(crate) struct ChannelMonitorImpl { commitment_transaction_number_obscure_factor: u64, destination_script: ScriptBuf, - broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, PublicKey)>, + broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>, counterparty_payment_script: ScriptBuf, shutdown_script: Option, channel_keys_id: [u8; 32], - holder_revocation_basepoint: PublicKey, + holder_revocation_basepoint: RevocationBasepoint, funding_info: (OutPoint, ScriptBuf), current_counterparty_commitment_txid: Option, prev_counterparty_commitment_txid: Option, @@ -1125,6 +1125,34 @@ macro_rules! _process_events_body { } pub(super) use _process_events_body as process_events_body; +pub(crate) struct WithChannelMonitor<'a, L: Deref> where L::Target: Logger { + logger: &'a L, + peer_id: Option, + channel_id: Option, +} + +impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger { + fn log(&self, mut record: Record) { + record.peer_id = self.peer_id; + record.channel_id = self.channel_id; + self.logger.log(record) + } +} + +impl<'a, L: Deref> WithChannelMonitor<'a, L> where L::Target: Logger { + pub(crate) fn from(logger: &'a L, monitor: &ChannelMonitor) -> Self { + Self::from_impl(logger, &*monitor.inner.lock().unwrap()) + } + + pub(crate) fn from_impl(logger: &'a L, monitor_impl: &ChannelMonitorImpl) -> Self { + let peer_id = monitor_impl.counterparty_node_id; + let channel_id = Some(monitor_impl.funding_info.0.to_channel_id()); + WithChannelMonitor { + logger, peer_id, channel_id, + } + } +} + impl ChannelMonitor { /// For lockorder enforcement purposes, we need to have a single site which constructs the /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our @@ -1258,9 +1286,11 @@ impl ChannelMonitor { ) where L::Target: Logger { - self.inner.lock().unwrap().provide_initial_counterparty_commitment_tx(txid, + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.provide_initial_counterparty_commitment_tx(txid, htlc_outputs, commitment_number, their_cur_per_commitment_point, feerate_per_kw, - to_broadcaster_value_sat, to_countersignatory_value_sat, logger); + to_broadcaster_value_sat, to_countersignatory_value_sat, &logger); } /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction. @@ -1276,8 +1306,10 @@ impl ChannelMonitor { their_per_commitment_point: PublicKey, logger: &L, ) where L::Target: Logger { - self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx( - txid, htlc_outputs, commitment_number, their_per_commitment_point, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.provide_latest_counterparty_commitment_tx( + txid, htlc_outputs, commitment_number, their_per_commitment_point, &logger) } #[cfg(test)] @@ -1302,8 +1334,10 @@ impl ChannelMonitor { F::Target: FeeEstimator, L::Target: Logger, { - self.inner.lock().unwrap().provide_payment_preimage( - payment_hash, payment_preimage, broadcaster, fee_estimator, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.provide_payment_preimage( + payment_hash, payment_preimage, broadcaster, fee_estimator, &logger) } /// Updates a ChannelMonitor on the basis of some new information provided by the Channel @@ -1322,7 +1356,9 @@ impl ChannelMonitor { F::Target: FeeEstimator, L::Target: Logger, { - self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.update_monitor(updates, broadcaster, fee_estimator, &logger) } /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this @@ -1459,7 +1495,7 @@ impl ChannelMonitor { /// to the commitment transaction being revoked, this will return a signed transaction, but /// the signature will not be valid. /// - /// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::EcdsaChannelSigner::sign_justice_revoked_output + /// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::ecdsa::EcdsaChannelSigner::sign_justice_revoked_output /// [`Persist`]: crate::chain::chainmonitor::Persist pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result { self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number) @@ -1501,7 +1537,9 @@ impl ChannelMonitor { /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager pub fn get_latest_holder_commitment_txn(&self, logger: &L) -> Vec where L::Target: Logger { - self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.get_latest_holder_commitment_txn(&logger) } /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework @@ -1510,7 +1548,9 @@ impl ChannelMonitor { #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))] pub fn unsafe_get_latest_holder_commitment_txn(&self, logger: &L) -> Vec where L::Target: Logger { - self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.unsafe_get_latest_holder_commitment_txn(&logger) } /// Processes transactions in a newly connected block, which may result in any of the following: @@ -1531,15 +1571,17 @@ impl ChannelMonitor { height: u32, broadcaster: B, fee_estimator: F, - logger: L, + logger: &L, ) -> Vec where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, { - self.inner.lock().unwrap().block_connected( - header, txdata, height, broadcaster, fee_estimator, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.block_connected( + header, txdata, height, broadcaster, fee_estimator, &logger) } /// Determines if the disconnected block contained any transactions of interest and updates @@ -1550,14 +1592,16 @@ impl ChannelMonitor { height: u32, broadcaster: B, fee_estimator: F, - logger: L, + logger: &L, ) where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, { - self.inner.lock().unwrap().block_disconnected( - header, height, broadcaster, fee_estimator, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.block_disconnected( + header, height, broadcaster, fee_estimator, &logger) } /// Processes transactions confirmed in a block with the given header and height, returning new @@ -1574,7 +1618,7 @@ impl ChannelMonitor { height: u32, broadcaster: B, fee_estimator: F, - logger: L, + logger: &L, ) -> Vec where B::Target: BroadcasterInterface, @@ -1582,8 +1626,10 @@ impl ChannelMonitor { L::Target: Logger, { let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); - self.inner.lock().unwrap().transactions_confirmed( - header, txdata, height, broadcaster, &bounded_fee_estimator, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.transactions_confirmed( + header, txdata, height, broadcaster, &bounded_fee_estimator, &logger) } /// Processes a transaction that was reorganized out of the chain. @@ -1597,15 +1643,18 @@ impl ChannelMonitor { txid: &Txid, broadcaster: B, fee_estimator: F, - logger: L, + logger: &L, ) where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, { let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); - self.inner.lock().unwrap().transaction_unconfirmed( - txid, broadcaster, &bounded_fee_estimator, logger); + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.transaction_unconfirmed( + txid, broadcaster, &bounded_fee_estimator, &logger + ); } /// Updates the monitor with the current best chain tip, returning new outputs to watch. See @@ -1621,7 +1670,7 @@ impl ChannelMonitor { height: u32, broadcaster: B, fee_estimator: F, - logger: L, + logger: &L, ) -> Vec where B::Target: BroadcasterInterface, @@ -1629,8 +1678,11 @@ impl ChannelMonitor { L::Target: Logger, { let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); - self.inner.lock().unwrap().best_block_updated( - header, height, broadcaster, &bounded_fee_estimator, logger) + let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); + inner.best_block_updated( + header, height, broadcaster, &bounded_fee_estimator, &logger + ) } /// Returns the set of txids that should be monitored for re-organization out of the chain. @@ -1658,7 +1710,7 @@ impl ChannelMonitor { /// invoking this every 30 seconds, or lower if running in an environment with spotty /// connections, like on mobile. pub fn rebroadcast_pending_claims( - &self, broadcaster: B, fee_estimator: F, logger: L, + &self, broadcaster: B, fee_estimator: F, logger: &L, ) where B::Target: BroadcasterInterface, @@ -1667,6 +1719,7 @@ impl ChannelMonitor { { let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator); let mut inner = self.inner.lock().unwrap(); + let logger = WithChannelMonitor::from_impl(logger, &*inner); let current_height = inner.best_block.height; inner.onchain_tx_handler.rebroadcast_pending_claims( current_height, &broadcaster, &fee_estimator, &logger, @@ -2375,13 +2428,11 @@ impl ChannelMonitorImpl { Ok(()) } - pub(crate) fn provide_initial_counterparty_commitment_tx( + fn provide_initial_counterparty_commitment_tx( &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, commitment_number: u64, their_per_commitment_point: PublicKey, feerate_per_kw: u32, - to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &L - ) - where L::Target: Logger - { + to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &WithChannelMonitor, + ) where L::Target: Logger { self.initial_counterparty_commitment_info = Some((their_per_commitment_point.clone(), feerate_per_kw, to_broadcaster_value, to_countersignatory_value)); @@ -2394,7 +2445,11 @@ impl ChannelMonitorImpl { their_per_commitment_point, logger); } - pub(crate) fn provide_latest_counterparty_commitment_tx(&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, commitment_number: u64, their_per_commitment_point: PublicKey, logger: &L) where L::Target: Logger { + fn provide_latest_counterparty_commitment_tx( + &mut self, txid: Txid, + htlc_outputs: Vec<(HTLCOutputInCommitment, Option>)>, + commitment_number: u64, their_per_commitment_point: PublicKey, logger: &WithChannelMonitor, + ) where L::Target: Logger { // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction // so that a remote monitor doesn't learn anything unless there is a malicious close. // (only maybe, sadly we cant do the same for local info, as we need to be aware of @@ -2527,7 +2582,7 @@ impl ChannelMonitorImpl { /// commitment_tx_infos which contain the payment hash have been revoked. fn provide_payment_preimage( &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B, - fee_estimator: &LowerBoundedFeeEstimator, logger: &L) + fee_estimator: &LowerBoundedFeeEstimator, logger: &WithChannelMonitor) where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, @@ -2604,9 +2659,9 @@ impl ChannelMonitorImpl { } } - pub(crate) fn broadcast_latest_holder_commitment_txn(&mut self, broadcaster: &B, logger: &L) + fn broadcast_latest_holder_commitment_txn(&mut self, broadcaster: &B, logger: &WithChannelMonitor) where B::Target: BroadcasterInterface, - L::Target: Logger, + L::Target: Logger, { let commit_txs = self.get_latest_holder_commitment_txn(logger); let mut txs = vec![]; @@ -2618,7 +2673,9 @@ impl ChannelMonitorImpl { self.pending_monitor_events.push(MonitorEvent::HolderForceClosed(self.funding_info.0)); } - pub fn update_monitor(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), ()> + fn update_monitor( + &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor + ) -> Result<(), ()> where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, @@ -2763,15 +2820,15 @@ impl ChannelMonitorImpl { } else { ret } } - pub fn get_latest_update_id(&self) -> u64 { + fn get_latest_update_id(&self) -> u64 { self.latest_update_id } - pub fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) { + fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) { &self.funding_info } - pub fn get_outputs_to_watch(&self) -> &HashMap> { + fn get_outputs_to_watch(&self) -> &HashMap> { // If we've detected a counterparty commitment tx on chain, we must include it in the set // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because // its trivial to do, double-check that here. @@ -2781,7 +2838,7 @@ impl ChannelMonitorImpl { &self.outputs_to_watch } - pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec { + fn get_and_clear_pending_monitor_events(&mut self) -> Vec { let mut ret = Vec::new(); mem::swap(&mut ret, &mut self.pending_monitor_events); ret @@ -2856,7 +2913,7 @@ impl ChannelMonitorImpl { ret } - pub(crate) fn initial_counterparty_commitment_tx(&mut self) -> Option { + fn initial_counterparty_commitment_tx(&mut self) -> Option { let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value, to_countersignatory_value) = self.initial_counterparty_commitment_info?; let htlc_outputs = vec![]; @@ -2890,7 +2947,7 @@ impl ChannelMonitorImpl { channel_parameters) } - pub(crate) fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec { + fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec { update.updates.iter().filter_map(|update| { match update { &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, @@ -2916,7 +2973,7 @@ impl ChannelMonitorImpl { }).collect() } - pub(crate) fn sign_to_local_justice_tx( + fn sign_to_local_justice_tx( &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64 ) -> Result { let secret = self.get_secret(commitment_number).ok_or(())?; @@ -2924,12 +2981,10 @@ impl ChannelMonitorImpl { let their_per_commitment_point = PublicKey::from_secret_key( &self.onchain_tx_handler.secp_ctx, &per_commitment_key); - let revocation_pubkey = chan_utils::derive_public_revocation_key( - &self.onchain_tx_handler.secp_ctx, &their_per_commitment_point, - &self.holder_revocation_basepoint); - let delayed_key = chan_utils::derive_public_key(&self.onchain_tx_handler.secp_ctx, - &their_per_commitment_point, - &self.counterparty_commitment_params.counterparty_delayed_payment_base_key); + let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, + &self.holder_revocation_basepoint, &their_per_commitment_point); + let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, + &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point); let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key); @@ -2946,15 +3001,15 @@ impl ChannelMonitorImpl { self.commitment_secrets.get_secret(idx) } - pub(crate) fn get_min_seen_secret(&self) -> u64 { + fn get_min_seen_secret(&self) -> u64 { self.commitment_secrets.get_min_seen_secret() } - pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 { + fn get_cur_counterparty_commitment_number(&self) -> u64 { self.current_counterparty_commitment_number } - pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 { + fn get_cur_holder_commitment_number(&self) -> u64 { self.current_holder_commitment_number } @@ -2992,8 +3047,8 @@ impl ChannelMonitorImpl { let secret = self.get_secret(commitment_number).unwrap(); let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret)); let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key); - let revocation_pubkey = chan_utils::derive_public_revocation_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint); - let delayed_key = chan_utils::derive_public_key(&self.onchain_tx_handler.secp_ctx, &PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key), &self.counterparty_commitment_params.counterparty_delayed_payment_base_key); + let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point,); + let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key)); let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key); let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh(); @@ -3105,11 +3160,11 @@ impl ChannelMonitorImpl { } else { return (claimable_outpoints, to_counterparty_output_info); }; if let Some(transaction) = tx { - let revocation_pubkey = chan_utils::derive_public_revocation_key( - &self.onchain_tx_handler.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint); - let delayed_key = chan_utils::derive_public_key(&self.onchain_tx_handler.secp_ctx, - &per_commitment_point, - &self.counterparty_commitment_params.counterparty_delayed_payment_base_key); + let revocation_pubkey = RevocationKey::from_basepoint( + &self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point); + + let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &per_commitment_point); + let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key).to_v0_p2wsh(); @@ -3204,7 +3259,7 @@ impl ChannelMonitorImpl { // Returns (1) `PackageTemplate`s that can be given to the OnchainTxHandler, so that the handler can // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable // script so we can detect whether a holder transaction has been seen on-chain. - fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec, Option<(ScriptBuf, PublicKey, PublicKey)>) { + fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec, Option<(ScriptBuf, PublicKey, RevocationKey)>) { let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len()); let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key); @@ -3301,7 +3356,9 @@ impl ChannelMonitorImpl { } } - pub fn get_latest_holder_commitment_txn(&mut self, logger: &L) -> Vec where L::Target: Logger { + fn get_latest_holder_commitment_txn( + &mut self, logger: &WithChannelMonitor, + ) -> Vec where L::Target: Logger { log_debug!(logger, "Getting signed latest holder commitment transaction!"); self.holder_tx_signed = true; let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript); @@ -3340,7 +3397,9 @@ impl ChannelMonitorImpl { #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))] /// Note that this includes possibly-locktimed-in-the-future transactions! - fn unsafe_get_latest_holder_commitment_txn(&mut self, logger: &L) -> Vec where L::Target: Logger { + fn unsafe_get_latest_holder_commitment_txn( + &mut self, logger: &WithChannelMonitor + ) -> Vec where L::Target: Logger { log_debug!(logger, "Getting signed copy of latest holder commitment transaction!"); let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript); let txid = commitment_tx.txid(); @@ -3367,10 +3426,13 @@ impl ChannelMonitorImpl { holder_transactions } - pub fn block_connected(&mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: L) -> Vec + fn block_connected( + &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B, + fee_estimator: F, logger: &WithChannelMonitor, + ) -> Vec where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, + F::Target: FeeEstimator, + L::Target: Logger, { let block_hash = header.block_hash(); self.best_block = BestBlock::new(block_hash, height); @@ -3385,7 +3447,7 @@ impl ChannelMonitorImpl { height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator, - logger: L, + logger: &WithChannelMonitor, ) -> Vec where B::Target: BroadcasterInterface, @@ -3396,7 +3458,7 @@ impl ChannelMonitorImpl { if height > self.best_block.height() { self.best_block = BestBlock::new(block_hash, height); - self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger) + self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger) } else if block_hash != self.best_block.block_hash() { self.best_block = BestBlock::new(block_hash, height); self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height); @@ -3412,7 +3474,7 @@ impl ChannelMonitorImpl { height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator, - logger: L, + logger: &WithChannelMonitor, ) -> Vec where B::Target: BroadcasterInterface, @@ -3529,9 +3591,9 @@ impl ChannelMonitorImpl { break; } } - self.is_resolving_htlc_output(&tx, height, &block_hash, &logger); + self.is_resolving_htlc_output(&tx, height, &block_hash, logger); - self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, &logger); + self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger); } } @@ -3539,7 +3601,7 @@ impl ChannelMonitorImpl { self.best_block = BestBlock::new(block_hash, height); } - self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger) + self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger) } /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update @@ -3559,7 +3621,7 @@ impl ChannelMonitorImpl { mut claimable_outpoints: Vec, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator, - logger: &L, + logger: &WithChannelMonitor, ) -> Vec where B::Target: BroadcasterInterface, @@ -3704,10 +3766,11 @@ impl ChannelMonitorImpl { watch_outputs } - pub fn block_disconnected(&mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: L) - where B::Target: BroadcasterInterface, - F::Target: FeeEstimator, - L::Target: Logger, + fn block_disconnected( + &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor + ) where B::Target: BroadcasterInterface, + F::Target: FeeEstimator, + L::Target: Logger, { log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height); @@ -3727,7 +3790,7 @@ impl ChannelMonitorImpl { txid: &Txid, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator, - logger: L, + logger: &WithChannelMonitor, ) where B::Target: BroadcasterInterface, F::Target: FeeEstimator, @@ -3806,7 +3869,9 @@ impl ChannelMonitorImpl { false } - fn should_broadcast_holder_commitment_txn(&self, logger: &L) -> bool where L::Target: Logger { + fn should_broadcast_holder_commitment_txn( + &self, logger: &WithChannelMonitor + ) -> bool where L::Target: Logger { // There's no need to broadcast our commitment transaction if we've seen one confirmed (even // with 1 confirmation) as it'll be rejected as duplicate/conflicting. if self.funding_spend_confirmed.is_some() || @@ -3882,7 +3947,9 @@ impl ChannelMonitorImpl { /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC - fn is_resolving_htlc_output(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) where L::Target: Logger { + fn is_resolving_htlc_output( + &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, + ) where L::Target: Logger { 'outer_loop: for input in &tx.input { let mut payment_data = None; let htlc_claim = HTLCClaim::from_witness(&input.witness); @@ -4084,6 +4151,7 @@ impl ChannelMonitorImpl { spendable_outputs.push(SpendableOutputDescriptor::StaticOutput { outpoint: OutPoint { txid: tx.txid(), index: i as u16 }, output: outp.clone(), + channel_keys_id: Some(self.channel_keys_id), }); } if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script { @@ -4093,7 +4161,7 @@ impl ChannelMonitorImpl { per_commitment_point: broadcasted_holder_revokable_script.1, to_self_delay: self.on_holder_tx_csv, output: outp.clone(), - revocation_pubkey: broadcasted_holder_revokable_script.2.clone(), + revocation_pubkey: broadcasted_holder_revokable_script.2, channel_keys_id: self.channel_keys_id, channel_value_satoshis: self.channel_value_satoshis, })); @@ -4112,6 +4180,7 @@ impl ChannelMonitorImpl { spendable_outputs.push(SpendableOutputDescriptor::StaticOutput { outpoint: OutPoint { txid: tx.txid(), index: i as u16 }, output: outp.clone(), + channel_keys_id: Some(self.channel_keys_id), }); } } @@ -4121,7 +4190,7 @@ impl ChannelMonitorImpl { /// Checks if the confirmed transaction is paying funds back to some address we can assume to /// own. fn check_tx_and_push_spendable_outputs( - &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L, + &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor, ) where L::Target: Logger { for spendable_output in self.get_spendable_outputs(tx) { let entry = OnchainEventEntry { @@ -4144,11 +4213,11 @@ where L::Target: Logger, { fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) { - self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3); + self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3); } fn block_disconnected(&self, header: &Header, height: u32) { - self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3); + self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3); } } @@ -4160,15 +4229,15 @@ where L::Target: Logger, { fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) { - self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3); + self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3); } fn transaction_unconfirmed(&self, txid: &Txid) { - self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3); + self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3); } fn best_block_updated(&self, header: &Header, height: u32) { - self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3); + self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3); } fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option)> { @@ -4179,7 +4248,7 @@ where const MAX_ALLOC_SIZE: usize = 64*1024; impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)> - for (BlockHash, ChannelMonitor) { + for (BlockHash, ChannelMonitor) { fn read(reader: &mut R, args: (&'a ES, &'b SP)) -> Result { macro_rules! unwrap_obj { ($key: expr) => { @@ -4365,7 +4434,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP return Err(DecodeError::InvalidValue); } } - let onchain_tx_handler: OnchainTxHandler = ReadableArgs::read( + let onchain_tx_handler: OnchainTxHandler = ReadableArgs::read( reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id) )?; @@ -4501,19 +4570,20 @@ mod tests { use super::ChannelMonitorUpdateStep; use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err}; use crate::chain::{BestBlock, Confirm}; - use crate::chain::channelmonitor::ChannelMonitor; + use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor}; use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT}; use crate::chain::transaction::OutPoint; use crate::sign::InMemorySigner; use crate::ln::{PaymentPreimage, PaymentHash}; - use crate::ln::chan_utils; - use crate::ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters}; + use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey}; + use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters}; use crate::ln::channelmanager::{PaymentSendFailure, PaymentId, RecipientOnionFields}; use crate::ln::functional_test_utils::*; use crate::ln::script::ShutdownScript; use crate::util::errors::APIError; use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator}; use crate::util::ser::{ReadableArgs, Writeable}; + use crate::util::logger::Logger; use crate::sync::{Arc, Mutex}; use crate::io; use crate::ln::features::ChannelTypeFeatures; @@ -4674,10 +4744,10 @@ mod tests { let counterparty_pubkeys = ChannelPublicKeys { funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()), - revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()), + revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())), payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()), - delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()), - htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()) + delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())), + htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())) }; let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() }; let channel_parameters = ChannelTransactionParameters { @@ -4703,6 +4773,7 @@ mod tests { let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]); let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs); + monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(), htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect()).unwrap(); monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()), @@ -4767,6 +4838,7 @@ mod tests { let privkey = SecretKey::from_slice(&>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap(); let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey); + use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint}; macro_rules! sign_input { ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => { let htlc = HTLCOutputInCommitment { @@ -4776,7 +4848,7 @@ mod tests { payment_hash: PaymentHash([1; 32]), transaction_output_index: Some($idx as u32), }; - let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &pubkey, &pubkey, &pubkey) }; + let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey), 256, &DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(pubkey), &pubkey)) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey)) }; let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]); let sig = secp_ctx.sign_ecdsa(&sighash, &privkey); let mut ser_sig = sig.serialize_der().to_vec(); @@ -4899,5 +4971,62 @@ mod tests { } } + #[test] + fn test_with_channel_monitor_impl_logger() { + let secp_ctx = Secp256k1::new(); + let logger = Arc::new(TestLogger::new()); + + let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); + + let keys = InMemorySigner::new( + &secp_ctx, + SecretKey::from_slice(&[41; 32]).unwrap(), + SecretKey::from_slice(&[41; 32]).unwrap(), + SecretKey::from_slice(&[41; 32]).unwrap(), + SecretKey::from_slice(&[41; 32]).unwrap(), + SecretKey::from_slice(&[41; 32]).unwrap(), + [41; 32], + 0, + [0; 32], + [0; 32], + ); + + let counterparty_pubkeys = ChannelPublicKeys { + funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()), + revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())), + payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()), + delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())), + htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())), + }; + let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() }; + let channel_parameters = ChannelTransactionParameters { + holder_pubkeys: keys.holder_channel_pubkeys.clone(), + holder_selected_contest_delay: 66, + is_outbound_from_holder: true, + counterparty_parameters: Some(CounterpartyChannelTransactionParameters { + pubkeys: counterparty_pubkeys, + selected_contest_delay: 67, + }), + funding_outpoint: Some(funding_outpoint), + channel_type_features: ChannelTypeFeatures::only_static_remote_key() + }; + let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()); + let best_block = BestBlock::from_network(Network::Testnet); + let monitor = ChannelMonitor::new(Secp256k1::new(), keys, + Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(), + (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()), + &channel_parameters, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()), + best_block, dummy_key); + + let chan_id = monitor.inner.lock().unwrap().funding_info.0.to_channel_id().clone(); + let context_logger = WithChannelMonitor::from(&logger, &monitor); + log_error!(context_logger, "This is an error"); + log_warn!(context_logger, "This is an error"); + log_debug!(context_logger, "This is an error"); + log_trace!(context_logger, "This is an error"); + log_gossip!(context_logger, "This is an error"); + log_info!(context_logger, "This is an error"); + logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6); + } // Further testing is done in the ChannelManager integration tests. }