+// This file is Copyright its original authors, visible in version control
+// history.
+//
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
+// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, 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
//! The logic to build claims and bump in-flight transactions until confirmations.
//!
//! OnchainTxHandler objetcs are fully-part of ChannelMonitor and encapsulates all
// much time for confirmation and we need to bump it.
height_timer: Option<u32>,
// Tracked in case of reorg to wipe out now-superflous bump material
// much time for confirmation and we need to bump it.
height_timer: Option<u32>,
// Tracked in case of reorg to wipe out now-superflous bump material
// Soonest timelocks among set of outpoints claimed, used to compute
// a priority of not feerate
soonest_timelock: u32,
// Soonest timelocks among set of outpoints claimed, used to compute
// a priority of not feerate
soonest_timelock: u32,
impl Writeable for ClaimTxBumpMaterial {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
self.height_timer.write(writer)?;
impl Writeable for ClaimTxBumpMaterial {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
self.height_timer.write(writer)?;
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() {
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() {
macro_rules! subtract_high_prio_fee {
($logger: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
{
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;
- $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);
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);
local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
prev_local_commitment: Option<LocalCommitmentTransaction>,
prev_local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
prev_local_commitment: Option<LocalCommitmentTransaction>,
prev_local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
let prev_local_commitment = Readable::read(reader)?;
let prev_local_htlc_sigs = Readable::read(reader)?;
let prev_local_commitment = Readable::read(reader)?;
let prev_local_htlc_sigs = Readable::read(reader)?;
- pub(super) fn new(destination_script: Script, keys: ChanSigner, local_csv: u16, remote_csv: u16) -> Self {
+ pub(super) fn new(destination_script: Script, keys: ChanSigner, on_local_tx_csv: u16) -> Self {
local_htlc_sigs: None,
prev_local_commitment: None,
prev_local_htlc_sigs: None,
local_htlc_sigs: None,
prev_local_commitment: None,
prev_local_htlc_sigs: None,
key_storage,
pending_claim_requests: HashMap::new(),
claimable_outpoints: HashMap::new(),
key_storage,
pending_claim_requests: HashMap::new(),
claimable_outpoints: HashMap::new(),
/// 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.
/// 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<F: Deref, L: Deref>(&mut self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F, logger: L) -> Option<(Option<u32>, u64, Transaction)>
+ fn generate_claim_tx<F: Deref, L: Deref>(&mut self, height: u32, cached_claim_datas: &ClaimTxBumpMaterial, fee_estimator: F, logger: L) -> Option<(Option<u32>, u32, Transaction)>
macro_rules! RBF_bump {
($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
{
macro_rules! RBF_bump {
($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
{
// 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
// 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
} 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 {
} 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 {
if $amount <= fee {
log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
return None;
if $amount <= fee {
log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
return None;
- 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.
// 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.
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 {
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) {
for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
match per_outp_material {
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 } => {
+ &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) {
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)
} else {
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) {
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)
} else {
- chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, self.remote_csv, &chan_keys.a_delayed_payment_key)
+ 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, &witness_script, *amount, &per_commitment_key, &chan_keys.revocation_key, htlc.is_some(), &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() {
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() {
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
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 {
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 {
- 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 {
} else {
for (_, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
match per_outp_material {
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);
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);
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() {
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() {
}
fn sign_prev_local_htlcs(&mut self) {
if let Some(ref local_commitment) = self.prev_local_commitment {
}
fn sign_prev_local_htlcs(&mut self) {
if let Some(ref local_commitment) = self.prev_local_commitment {
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() {
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() {
pub(super) fn get_fully_signed_copy_local_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
if let Some(ref mut local_commitment) = self.local_commitment {
let local_commitment = local_commitment.clone();
pub(super) fn get_fully_signed_copy_local_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
if let Some(ref mut local_commitment) = self.local_commitment {
let local_commitment = local_commitment.clone();
if let &Some(ref htlc_sigs) = &self.local_htlc_sigs {
let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
htlc_tx = Some(self.local_commitment.as_ref().unwrap()
if let &Some(ref htlc_sigs) = &self.local_htlc_sigs {
let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
htlc_tx = Some(self.local_commitment.as_ref().unwrap()
- .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.local_csv));
+ .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.on_local_tx_csv));
if let &Some(ref htlc_sigs) = &self.prev_local_htlc_sigs {
let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
htlc_tx = Some(self.prev_local_commitment.as_ref().unwrap()
if let &Some(ref htlc_sigs) = &self.prev_local_htlc_sigs {
let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
htlc_tx = Some(self.prev_local_commitment.as_ref().unwrap()
- .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.local_csv));
+ .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.on_local_tx_csv));
pub(super) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
let latest_had_sigs = self.local_htlc_sigs.is_some();
let prev_had_sigs = self.prev_local_htlc_sigs.is_some();
pub(super) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
let latest_had_sigs = self.local_htlc_sigs.is_some();
let prev_had_sigs = self.prev_local_htlc_sigs.is_some();