X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fln%2Fonchaintx.rs;h=37c7f3964a21d0315f46ba76be9e28455220fb56;hb=9d8efecadf4d5f966223b352ffc0a65a8fdfd263;hp=e27315a8f075bd647d19c6e1ea66a5555ae9fea7;hpb=479e1c8ddfc6caa11cd4f872e0b7149534035423;p=rust-lightning diff --git a/lightning/src/ln/onchaintx.rs b/lightning/src/ln/onchaintx.rs index e27315a8..37c7f396 100644 --- a/lightning/src/ln/onchaintx.rs +++ b/lightning/src/ln/onchaintx.rs @@ -1,3 +1,12 @@ +// This file is Copyright its original authors, visible in version control +// history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license +// , at your option. +// You may not use this file except in accordance with one or both of these +// licenses. + //! The logic to build claims and bump in-flight transactions until confirmations. //! //! OnchainTxHandler objetcs are fully-part of ChannelMonitor and encapsulates all @@ -54,7 +63,7 @@ pub struct ClaimTxBumpMaterial { // much time for confirmation and we need to bump it. height_timer: Option, // Tracked in case of reorg to wipe out now-superflous bump material - feerate_previous: u64, + feerate_previous: u32, // Soonest timelocks among set of outpoints claimed, used to compute // a priority of not feerate soonest_timelock: u32, @@ -65,7 +74,7 @@ pub struct ClaimTxBumpMaterial { impl Writeable for ClaimTxBumpMaterial { fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { self.height_timer.write(writer)?; - writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?; + writer.write_all(&byte_utils::be32_to_array(self.feerate_previous))?; writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?; writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?; for (outp, tx_material) in self.per_input_material.iter() { @@ -151,14 +160,14 @@ impl Readable for InputDescriptors { macro_rules! subtract_high_prio_fee { ($logger: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => { { - $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority); - let mut fee = $used_feerate * ($predicted_weight as u64) / 1000; + $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority).into(); + let mut fee = $used_feerate as u64 * $predicted_weight / 1000; if $value <= fee { - $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal); - fee = $used_feerate * ($predicted_weight as u64) / 1000; - if $value <= fee { - $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background); - fee = $used_feerate * ($predicted_weight as u64) / 1000; + $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal).into(); + fee = $used_feerate as u64 * $predicted_weight / 1000; + if $value <= fee.into() { + $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background).into(); + fee = $used_feerate as u64 * $predicted_weight / 1000; if $value <= fee { log_error!($logger, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)", fee, $value); @@ -462,7 +471,7 @@ impl OnchainTxHandler { /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent. - fn generate_claim_tx(&mut self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F, logger: L) -> Option<(Option, u64, Transaction)> + fn generate_claim_tx(&mut self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F, logger: L) -> Option<(Option, u32, Transaction)> where F::Target: FeeEstimator, L::Target: Logger, { @@ -490,20 +499,20 @@ impl OnchainTxHandler { macro_rules! RBF_bump { ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => { { - let mut used_feerate; + let mut used_feerate: u32; // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee... let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) { let mut value = $amount; if subtract_high_prio_fee!(logger, $fee_estimator, value, $predicted_weight, used_feerate) { // Overflow check is done in subtract_high_prio_fee - $amount - value + ($amount - value) } else { log_trace!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount); return None; } // ...else just increase the previous feerate by 25% (because that's a nice number) } else { - let fee = $old_feerate * $predicted_weight / 750; + let fee = $old_feerate as u64 * ($predicted_weight as u64) / 750; if $amount <= fee { log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", $amount); return None; @@ -511,8 +520,8 @@ impl OnchainTxHandler { fee }; - let previous_fee = $old_feerate * $predicted_weight / 1000; - let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000; + let previous_fee = $old_feerate as u64 * ($predicted_weight as u64) / 1000; + let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * ($predicted_weight as u64) / 1000; // BIP 125 Opt-in Full Replace-by-Fee Signaling // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions. // * 4. The replacement transaction must also pay for its own bandwidth at or above the rate set by the node's minimum relay fee setting. @@ -521,7 +530,7 @@ impl OnchainTxHandler { } else { new_fee }; - Some((new_fee, new_fee * 1000 / $predicted_weight)) + Some((new_fee, new_fee * 1000 / ($predicted_weight as u64))) } } } @@ -551,16 +560,16 @@ impl OnchainTxHandler { } } if dynamic_fee { - let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight; + let predicted_weight = (bumped_tx.get_weight() + inputs_witnesses_weight) as u64; let mut new_feerate; // If old feerate is 0, first iteration of this claim, use normal fee calculation if cached_claim_datas.feerate_previous != 0 { - if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) { + if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight) { // If new computed fee is superior at the whole claimable amount burn all in fees - if new_fee > amt { + if new_fee as u64 > amt { bumped_tx.output[0].value = 0; } else { - bumped_tx.output[0].value = amt - new_fee; + bumped_tx.output[0].value = amt - new_fee as u64; } new_feerate = feerate; } else { return None; } @@ -574,7 +583,7 @@ impl OnchainTxHandler { for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() { match per_outp_material { &InputMaterial::Revoked { ref per_commitment_point, ref remote_delayed_payment_base_key, ref remote_htlc_base_key, ref per_commitment_key, ref input_descriptor, ref amount, ref htlc, ref on_remote_tx_csv } => { - if let Ok(chan_keys) = TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, remote_delayed_payment_base_key, remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) { + if let Ok(chan_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, remote_delayed_payment_base_key, remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) { let witness_script = if let Some(ref htlc) = *htlc { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.a_htlc_key, &chan_keys.b_htlc_key, &chan_keys.revocation_key) @@ -582,7 +591,7 @@ impl OnchainTxHandler { chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, *on_remote_tx_csv, &chan_keys.a_delayed_payment_key) }; - if let Ok(sig) = self.key_storage.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, *on_remote_tx_csv, &self.secp_ctx) { + if let Ok(sig) = self.key_storage.sign_justice_transaction(&bumped_tx, i, *amount, &per_commitment_key, htlc, &self.secp_ctx) { bumped_tx.input[i].witness.push(sig.serialize_der().to_vec()); bumped_tx.input[i].witness[0].push(SigHashType::All as u8); if htlc.is_some() { @@ -598,11 +607,11 @@ impl OnchainTxHandler { } }, &InputMaterial::RemoteHTLC { ref per_commitment_point, ref remote_delayed_payment_base_key, ref remote_htlc_base_key, ref preimage, ref htlc } => { - if let Ok(chan_keys) = TxCreationKeys::new(&self.secp_ctx, &per_commitment_point, remote_delayed_payment_base_key, remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) { + if let Ok(chan_keys) = TxCreationKeys::derive_new(&self.secp_ctx, &per_commitment_point, remote_delayed_payment_base_key, remote_htlc_base_key, &self.key_storage.pubkeys().revocation_basepoint, &self.key_storage.pubkeys().htlc_basepoint) { let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, &chan_keys.a_htlc_key, &chan_keys.b_htlc_key, &chan_keys.revocation_key); if !preimage.is_some() { bumped_tx.lock_time = htlc.cltv_expiry }; // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation - if let Ok(sig) = self.key_storage.sign_remote_htlc_transaction(&bumped_tx, i, &witness_script, htlc.amount_msat / 1000, &per_commitment_point, preimage, &self.secp_ctx) { + if let Ok(sig) = self.key_storage.sign_remote_htlc_transaction(&bumped_tx, i, &htlc.amount_msat / 1000, &per_commitment_point, htlc, &self.secp_ctx) { bumped_tx.input[i].witness.push(sig.serialize_der().to_vec()); bumped_tx.input[i].witness[0].push(SigHashType::All as u8); if let &Some(preimage) = preimage { @@ -620,8 +629,8 @@ impl OnchainTxHandler { } } log_trace!(logger, "...with timer {}", new_timer.unwrap()); - assert!(predicted_weight >= bumped_tx.get_weight()); - return Some((new_timer, new_feerate, bumped_tx)) + assert!(predicted_weight >= bumped_tx.get_weight() as u64); + return Some((new_timer, new_feerate as u32, bumped_tx)) } else { for (_, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() { match per_outp_material { @@ -631,7 +640,7 @@ impl OnchainTxHandler { let feerate = (amount - htlc_tx.output[0].value) * 1000 / htlc_tx.get_weight() as u64; // Timer set to $NEVER given we can't bump tx without anchor outputs log_trace!(logger, "Going to broadcast Local HTLC-{} claiming HTLC output {} from {}...", if preimage.is_some() { "Success" } else { "Timeout" }, outp.vout, outp.txid); - return Some((None, feerate, htlc_tx)); + return Some((None, feerate as u32, htlc_tx)); } return None; }, @@ -884,7 +893,7 @@ impl OnchainTxHandler { fn sign_latest_local_htlcs(&mut self) { if let Some(ref local_commitment) = self.local_commitment { - if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, self.on_local_tx_csv, &self.secp_ctx) { + if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, &self.secp_ctx) { self.local_htlc_sigs = Some(Vec::new()); let ret = self.local_htlc_sigs.as_mut().unwrap(); for (htlc_idx, (local_sig, &(ref htlc, _))) in sigs.iter().zip(local_commitment.per_htlc.iter()).enumerate() { @@ -900,7 +909,7 @@ impl OnchainTxHandler { } fn sign_prev_local_htlcs(&mut self) { if let Some(ref local_commitment) = self.prev_local_commitment { - if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, self.on_local_tx_csv, &self.secp_ctx) { + if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, &self.secp_ctx) { self.prev_local_htlc_sigs = Some(Vec::new()); let ret = self.prev_local_htlc_sigs.as_mut().unwrap(); for (htlc_idx, (local_sig, &(ref htlc, _))) in sigs.iter().zip(local_commitment.per_htlc.iter()).enumerate() { @@ -930,7 +939,7 @@ impl OnchainTxHandler { } } - #[cfg(test)] + #[cfg(any(test, feature="unsafe_revoked_tx_signing"))] pub(super) fn get_fully_signed_copy_local_tx(&mut self, funding_redeemscript: &Script) -> Option { if let Some(ref mut local_commitment) = self.local_commitment { let local_commitment = local_commitment.clone(); @@ -970,7 +979,7 @@ impl OnchainTxHandler { htlc_tx } - #[cfg(test)] + #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))] pub(super) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option) -> Option { let latest_had_sigs = self.local_htlc_sigs.is_some(); let prev_had_sigs = self.prev_local_htlc_sigs.is_some();