1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Various utilities to assemble claimable outpoints in package of one or more transactions. Those
11 //! packages are attached metadata, guiding their aggregable or fee-bumping re-schedule. This file
12 //! also includes witness weight computation and fee computation methods.
14 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
15 use bitcoin::blockdata::transaction::{TxOut,TxIn, Transaction, SigHashType};
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
19 use bitcoin::hash_types::Txid;
21 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
23 use ln::PaymentPreimage;
24 use ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment, HTLC_OUTPUT_IN_COMMITMENT_SIZE};
26 use ln::msgs::DecodeError;
27 use chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
28 use chain::keysinterface::Sign;
29 use chain::onchaintx::OnchainTxHandler;
31 use util::logger::Logger;
32 use util::ser::{Readable, Writer, Writeable};
38 const MAX_ALLOC_SIZE: usize = 64*1024;
41 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
42 pub(crate) const WEIGHT_REVOKED_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 133;
43 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
44 pub(crate) const WEIGHT_REVOKED_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 139;
45 // number_of_witness_elements + sig_length + counterpartyhtlc_sig + preimage_length + preimage + witness_script_length + witness_script
46 pub(crate) const WEIGHT_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 32 + 1 + 133;
47 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
48 pub(crate) const WEIGHT_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 139;
49 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
50 pub(crate) const WEIGHT_REVOKED_OUTPUT: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 77;
52 /// Height delay at which transactions are fee-bumped/rebroadcasted with a low priority.
53 const LOW_FREQUENCY_BUMP_INTERVAL: u32 = 15;
54 /// Height delay at which transactions are fee-bumped/rebroadcasted with a middle priority.
55 const MIDDLE_FREQUENCY_BUMP_INTERVAL: u32 = 3;
56 /// Height delay at which transactions are fee-bumped/rebroadcasted with a high priority.
57 const HIGH_FREQUENCY_BUMP_INTERVAL: u32 = 1;
59 /// A struct to describe a revoked output and corresponding information to generate a solving
60 /// witness spending a commitment `to_local` output or a second-stage HTLC transaction output.
62 /// CSV and pubkeys are used as part of a witnessScript redeeming a balance output, amount is used
63 /// as part of the signature hash and revocation secret to generate a satisfying witness.
64 #[derive(Clone, PartialEq)]
65 pub(crate) struct RevokedOutput {
66 per_commitment_point: PublicKey,
67 counterparty_delayed_payment_base_key: PublicKey,
68 counterparty_htlc_base_key: PublicKey,
69 per_commitment_key: SecretKey,
72 on_counterparty_tx_csv: u16,
76 pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, per_commitment_key: SecretKey, amount: u64, on_counterparty_tx_csv: u16) -> Self {
79 counterparty_delayed_payment_base_key,
80 counterparty_htlc_base_key,
82 weight: WEIGHT_REVOKED_OUTPUT,
84 on_counterparty_tx_csv
89 impl_writeable!(RevokedOutput, 33*3 + 32 + 8 + 8 + 2, {
91 counterparty_delayed_payment_base_key,
92 counterparty_htlc_base_key,
96 on_counterparty_tx_csv
99 /// A struct to describe a revoked offered output and corresponding information to generate a
102 /// HTLCOuputInCommitment (hash timelock, direction) and pubkeys are used to generate a suitable
105 /// CSV is used as part of a witnessScript redeeming a balance output, amount is used as part
106 /// of the signature hash and revocation secret to generate a satisfying witness.
107 #[derive(Clone, PartialEq)]
108 pub(crate) struct RevokedHTLCOutput {
109 per_commitment_point: PublicKey,
110 counterparty_delayed_payment_base_key: PublicKey,
111 counterparty_htlc_base_key: PublicKey,
112 per_commitment_key: SecretKey,
115 htlc: HTLCOutputInCommitment,
118 impl RevokedHTLCOutput {
119 pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, per_commitment_key: SecretKey, amount: u64, htlc: HTLCOutputInCommitment) -> Self {
120 let weight = if htlc.offered { WEIGHT_REVOKED_OFFERED_HTLC } else { WEIGHT_REVOKED_RECEIVED_HTLC };
122 per_commitment_point,
123 counterparty_delayed_payment_base_key,
124 counterparty_htlc_base_key,
133 impl_writeable!(RevokedHTLCOutput, 33*3 + 32 + 8 + 8 + HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
134 per_commitment_point,
135 counterparty_delayed_payment_base_key,
136 counterparty_htlc_base_key,
143 /// A struct to describe a HTLC output on a counterparty commitment transaction.
145 /// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
148 /// The preimage is used as part of the witness.
149 #[derive(Clone, PartialEq)]
150 pub(crate) struct CounterpartyOfferedHTLCOutput {
151 per_commitment_point: PublicKey,
152 counterparty_delayed_payment_base_key: PublicKey,
153 counterparty_htlc_base_key: PublicKey,
154 preimage: PaymentPreimage,
155 htlc: HTLCOutputInCommitment
158 impl CounterpartyOfferedHTLCOutput {
159 pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, preimage: PaymentPreimage, htlc: HTLCOutputInCommitment) -> Self {
160 CounterpartyOfferedHTLCOutput {
161 per_commitment_point,
162 counterparty_delayed_payment_base_key,
163 counterparty_htlc_base_key,
170 impl_writeable!(CounterpartyOfferedHTLCOutput, 33*3 + 32 + HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
171 per_commitment_point,
172 counterparty_delayed_payment_base_key,
173 counterparty_htlc_base_key,
178 /// A struct to describe a HTLC output on a counterparty commitment transaction.
180 /// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
182 #[derive(Clone, PartialEq)]
183 pub(crate) struct CounterpartyReceivedHTLCOutput {
184 per_commitment_point: PublicKey,
185 counterparty_delayed_payment_base_key: PublicKey,
186 counterparty_htlc_base_key: PublicKey,
187 htlc: HTLCOutputInCommitment
190 impl CounterpartyReceivedHTLCOutput {
191 pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: PublicKey, counterparty_htlc_base_key: PublicKey, htlc: HTLCOutputInCommitment) -> Self {
192 CounterpartyReceivedHTLCOutput {
193 per_commitment_point,
194 counterparty_delayed_payment_base_key,
195 counterparty_htlc_base_key,
201 impl_writeable!(CounterpartyReceivedHTLCOutput, 33*3 + HTLC_OUTPUT_IN_COMMITMENT_SIZE, {
202 per_commitment_point,
203 counterparty_delayed_payment_base_key,
204 counterparty_htlc_base_key,
208 /// A struct to describe a HTLC output on holder commitment transaction.
210 /// Either offered or received, the amount is always used as part of the bip143 sighash.
211 /// Preimage is only included as part of the witness in former case.
212 #[derive(Clone, PartialEq)]
213 pub(crate) struct HolderHTLCOutput {
214 preimage: Option<PaymentPreimage>,
218 impl HolderHTLCOutput {
219 pub(crate) fn build(preimage: Option<PaymentPreimage>, amount: u64) -> Self {
227 impl_writeable!(HolderHTLCOutput, 0, {
232 /// A struct to describe the channel output on the funding transaction.
234 /// witnessScript is used as part of the witness redeeming the funding utxo.
235 #[derive(Clone, PartialEq)]
236 pub(crate) struct HolderFundingOutput {
237 funding_redeemscript: Script,
240 impl HolderFundingOutput {
241 pub(crate) fn build(funding_redeemscript: Script) -> Self {
242 HolderFundingOutput {
243 funding_redeemscript,
248 impl_writeable!(HolderFundingOutput, 0, {
252 /// A wrapper encapsulating all in-protocol differing outputs types.
254 /// The generic API offers access to an outputs common attributes or allow transformation such as
255 /// finalizing an input claiming the output.
256 #[derive(Clone, PartialEq)]
257 pub(crate) enum PackageSolvingData {
258 RevokedOutput(RevokedOutput),
259 RevokedHTLCOutput(RevokedHTLCOutput),
260 CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput),
261 CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput),
262 HolderHTLCOutput(HolderHTLCOutput),
263 HolderFundingOutput(HolderFundingOutput),
266 impl PackageSolvingData {
267 fn amount(&self) -> u64 {
268 let amt = match self {
269 PackageSolvingData::RevokedOutput(ref outp) => { outp.amount },
270 PackageSolvingData::RevokedHTLCOutput(ref outp) => { outp.amount },
271 PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => { outp.htlc.amount_msat / 1000 },
272 PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => { outp.htlc.amount_msat / 1000 },
273 // Note: Currently, amounts of holder outputs spending witnesses aren't used
274 // as we can't malleate spending package to increase their feerate. This
275 // should change with the remaining anchor output patchset.
276 PackageSolvingData::HolderHTLCOutput(..) => { 0 },
277 PackageSolvingData::HolderFundingOutput(..) => { 0 },
281 fn weight(&self) -> usize {
282 let weight = match self {
283 PackageSolvingData::RevokedOutput(ref outp) => { outp.weight as usize },
284 PackageSolvingData::RevokedHTLCOutput(ref outp) => { outp.weight as usize },
285 PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { WEIGHT_OFFERED_HTLC as usize },
286 PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { WEIGHT_RECEIVED_HTLC as usize },
287 // Note: Currently, weights of holder outputs spending witnesses aren't used
288 // as we can't malleate spending package to increase their feerate. This
289 // should change with the remaining anchor output patchset.
290 PackageSolvingData::HolderHTLCOutput(..) => { debug_assert!(false); 0 },
291 PackageSolvingData::HolderFundingOutput(..) => { debug_assert!(false); 0 },
295 fn is_compatible(&self, input: &PackageSolvingData) -> bool {
297 PackageSolvingData::RevokedOutput(..) => {
299 PackageSolvingData::RevokedHTLCOutput(..) => { true },
300 PackageSolvingData::RevokedOutput(..) => { true },
304 PackageSolvingData::RevokedHTLCOutput(..) => {
306 PackageSolvingData::RevokedOutput(..) => { true },
307 PackageSolvingData::RevokedHTLCOutput(..) => { true },
311 _ => { mem::discriminant(self) == mem::discriminant(&input) }
314 fn finalize_input<Signer: Sign>(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler<Signer>) -> bool {
316 PackageSolvingData::RevokedOutput(ref outp) => {
317 if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
318 let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
319 //TODO: should we panic on signer failure ?
320 if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &onchain_handler.secp_ctx) {
321 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
322 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
323 bumped_tx.input[i].witness.push(vec!(1));
324 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
325 } else { return false; }
328 PackageSolvingData::RevokedHTLCOutput(ref outp) => {
329 if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
330 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
331 //TODO: should we panic on signer failure ?
332 if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_htlc(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &outp.htlc, &onchain_handler.secp_ctx) {
333 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
334 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
335 bumped_tx.input[i].witness.push(chan_keys.revocation_key.clone().serialize().to_vec());
336 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
337 } else { return false; }
340 PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
341 if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
342 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
344 if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
345 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
346 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
347 bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
348 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
352 PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
353 if let Ok(chan_keys) = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint) {
354 let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
356 bumped_tx.lock_time = outp.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
357 if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
358 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
359 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
360 // Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
361 bumped_tx.input[i].witness.push(vec![]);
362 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
366 _ => { panic!("API Error!"); }
370 fn get_finalized_tx<Signer: Sign>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<Transaction> {
372 PackageSolvingData::HolderHTLCOutput(ref outp) => { return onchain_handler.get_fully_signed_htlc_tx(outpoint, &outp.preimage); }
373 PackageSolvingData::HolderFundingOutput(ref outp) => { return Some(onchain_handler.get_fully_signed_holder_tx(&outp.funding_redeemscript)); }
374 _ => { panic!("API Error!"); }
379 impl Writeable for PackageSolvingData {
380 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
382 PackageSolvingData::RevokedOutput(ref revoked_outp) => {
384 revoked_outp.write(writer)?;
386 PackageSolvingData::RevokedHTLCOutput(ref revoked_outp) => {
388 revoked_outp.write(writer)?;
390 PackageSolvingData::CounterpartyOfferedHTLCOutput(ref counterparty_outp) => {
392 counterparty_outp.write(writer)?;
394 PackageSolvingData::CounterpartyReceivedHTLCOutput(ref counterparty_outp) => {
396 counterparty_outp.write(writer)?;
398 PackageSolvingData::HolderHTLCOutput(ref holder_outp) => {
400 holder_outp.write(writer)?;
402 PackageSolvingData::HolderFundingOutput(ref funding_outp) => {
404 funding_outp.write(writer)?;
411 impl Readable for PackageSolvingData {
412 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
413 let byte = <u8 as Readable>::read(reader)?;
414 let solving_data = match byte {
416 PackageSolvingData::RevokedOutput(Readable::read(reader)?)
419 PackageSolvingData::RevokedHTLCOutput(Readable::read(reader)?)
422 PackageSolvingData::CounterpartyOfferedHTLCOutput(Readable::read(reader)?)
425 PackageSolvingData::CounterpartyReceivedHTLCOutput(Readable::read(reader)?)
428 PackageSolvingData::HolderHTLCOutput(Readable::read(reader)?)
431 PackageSolvingData::HolderFundingOutput(Readable::read(reader)?)
433 _ => return Err(DecodeError::UnknownVersion)
439 /// A malleable package might be aggregated with other packages to save on fees.
440 /// A untractable package has been counter-signed and aggregable will break cached counterparty
442 #[derive(Clone, PartialEq)]
443 pub(crate) enum PackageMalleability {
448 /// A structure to describe a package content that is generated by ChannelMonitor and
449 /// used by OnchainTxHandler to generate and broadcast transactions settling onchain claims.
451 /// A package is defined as one or more transactions claiming onchain outputs in reaction
452 /// to confirmation of a channel transaction. Those packages might be aggregated to save on
453 /// fees, if satisfaction of outputs's witnessScript let's us do so.
455 /// As packages are time-sensitive, we fee-bump and rebroadcast them at scheduled intervals.
456 /// Failing to confirm a package translate as a loss of funds for the user.
457 #[derive(Clone, PartialEq)]
458 pub struct PackageTemplate {
459 // List of onchain outputs and solving data to generate satisfying witnesses.
460 inputs: Vec<(BitcoinOutPoint, PackageSolvingData)>,
461 // Packages are deemed as malleable if we have local knwoledge of at least one set of
462 // private keys yielding a satisfying witnesses. Malleability implies that we can aggregate
463 // packages among them to save on fees or rely on RBF to bump their feerates.
464 // Untractable packages have been counter-signed and thus imply that we can't aggregate
465 // them without breaking signatures. Fee-bumping strategy will also rely on CPFP.
466 malleability: PackageMalleability,
467 // Block height after which the earlier-output belonging to this package is mature for a
468 // competing claim by the counterparty. As our chain tip becomes nearer from the timelock,
469 // the fee-bumping frequency will increase. See `OnchainTxHandler::get_height_timer`.
470 soonest_conf_deadline: u32,
471 // Determines if this package can be aggregated.
472 // Timelocked outputs belonging to the same transaction might have differing
473 // satisfying heights. Picking up the later height among the output set would be a valid
474 // aggregable strategy but it comes with at least 2 trade-offs :
475 // * earlier-output fund are going to take longer to come back
476 // * CLTV delta backing up a corresponding HTLC on an upstream channel could be swallowed
477 // by the requirement of the later-output part of the set
478 // For now, we mark such timelocked outputs as non-aggregable, though we might introduce
479 // smarter aggregable strategy in the future.
481 // Cache of package feerate committed at previous (re)broadcast. If bumping resources
482 // (either claimed output value or external utxo), it will keep increasing until holder
483 // or counterparty successful claim.
484 feerate_previous: u64,
485 // Cache of next height at which fee-bumping and rebroadcast will be attempted. In
486 // the future, we might abstract it to an observed mempool fluctuation.
487 height_timer: Option<u32>,
488 // Confirmation height of the claimed outputs set transaction. In case of reorg reaching
489 // it, we wipe out and forget the package.
490 height_original: u32,
493 impl PackageTemplate {
494 pub(crate) fn is_malleable(&self) -> bool {
495 self.malleability == PackageMalleability::Malleable
497 pub(crate) fn timelock(&self) -> u32 {
498 self.soonest_conf_deadline
500 pub(crate) fn aggregable(&self) -> bool {
503 pub(crate) fn set_feerate(&mut self, new_feerate: u64) {
504 self.feerate_previous = new_feerate;
506 pub(crate) fn timer(&self) -> Option<u32> {
507 if let Some(ref timer) = self.height_timer {
512 pub(crate) fn set_timer(&mut self, new_timer: Option<u32>) {
513 self.height_timer = new_timer;
515 pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
516 self.inputs.iter().map(|(o, _)| o).collect()
518 pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
519 match self.malleability {
520 PackageMalleability::Malleable => {
521 let mut split_package = None;
522 let timelock = self.soonest_conf_deadline;
523 let aggregable = self.aggregable;
524 let feerate_previous = self.feerate_previous;
525 let height_timer = self.height_timer;
526 let height_original = self.height_original;
527 self.inputs.retain(|outp| {
528 if *split_outp == outp.0 {
529 split_package = Some(PackageTemplate {
530 inputs: vec![(outp.0, outp.1.clone())],
531 malleability: PackageMalleability::Malleable,
532 soonest_conf_deadline: timelock,
542 return split_package;
545 // Note, we may try to split on remote transaction for
546 // which we don't have a competing one (HTLC-Success before
547 // timelock expiration). This explain we don't panic!
548 // We should refactor OnchainTxHandler::block_connected to
549 // only test equality on competing claims.
554 pub(crate) fn merge_package(&mut self, mut merge_from: PackageTemplate) {
555 assert_eq!(self.height_original, merge_from.height_original);
556 if self.malleability == PackageMalleability::Untractable || merge_from.malleability == PackageMalleability::Untractable {
557 panic!("Merging template on untractable packages");
559 if !self.aggregable || !merge_from.aggregable {
560 panic!("Merging non aggregatable packages");
562 if let Some((_, lead_input)) = self.inputs.first() {
563 for (_, v) in merge_from.inputs.iter() {
564 if !lead_input.is_compatible(v) { panic!("Merging outputs from differing types !"); }
566 } else { panic!("Merging template on an empty package"); }
567 for (k, v) in merge_from.inputs.drain(..) {
568 self.inputs.push((k, v));
570 //TODO: verify coverage and sanity?
571 if self.soonest_conf_deadline > merge_from.soonest_conf_deadline {
572 self.soonest_conf_deadline = merge_from.soonest_conf_deadline;
574 if self.feerate_previous > merge_from.feerate_previous {
575 self.feerate_previous = merge_from.feerate_previous;
577 self.height_timer = cmp::min(self.height_timer, merge_from.height_timer);
579 pub(crate) fn package_amount(&self) -> u64 {
581 for (_, outp) in self.inputs.iter() {
582 amounts += outp.amount();
586 pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
587 let mut inputs_weight = 0;
588 let mut witnesses_weight = 2; // count segwit flags
589 for (_, outp) in self.inputs.iter() {
590 // previous_out_point: 36 bytes ; var_int: 1 byte ; sequence: 4 bytes
591 inputs_weight += 41 * WITNESS_SCALE_FACTOR;
592 witnesses_weight += outp.weight();
594 // version: 4 bytes ; count_tx_in: 1 byte ; count_tx_out: 1 byte ; lock_time: 4 bytes
595 let transaction_weight = 10 * WITNESS_SCALE_FACTOR;
596 // value: 8 bytes ; var_int: 1 byte ; pk_script: `destination_script.len()`
597 let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
598 inputs_weight + witnesses_weight + transaction_weight + output_weight
600 pub(crate) fn finalize_package<L: Deref, Signer: Sign>(&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L) -> Option<Transaction>
601 where L::Target: Logger,
603 match self.malleability {
604 PackageMalleability::Malleable => {
605 let mut bumped_tx = Transaction {
610 script_pubkey: destination_script,
614 for (outpoint, _) in self.inputs.iter() {
615 bumped_tx.input.push(TxIn {
616 previous_output: *outpoint,
617 script_sig: Script::new(),
618 sequence: 0xfffffffd,
622 for (i, (outpoint, out)) in self.inputs.iter().enumerate() {
623 log_trace!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
624 if !out.finalize_input(&mut bumped_tx, i, onchain_handler) { return None; }
626 log_trace!(logger, "Finalized transaction {} ready to broadcast", bumped_tx.txid());
627 return Some(bumped_tx);
629 PackageMalleability::Untractable => {
630 if let Some((outpoint, outp)) = self.inputs.first() {
631 if let Some(final_tx) = outp.get_finalized_tx(outpoint, onchain_handler) {
632 log_trace!(logger, "Adding claiming input for outpoint {}:{}", outpoint.txid, outpoint.vout);
633 log_trace!(logger, "Finalized transaction {} ready to broadcast", final_tx.txid());
634 return Some(final_tx);
637 } else { panic!("API Error: Package must not be inputs empty"); }
641 /// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
642 /// output detection, we generate a first version of a claim tx and associate to it a height timer. A height timer is an absolute block
643 /// height that once reached we should generate a new bumped "version" of the claim tx to be sure that we safely claim outputs before
644 /// that our counterparty can do so. If timelock expires soon, height timer is going to be scaled down in consequence to increase
645 /// frequency of the bump and so increase our bets of success.
646 pub(crate) fn get_height_timer(&self, current_height: u32) -> u32 {
647 if self.soonest_conf_deadline <= current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL {
648 return current_height + HIGH_FREQUENCY_BUMP_INTERVAL
649 } else if self.soonest_conf_deadline - current_height <= LOW_FREQUENCY_BUMP_INTERVAL {
650 return current_height + MIDDLE_FREQUENCY_BUMP_INTERVAL
652 current_height + LOW_FREQUENCY_BUMP_INTERVAL
654 /// Returns value in satoshis to be included as package outgoing output amount and feerate with which package finalization should be done.
655 pub(crate) fn compute_package_output<F: Deref, L: Deref>(&self, predicted_weight: usize, input_amounts: u64, fee_estimator: &F, logger: &L) -> Option<(u64, u64)>
656 where F::Target: FeeEstimator,
659 // If old feerate is 0, first iteration of this claim, use normal fee calculation
660 if self.feerate_previous != 0 {
661 if let Some((new_fee, feerate)) = feerate_bump(predicted_weight, input_amounts, self.feerate_previous, fee_estimator, logger) {
662 // If new computed fee is superior at the whole claimable amount burn all in fees
663 if new_fee > input_amounts {
664 return Some((0, feerate));
666 return Some((input_amounts - new_fee, feerate));
670 if let Some((new_fee, feerate)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
671 return Some((input_amounts - new_fee, feerate));
676 pub (crate) fn build_package(txid: Txid, vout: u32, input_solving_data: PackageSolvingData, soonest_conf_deadline: u32, aggregable: bool, height_original: u32) -> Self {
677 let malleability = match input_solving_data {
678 PackageSolvingData::RevokedOutput(..) => { PackageMalleability::Malleable },
679 PackageSolvingData::RevokedHTLCOutput(..) => { PackageMalleability::Malleable },
680 PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { PackageMalleability::Malleable },
681 PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { PackageMalleability::Malleable },
682 PackageSolvingData::HolderHTLCOutput(..) => { PackageMalleability::Untractable },
683 PackageSolvingData::HolderFundingOutput(..) => { PackageMalleability::Untractable },
685 let mut inputs = Vec::with_capacity(1);
686 inputs.push((BitcoinOutPoint { txid, vout }, input_solving_data));
690 soonest_conf_deadline,
699 impl Writeable for PackageTemplate {
700 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
701 writer.write_all(&byte_utils::be64_to_array(self.inputs.len() as u64))?;
702 for (ref outpoint, ref rev_outp) in self.inputs.iter() {
703 outpoint.write(writer)?;
704 rev_outp.write(writer)?;
706 self.soonest_conf_deadline.write(writer)?;
707 self.feerate_previous.write(writer)?;
708 self.height_timer.write(writer)?;
709 self.height_original.write(writer)?;
714 impl Readable for PackageTemplate {
715 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
716 let inputs_count = <u64 as Readable>::read(reader)?;
717 let mut inputs: Vec<(BitcoinOutPoint, PackageSolvingData)> = Vec::with_capacity(cmp::min(inputs_count as usize, MAX_ALLOC_SIZE / 128));
718 for _ in 0..inputs_count {
719 let outpoint = Readable::read(reader)?;
720 let rev_outp = Readable::read(reader)?;
721 inputs.push((outpoint, rev_outp));
723 let (malleability, aggregable) = if let Some((_, lead_input)) = inputs.first() {
725 PackageSolvingData::RevokedOutput(..) => { (PackageMalleability::Malleable, true) },
726 PackageSolvingData::RevokedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
727 PackageSolvingData::CounterpartyOfferedHTLCOutput(..) => { (PackageMalleability::Malleable, true) },
728 PackageSolvingData::CounterpartyReceivedHTLCOutput(..) => { (PackageMalleability::Malleable, false) },
729 PackageSolvingData::HolderHTLCOutput(..) => { (PackageMalleability::Untractable, false) },
730 PackageSolvingData::HolderFundingOutput(..) => { (PackageMalleability::Untractable, false) },
732 } else { return Err(DecodeError::InvalidValue); };
733 let soonest_conf_deadline = Readable::read(reader)?;
734 let feerate_previous = Readable::read(reader)?;
735 let height_timer = Readable::read(reader)?;
736 let height_original = Readable::read(reader)?;
740 soonest_conf_deadline,
749 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
750 /// weight. We start with the highest priority feerate returned by the node's fee estimator then
751 /// fall-back to lower priorities until we have enough value available to suck from.
753 /// If the proposed fee is less than the available spent output's values, we return the proposed
754 /// fee and the corresponding updated feerate. If the proposed fee is equal or more than the
755 /// available spent output's values, we return nothing
756 fn compute_fee_from_spent_amounts<F: Deref, L: Deref>(input_amounts: u64, predicted_weight: usize, fee_estimator: &F, logger: &L) -> Option<(u64, u64)>
757 where F::Target: FeeEstimator,
760 let mut updated_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) as u64;
761 let mut fee = updated_feerate * (predicted_weight as u64) / 1000;
762 if input_amounts <= fee {
763 updated_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal) as u64;
764 fee = updated_feerate * (predicted_weight as u64) / 1000;
765 if input_amounts <= fee {
766 updated_feerate = fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background) as u64;
767 fee = updated_feerate * (predicted_weight as u64) / 1000;
768 if input_amounts <= fee {
769 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)",
773 log_warn!(logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
775 Some((fee, updated_feerate))
778 log_warn!(logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
780 Some((fee, updated_feerate))
783 Some((fee, updated_feerate))
787 /// Attempt to propose a bumping fee for a transaction from its spent output's values and predicted
788 /// weight. If feerates proposed by the fee-estimator have been increasing since last fee-bumping
789 /// attempt, use them. Otherwise, blindly bump the feerate by 25% of the previous feerate. We also
790 /// verify that those bumping heuristics respect BIP125 rules 3) and 4) and if required adjust
791 /// the new fee to meet the RBF policy requirement.
792 fn feerate_bump<F: Deref, L: Deref>(predicted_weight: usize, input_amounts: u64, previous_feerate: u64, fee_estimator: &F, logger: &L) -> Option<(u64, u64)>
793 where F::Target: FeeEstimator,
796 // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
797 let new_fee = if let Some((new_fee, _)) = compute_fee_from_spent_amounts(input_amounts, predicted_weight, fee_estimator, logger) {
798 let updated_feerate = new_fee / (predicted_weight as u64 * 1000);
799 if updated_feerate > previous_feerate {
802 // ...else just increase the previous feerate by 25% (because that's a nice number)
803 let new_fee = previous_feerate * (predicted_weight as u64) / 750;
804 if input_amounts <= new_fee {
805 log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", input_amounts);
811 log_trace!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", input_amounts);
815 let previous_fee = previous_feerate * (predicted_weight as u64) / 1000;
816 let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * (predicted_weight as u64) / 1000;
817 // BIP 125 Opt-in Full Replace-by-Fee Signaling
818 // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
819 // * 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.
820 let new_fee = if new_fee < previous_fee + min_relay_fee {
821 new_fee + previous_fee + min_relay_fee - new_fee
825 Some((new_fee, new_fee * 1000 / (predicted_weight as u64)))
830 use chain::package::{CounterpartyReceivedHTLCOutput, HolderHTLCOutput, PackageTemplate, PackageSolvingData, RevokedOutput, WEIGHT_REVOKED_OUTPUT};
832 use ln::chan_utils::HTLCOutputInCommitment;
833 use ln::{PaymentPreimage, PaymentHash};
835 use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
836 use bitcoin::blockdata::script::Script;
837 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
839 use bitcoin::hashes::hex::FromHex;
841 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
842 use bitcoin::secp256k1::Secp256k1;
844 macro_rules! dumb_revk_output {
845 ($secp_ctx: expr) => {
847 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
848 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
849 PackageSolvingData::RevokedOutput(RevokedOutput::build(dumb_point, dumb_point, dumb_point, dumb_scalar, 0, 0))
854 macro_rules! dumb_counterparty_output {
855 ($secp_ctx: expr, $amt: expr) => {
857 let dumb_scalar = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
858 let dumb_point = PublicKey::from_secret_key(&$secp_ctx, &dumb_scalar);
859 let hash = PaymentHash([1; 32]);
860 let htlc = HTLCOutputInCommitment { offered: true, amount_msat: $amt, cltv_expiry: 0, payment_hash: hash, transaction_output_index: None };
861 PackageSolvingData::CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput::build(dumb_point, dumb_point, dumb_point, htlc))
866 macro_rules! dumb_htlc_output {
869 let preimage = PaymentPreimage([2;32]);
870 PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build(Some(preimage), 0))
877 fn test_package_differing_heights() {
878 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
879 let secp_ctx = Secp256k1::new();
880 let revk_outp = dumb_revk_output!(secp_ctx);
882 let mut package_one_hundred = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
883 let package_two_hundred = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 200);
884 package_one_hundred.merge_package(package_two_hundred);
889 fn test_package_untractable_merge_to() {
890 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
891 let secp_ctx = Secp256k1::new();
892 let revk_outp = dumb_revk_output!(secp_ctx);
893 let htlc_outp = dumb_htlc_output!();
895 let mut untractable_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
896 let malleable_package = PackageTemplate::build_package(txid, 1, htlc_outp.clone(), 1000, true, 100);
897 untractable_package.merge_package(malleable_package);
902 fn test_package_untractable_merge_from() {
903 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
904 let secp_ctx = Secp256k1::new();
905 let htlc_outp = dumb_htlc_output!();
906 let revk_outp = dumb_revk_output!(secp_ctx);
908 let mut malleable_package = PackageTemplate::build_package(txid, 0, htlc_outp.clone(), 1000, true, 100);
909 let untractable_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 100);
910 malleable_package.merge_package(untractable_package);
915 fn test_package_noaggregation_to() {
916 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
917 let secp_ctx = Secp256k1::new();
918 let revk_outp = dumb_revk_output!(secp_ctx);
920 let mut noaggregation_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, false, 100);
921 let aggregation_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 100);
922 noaggregation_package.merge_package(aggregation_package);
927 fn test_package_noaggregation_from() {
928 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
929 let secp_ctx = Secp256k1::new();
930 let revk_outp = dumb_revk_output!(secp_ctx);
932 let mut aggregation_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
933 let noaggregation_package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, false, 100);
934 aggregation_package.merge_package(noaggregation_package);
939 fn test_package_empty() {
940 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
941 let secp_ctx = Secp256k1::new();
942 let revk_outp = dumb_revk_output!(secp_ctx);
944 let mut empty_package = PackageTemplate::build_package(txid, 0, revk_outp.clone(), 1000, true, 100);
945 empty_package.inputs = vec![];
946 let package = PackageTemplate::build_package(txid, 1, revk_outp.clone(), 1000, true, 100);
947 empty_package.merge_package(package);
952 fn test_package_differing_categories() {
953 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
954 let secp_ctx = Secp256k1::new();
955 let revk_outp = dumb_revk_output!(secp_ctx);
956 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 0);
958 let mut revoked_package = PackageTemplate::build_package(txid, 0, revk_outp, 1000, true, 100);
959 let counterparty_package = PackageTemplate::build_package(txid, 1, counterparty_outp, 1000, true, 100);
960 revoked_package.merge_package(counterparty_package);
964 fn test_package_split_malleable() {
965 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
966 let secp_ctx = Secp256k1::new();
967 let revk_outp_one = dumb_revk_output!(secp_ctx);
968 let revk_outp_two = dumb_revk_output!(secp_ctx);
969 let revk_outp_three = dumb_revk_output!(secp_ctx);
971 let mut package_one = PackageTemplate::build_package(txid, 0, revk_outp_one, 1000, true, 100);
972 let package_two = PackageTemplate::build_package(txid, 1, revk_outp_two, 1000, true, 100);
973 let package_three = PackageTemplate::build_package(txid, 2, revk_outp_three, 1000, true, 100);
975 package_one.merge_package(package_two);
976 package_one.merge_package(package_three);
977 assert_eq!(package_one.outpoints().len(), 3);
979 if let Some(split_package) = package_one.split_package(&BitcoinOutPoint { txid, vout: 1 }) {
980 // Packages attributes should be identical
981 assert!(split_package.is_malleable());
982 assert_eq!(split_package.soonest_conf_deadline, package_one.soonest_conf_deadline);
983 assert_eq!(split_package.aggregable, package_one.aggregable);
984 assert_eq!(split_package.feerate_previous, package_one.feerate_previous);
985 assert_eq!(split_package.height_timer, package_one.height_timer);
986 assert_eq!(split_package.height_original, package_one.height_original);
988 assert_eq!(package_one.outpoints().len(), 2);
992 fn test_package_split_untractable() {
993 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
994 let htlc_outp_one = dumb_htlc_output!();
996 let mut package_one = PackageTemplate::build_package(txid, 0, htlc_outp_one, 1000, true, 100);
997 let ret_split = package_one.split_package(&BitcoinOutPoint { txid, vout: 0});
998 assert!(ret_split.is_none());
1002 fn test_package_timer() {
1003 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1004 let secp_ctx = Secp256k1::new();
1005 let revk_outp = dumb_revk_output!(secp_ctx);
1007 let mut package = PackageTemplate::build_package(txid, 0, revk_outp, 1000, true, 100);
1008 let timer_none = package.timer();
1009 assert!(timer_none.is_none());
1010 package.set_timer(Some(100));
1011 if let Some(timer_some) = package.timer() {
1012 assert_eq!(timer_some, 100);
1017 fn test_package_amounts() {
1018 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1019 let secp_ctx = Secp256k1::new();
1020 let counterparty_outp = dumb_counterparty_output!(secp_ctx, 1_000_000);
1022 let package = PackageTemplate::build_package(txid, 0, counterparty_outp, 1000, true, 100);
1023 assert_eq!(package.package_amount(), 1000);
1027 fn test_package_weight() {
1028 let txid = Txid::from_hex("c2d4449afa8d26140898dd54d3390b057ba2a5afcf03ba29d7dc0d8b9ffe966e").unwrap();
1029 let secp_ctx = Secp256k1::new();
1030 let revk_outp = dumb_revk_output!(secp_ctx);
1032 let package = PackageTemplate::build_package(txid, 0, revk_outp, 0, true, 100);
1033 // (nVersion (4) + nLocktime (4) + count_tx_in (1) + prevout (36) + sequence (4) + script_length (1) + count_tx_out (1) + value (8) + var_int (1)) * WITNESS_SCALE_FACTOR
1034 // + witness marker (2) + WEIGHT_REVOKED_OUTPUT
1035 assert_eq!(package.package_weight(&Script::new()), (4 + 4 + 1 + 36 + 4 + 1 + 1 + 8 + 1) * WITNESS_SCALE_FACTOR + 2 + WEIGHT_REVOKED_OUTPUT as usize);