1 //! The logic to build claims and bump in-flight transactions until confirmations.
3 //! OnchainTxHandler objetcs are fully-part of ChannelMonitor and encapsulates all
4 //! building, tracking, bumping and notifications functions.
6 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, SigHashType};
7 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
8 use bitcoin::blockdata::script::Script;
9 use bitcoin::util::bip143;
11 use bitcoin::hash_types::Txid;
13 use bitcoin::secp256k1::{Secp256k1, Signature};
14 use bitcoin::secp256k1;
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::msgs::DecodeError;
18 use ln::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER, InputMaterial, ClaimRequest};
19 use ln::channelmanager::PaymentPreimage;
20 use ln::chan_utils::{HTLCType, LocalCommitmentTransaction, HTLCOutputInCommitment};
21 use chain::chaininterface::{FeeEstimator, BroadcasterInterface, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
22 use chain::keysinterface::ChannelKeys;
23 use util::logger::Logger;
24 use util::ser::{Readable, Writer, Writeable};
27 use std::collections::{HashMap, hash_map};
31 const MAX_ALLOC_SIZE: usize = 64*1024;
33 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
34 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
35 #[derive(Clone, PartialEq)]
37 /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
38 /// bump-txn candidate buffer.
42 /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a remote party tx.
43 /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
44 /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
46 outpoint: BitcoinOutPoint,
47 input_material: InputMaterial,
51 /// Cache remote basepoint to compute any transaction on
52 /// remote outputs, either justice or preimage/timeout transactions.
53 struct RemoteTxCache {
54 remote_delayed_payment_base_key: PublicKey,
55 remote_htlc_base_key: PublicKey,
56 per_htlc: HashMap<Sha256dHash, Vec<(HTLCOutputInCommitment)>>
59 /// Higher-level cache structure needed to re-generate bumped claim txn if needed
60 #[derive(Clone, PartialEq)]
61 pub struct ClaimTxBumpMaterial {
62 // At every block tick, used to check if pending claiming tx is taking too
63 // much time for confirmation and we need to bump it.
64 height_timer: Option<u32>,
65 // Tracked in case of reorg to wipe out now-superflous bump material
66 feerate_previous: u64,
67 // Soonest timelocks among set of outpoints claimed, used to compute
68 // a priority of not feerate
69 soonest_timelock: u32,
70 // Cache of script, pubkey, sig or key to solve claimable outputs scriptpubkey.
71 per_input_material: HashMap<BitcoinOutPoint, InputMaterial>,
74 impl Writeable for ClaimTxBumpMaterial {
75 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
76 self.height_timer.write(writer)?;
77 writer.write_all(&byte_utils::be64_to_array(self.feerate_previous))?;
78 writer.write_all(&byte_utils::be32_to_array(self.soonest_timelock))?;
79 writer.write_all(&byte_utils::be64_to_array(self.per_input_material.len() as u64))?;
80 for (outp, tx_material) in self.per_input_material.iter() {
82 tx_material.write(writer)?;
88 impl Readable for ClaimTxBumpMaterial {
89 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
90 let height_timer = Readable::read(reader)?;
91 let feerate_previous = Readable::read(reader)?;
92 let soonest_timelock = Readable::read(reader)?;
93 let per_input_material_len: u64 = Readable::read(reader)?;
94 let mut per_input_material = HashMap::with_capacity(cmp::min(per_input_material_len as usize, MAX_ALLOC_SIZE / 128));
95 for _ in 0 ..per_input_material_len {
96 let outpoint = Readable::read(reader)?;
97 let input_material = Readable::read(reader)?;
98 per_input_material.insert(outpoint, input_material);
100 Ok(Self { height_timer, feerate_previous, soonest_timelock, per_input_material })
105 pub(super) enum InputDescriptors {
110 RevokedOutput, // either a revoked to_local output on commitment tx, a revoked HTLC-Timeout output or a revoked HTLC-Success output
113 macro_rules! subtract_high_prio_fee {
114 ($logger: ident, $fee_estimator: expr, $value: expr, $predicted_weight: expr, $used_feerate: expr) => {
116 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority);
117 let mut fee = $used_feerate * ($predicted_weight as u64) / 1000;
119 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
120 fee = $used_feerate * ($predicted_weight as u64) / 1000;
122 $used_feerate = $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::Background);
123 fee = $used_feerate * ($predicted_weight as u64) / 1000;
125 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)",
129 log_warn!($logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
135 log_warn!($logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
148 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
149 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
150 match Readable::read(reader)? {
153 let vlen: u64 = Readable::read(reader)?;
154 let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::std::mem::size_of::<Option<(usize, Signature)>>()));
156 ret.push(match Readable::read(reader)? {
158 1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
159 _ => return Err(DecodeError::InvalidValue)
164 _ => Err(DecodeError::InvalidValue),
169 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
170 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
174 (vec.len() as u64).write(writer)?;
175 for opt in vec.iter() {
177 &Some((ref idx, ref sig)) => {
179 (*idx as u64).write(writer)?;
182 &None => 0u8.write(writer)?,
186 &None => 0u8.write(writer)?,
193 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
194 /// do RBF bumping if possible.
195 pub struct OnchainTxHandler<ChanSigner: ChannelKeys> {
196 destination_script: Script,
197 local_commitment: Option<LocalCommitmentTransaction>,
198 // local_htlc_sigs and prev_local_htlc_sigs are in the order as they appear in the commitment
199 // transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
200 // the set of HTLCs in the LocalCommitmentTransaction (including those which do not appear in
201 // the commitment transaction).
202 local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
203 prev_local_commitment: Option<LocalCommitmentTransaction>,
204 prev_local_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
206 remote_tx_cache: RemoteTxCache,
209 key_storage: ChanSigner,
211 // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
212 // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
213 // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
214 // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
215 // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
216 // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
217 // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
218 // we need to regenerate new claim request with reduced set of still-claimable outpoints.
219 // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
220 // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
221 // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
222 #[cfg(test)] // Used in functional_test to verify sanitization
223 pub pending_claim_requests: HashMap<Txid, ClaimTxBumpMaterial>,
225 pending_claim_requests: HashMap<Txid, ClaimTxBumpMaterial>,
227 // Used to link outpoints claimed in a connected block to a pending claim request.
228 // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
229 // Value is (pending claim request identifier, confirmation_block), identifier
230 // is txid of the initial claiming transaction and is immutable until outpoint is
231 // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
232 // block with output gets disconnected.
233 #[cfg(test)] // Used in functional_test to verify sanitization
234 pub claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
236 claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
238 onchain_events_waiting_threshold_conf: HashMap<u32, Vec<OnchainEvent>>,
240 secp_ctx: Secp256k1<secp256k1::All>,
243 impl<ChanSigner: ChannelKeys + Writeable> OnchainTxHandler<ChanSigner> {
244 pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
245 self.destination_script.write(writer)?;
246 self.local_commitment.write(writer)?;
247 self.local_htlc_sigs.write(writer)?;
248 self.prev_local_commitment.write(writer)?;
249 self.prev_local_htlc_sigs.write(writer)?;
251 self.local_csv.write(writer)?;
253 self.remote_tx_cache.remote_delayed_payment_base_key.write(writer)?;
254 self.remote_tx_cache.remote_htlc_base_key.write(writer)?;
255 writer.write_all(&byte_utils::be64_to_array(self.remote_tx_cache.per_htlc.len() as u64))?;
256 for (ref txid, ref htlcs) in self.remote_tx_cache.per_htlc.iter() {
257 writer.write_all(&txid[..])?;
258 writer.write_all(&byte_utils::be64_to_array(htlcs.len() as u64))?;
259 for &ref htlc in htlcs.iter() {
263 self.remote_csv.write(writer)?;
265 self.key_storage.write(writer)?;
267 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
268 for (ref ancestor_claim_txid, claim_tx_data) in self.pending_claim_requests.iter() {
269 ancestor_claim_txid.write(writer)?;
270 claim_tx_data.write(writer)?;
273 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
274 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
276 claim_and_height.0.write(writer)?;
277 claim_and_height.1.write(writer)?;
280 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_waiting_threshold_conf.len() as u64))?;
281 for (ref target, ref events) in self.onchain_events_waiting_threshold_conf.iter() {
282 writer.write_all(&byte_utils::be32_to_array(**target))?;
283 writer.write_all(&byte_utils::be64_to_array(events.len() as u64))?;
284 for ev in events.iter() {
286 OnchainEvent::Claim { ref claim_request } => {
287 writer.write_all(&[0; 1])?;
288 claim_request.write(writer)?;
290 OnchainEvent::ContentiousOutpoint { ref outpoint, ref input_material } => {
291 writer.write_all(&[1; 1])?;
292 outpoint.write(writer)?;
293 input_material.write(writer)?;
302 impl<ChanSigner: ChannelKeys + Readable> Readable for OnchainTxHandler<ChanSigner> {
303 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
304 let destination_script = Readable::read(reader)?;
306 let local_commitment = Readable::read(reader)?;
307 let local_htlc_sigs = Readable::read(reader)?;
308 let prev_local_commitment = Readable::read(reader)?;
309 let prev_local_htlc_sigs = Readable::read(reader)?;
311 let local_csv = Readable::read(reader)?;
313 let remote_tx_cache = {
314 let remote_delayed_payment_base_key = Readable::read(reader)?;
315 let remote_htlc_base_key = Readable::read(reader)?;
316 let per_htlc_len: u64 = Readable::read(reader)?;
317 let mut per_htlc = HashMap::with_capacity(cmp::min(per_htlc_len as usize, MAX_ALLOC_SIZE / 64));
318 for _ in 0..per_htlc_len {
319 let txid: Sha256dHash = Readable::read(reader)?;
320 let htlcs_count: u64 = Readable::read(reader)?;
321 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
322 for _ in 0..htlcs_count {
323 let htlc = Readable::read(reader)?;
326 if let Some(_) = per_htlc.insert(txid, htlcs) {
327 return Err(DecodeError::InvalidValue);
331 remote_delayed_payment_base_key,
332 remote_htlc_base_key,
336 let remote_csv = Readable::read(reader)?;
338 let key_storage = Readable::read(reader)?;
340 let pending_claim_requests_len: u64 = Readable::read(reader)?;
341 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
342 for _ in 0..pending_claim_requests_len {
343 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
346 let claimable_outpoints_len: u64 = Readable::read(reader)?;
347 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
348 for _ in 0..claimable_outpoints_len {
349 let outpoint = Readable::read(reader)?;
350 let ancestor_claim_txid = Readable::read(reader)?;
351 let height = Readable::read(reader)?;
352 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
354 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
355 let mut onchain_events_waiting_threshold_conf = HashMap::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
356 for _ in 0..waiting_threshold_conf_len {
357 let height_target = Readable::read(reader)?;
358 let events_len: u64 = Readable::read(reader)?;
359 let mut events = Vec::with_capacity(cmp::min(events_len as usize, MAX_ALLOC_SIZE / 128));
360 for _ in 0..events_len {
361 let ev = match <u8 as Readable>::read(reader)? {
363 let claim_request = Readable::read(reader)?;
364 OnchainEvent::Claim {
369 let outpoint = Readable::read(reader)?;
370 let input_material = Readable::read(reader)?;
371 OnchainEvent::ContentiousOutpoint {
376 _ => return Err(DecodeError::InvalidValue),
380 onchain_events_waiting_threshold_conf.insert(height_target, events);
383 Ok(OnchainTxHandler {
387 prev_local_commitment,
388 prev_local_htlc_sigs,
394 pending_claim_requests,
395 onchain_events_waiting_threshold_conf,
396 secp_ctx: Secp256k1::new(),
401 impl<ChanSigner: ChannelKeys> OnchainTxHandler<ChanSigner> {
402 pub(super) fn new(destination_script: Script, keys: ChanSigner, local_csv: u16, remote_delayed_payment_base_key: PublicKey, remote_htlc_base_key: PublicKey, remote_csv: u16) -> Self {
404 let key_storage = keys;
406 let remote_tx_cache = RemoteTxCache {
407 remote_delayed_payment_base_key,
408 remote_htlc_base_key,
409 per_htlc: HashMap::new(),
414 local_commitment: None,
415 local_htlc_sigs: None,
416 prev_local_commitment: None,
417 prev_local_htlc_sigs: None,
422 pending_claim_requests: HashMap::new(),
423 claimable_outpoints: HashMap::new(),
424 onchain_events_waiting_threshold_conf: HashMap::new(),
426 secp_ctx: Secp256k1::new(),
430 pub(super) fn get_witnesses_weight(inputs: &[InputDescriptors]) -> usize {
431 let mut tx_weight = 2; // count segwit flags
433 // We use expected weight (and not actual) as signatures and time lock delays may vary
434 tx_weight += match inp {
435 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
436 &InputDescriptors::RevokedOfferedHTLC => {
437 1 + 1 + 73 + 1 + 33 + 1 + 133
439 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
440 &InputDescriptors::RevokedReceivedHTLC => {
441 1 + 1 + 73 + 1 + 33 + 1 + 139
443 // number_of_witness_elements + sig_length + remotehtlc_sig + preimage_length + preimage + witness_script_length + witness_script
444 &InputDescriptors::OfferedHTLC => {
445 1 + 1 + 73 + 1 + 32 + 1 + 133
447 // number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
448 &InputDescriptors::ReceivedHTLC => {
449 1 + 1 + 73 + 1 + 1 + 1 + 139
451 // number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
452 &InputDescriptors::RevokedOutput => {
453 1 + 1 + 73 + 1 + 1 + 1 + 77
460 /// In LN, output claimed are time-sensitive, which means we have to spend them before reaching some timelock expiration. At in-channel
461 /// 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
462 /// height than once reached we should generate a new bumped "version" of the claim tx to be sure than we safely claim outputs before
463 /// than our counterparty can do it too. If timelock expires soon, height timer is going to be scale down in consequence to increase
464 /// frequency of the bump and so increase our bets of success.
465 fn get_height_timer(current_height: u32, timelock_expiration: u32) -> u32 {
466 if timelock_expiration <= current_height + 3 {
467 return current_height + 1
468 } else if timelock_expiration - current_height <= 15 {
469 return current_height + 3
474 /// 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
475 /// (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.
476 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)>
477 where F::Target: FeeEstimator,
480 if cached_claim_datas.per_input_material.len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
481 let mut inputs = Vec::new();
482 for outp in cached_claim_datas.per_input_material.keys() {
483 log_trace!(logger, "Outpoint {}:{}", outp.txid, outp.vout);
485 previous_output: *outp,
486 script_sig: Script::new(),
487 sequence: 0xfffffffd,
491 let mut bumped_tx = Transaction {
496 script_pubkey: self.destination_script.clone(),
501 macro_rules! RBF_bump {
502 ($amount: expr, $old_feerate: expr, $fee_estimator: expr, $predicted_weight: expr) => {
504 let mut used_feerate;
505 // If old feerate inferior to actual one given back by Fee Estimator, use it to compute new fee...
506 let new_fee = if $old_feerate < $fee_estimator.get_est_sat_per_1000_weight(ConfirmationTarget::HighPriority) {
507 let mut value = $amount;
508 if subtract_high_prio_fee!(logger, $fee_estimator, value, $predicted_weight, used_feerate) {
509 // Overflow check is done in subtract_high_prio_fee
512 log_trace!(logger, "Can't new-estimation bump new claiming tx, amount {} is too small", $amount);
515 // ...else just increase the previous feerate by 25% (because that's a nice number)
517 let fee = $old_feerate * $predicted_weight / 750;
519 log_trace!(logger, "Can't 25% bump new claiming tx, amount {} is too small", $amount);
525 let previous_fee = $old_feerate * $predicted_weight / 1000;
526 let min_relay_fee = MIN_RELAY_FEE_SAT_PER_1000_WEIGHT * $predicted_weight / 1000;
527 // BIP 125 Opt-in Full Replace-by-Fee Signaling
528 // * 3. The replacement transaction pays an absolute fee of at least the sum paid by the original transactions.
529 // * 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.
530 let new_fee = if new_fee < previous_fee + min_relay_fee {
531 new_fee + previous_fee + min_relay_fee - new_fee
535 Some((new_fee, new_fee * 1000 / $predicted_weight))
540 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
541 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
542 let new_timer = Some(Self::get_height_timer(height, cached_claim_datas.soonest_timelock));
543 let mut inputs_witnesses_weight = 0;
545 let mut dynamic_fee = true;
546 for per_outp_material in cached_claim_datas.per_input_material.values() {
547 match per_outp_material {
548 &InputMaterial::Revoked { ref witness_script, ref is_htlc, ref amount, .. } => {
549 inputs_witnesses_weight += Self::get_witnesses_weight(if !is_htlc { &[InputDescriptors::RevokedOutput] } else if HTLCType::scriptlen_to_htlctype(witness_script.len()) == Some(HTLCType::OfferedHTLC) { &[InputDescriptors::RevokedOfferedHTLC] } else if HTLCType::scriptlen_to_htlctype(witness_script.len()) == Some(HTLCType::AcceptedHTLC) { &[InputDescriptors::RevokedReceivedHTLC] } else { unreachable!() });
552 &InputMaterial::RemoteHTLC { ref preimage, ref amount, .. } => {
553 inputs_witnesses_weight += Self::get_witnesses_weight(if preimage.is_some() { &[InputDescriptors::OfferedHTLC] } else { &[InputDescriptors::ReceivedHTLC] });
556 &InputMaterial::LocalHTLC { .. } => {
559 &InputMaterial::Funding { .. } => {
565 let predicted_weight = bumped_tx.get_weight() + inputs_witnesses_weight;
567 // If old feerate is 0, first iteration of this claim, use normal fee calculation
568 if cached_claim_datas.feerate_previous != 0 {
569 if let Some((new_fee, feerate)) = RBF_bump!(amt, cached_claim_datas.feerate_previous, fee_estimator, predicted_weight as u64) {
570 // If new computed fee is superior at the whole claimable amount burn all in fees
572 bumped_tx.output[0].value = 0;
574 bumped_tx.output[0].value = amt - new_fee;
576 new_feerate = feerate;
577 } else { return None; }
579 if subtract_high_prio_fee!(logger, fee_estimator, amt, predicted_weight, new_feerate) {
580 bumped_tx.output[0].value = amt;
581 } else { return None; }
583 assert!(new_feerate != 0);
585 for (i, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
586 match per_outp_material {
587 &InputMaterial::Revoked { ref witness_script, ref pubkey, ref key, ref is_htlc, ref amount } => {
588 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
589 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &witness_script, *amount)[..]);
590 let sig = self.secp_ctx.sign(&sighash, &key);
591 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
592 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
594 bumped_tx.input[i].witness.push(pubkey.unwrap().clone().serialize().to_vec());
596 bumped_tx.input[i].witness.push(vec!(1));
598 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
599 log_trace!(logger, "Going to broadcast Penalty Transaction {} claiming revoked {} output {} from {} with new feerate {}...", bumped_tx.txid(), if !is_htlc { "to_local" } else if HTLCType::scriptlen_to_htlctype(witness_script.len()) == Some(HTLCType::OfferedHTLC) { "offered" } else if HTLCType::scriptlen_to_htlctype(witness_script.len()) == Some(HTLCType::AcceptedHTLC) { "received" } else { "" }, outp.vout, outp.txid, new_feerate);
601 &InputMaterial::RemoteHTLC { ref witness_script, ref key, ref preimage, ref amount, ref locktime } => {
602 if !preimage.is_some() { bumped_tx.lock_time = *locktime }; // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
603 let sighash_parts = bip143::SighashComponents::new(&bumped_tx);
604 let sighash = hash_to_message!(&sighash_parts.sighash_all(&bumped_tx.input[i], &witness_script, *amount)[..]);
605 let sig = self.secp_ctx.sign(&sighash, &key);
606 bumped_tx.input[i].witness.push(sig.serialize_der().to_vec());
607 bumped_tx.input[i].witness[0].push(SigHashType::All as u8);
608 if let &Some(preimage) = preimage {
609 bumped_tx.input[i].witness.push(preimage.clone().0.to_vec());
611 bumped_tx.input[i].witness.push(vec![]);
613 bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
614 log_trace!(logger, "Going to broadcast Claim Transaction {} claiming remote {} htlc output {} from {} with new feerate {}...", bumped_tx.txid(), if preimage.is_some() { "offered" } else { "received" }, outp.vout, outp.txid, new_feerate);
619 log_trace!(logger, "...with timer {}", new_timer.unwrap());
620 assert!(predicted_weight >= bumped_tx.get_weight());
621 return Some((new_timer, new_feerate, bumped_tx))
623 for (_, (outp, per_outp_material)) in cached_claim_datas.per_input_material.iter().enumerate() {
624 match per_outp_material {
625 &InputMaterial::LocalHTLC { ref preimage, ref amount } => {
626 let htlc_tx = self.get_fully_signed_htlc_tx(outp, preimage);
627 if let Some(htlc_tx) = htlc_tx {
628 let feerate = (amount - htlc_tx.output[0].value) * 1000 / htlc_tx.get_weight() as u64;
629 // Timer set to $NEVER given we can't bump tx without anchor outputs
630 log_trace!(logger, "Going to broadcast Local HTLC-{} claiming HTLC output {} from {}...", if preimage.is_some() { "Success" } else { "Timeout" }, outp.vout, outp.txid);
631 return Some((None, feerate, htlc_tx));
635 &InputMaterial::Funding { ref funding_redeemscript } => {
636 let signed_tx = self.get_fully_signed_local_tx(funding_redeemscript).unwrap();
637 // Timer set to $NEVER given we can't bump tx without anchor outputs
638 log_trace!(logger, "Going to broadcast Local Transaction {} claiming funding output {} from {}...", signed_tx.txid(), outp.vout, outp.txid);
639 return Some((None, self.local_commitment.as_ref().unwrap().feerate_per_kw, signed_tx));
648 pub(super) fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], claimable_outpoints: Vec<ClaimRequest>, height: u32, broadcaster: B, fee_estimator: F, logger: L)
649 where B::Target: BroadcasterInterface,
650 F::Target: FeeEstimator,
653 log_trace!(logger, "Block at height {} connected with {} claim requests", height, claimable_outpoints.len());
654 let mut new_claims = Vec::new();
655 let mut aggregated_claim = HashMap::new();
656 let mut aggregated_soonest = ::std::u32::MAX;
658 // Try to aggregate outputs if their timelock expiration isn't imminent (absolute_timelock
659 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
660 for req in claimable_outpoints {
661 // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
662 if let Some(_) = self.claimable_outpoints.get(&req.outpoint) { log_trace!(logger, "Bouncing off outpoint {}:{}, already registered its claiming request", req.outpoint.txid, req.outpoint.vout); } else {
663 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.absolute_timelock, height + CLTV_SHARED_CLAIM_BUFFER);
664 if req.absolute_timelock <= height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable { // Don't aggregate if outpoint absolute timelock is soon or marked as non-aggregable
665 let mut single_input = HashMap::new();
666 single_input.insert(req.outpoint, req.witness_data);
667 new_claims.push((req.absolute_timelock, single_input));
669 aggregated_claim.insert(req.outpoint, req.witness_data);
670 if req.absolute_timelock < aggregated_soonest {
671 aggregated_soonest = req.absolute_timelock;
676 new_claims.push((aggregated_soonest, aggregated_claim));
678 // Generate claim transactions and track them to bump if necessary at
679 // height timer expiration (i.e in how many blocks we're going to take action).
680 for (soonest_timelock, claim) in new_claims.drain(..) {
681 let mut claim_material = ClaimTxBumpMaterial { height_timer: None, feerate_previous: 0, soonest_timelock, per_input_material: claim };
682 if let Some((new_timer, new_feerate, tx)) = self.generate_claim_tx(height, &claim_material, &*fee_estimator, &*logger) {
683 claim_material.height_timer = new_timer;
684 claim_material.feerate_previous = new_feerate;
685 let txid = tx.txid();
686 for k in claim_material.per_input_material.keys() {
687 log_trace!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
688 self.claimable_outpoints.insert(k.clone(), (txid, height));
690 self.pending_claim_requests.insert(txid, claim_material);
691 log_trace!(logger, "Broadcast onchain {}", log_tx!(tx));
692 broadcaster.broadcast_transaction(&tx);
696 let mut bump_candidates = HashMap::new();
697 for tx in txn_matched {
698 // Scan all input to verify is one of the outpoint spent is of interest for us
699 let mut claimed_outputs_material = Vec::new();
700 for inp in &tx.input {
701 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
702 // If outpoint has claim request pending on it...
703 if let Some(claim_material) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
704 //... we need to verify equality between transaction outpoints and claim request
705 // outpoints to know if transaction is the original claim or a bumped one issued
707 let mut set_equality = true;
708 if claim_material.per_input_material.len() != tx.input.len() {
709 set_equality = false;
711 for (claim_inp, tx_inp) in claim_material.per_input_material.keys().zip(tx.input.iter()) {
712 if *claim_inp != tx_inp.previous_output {
713 set_equality = false;
718 macro_rules! clean_claim_request_after_safety_delay {
720 let new_event = OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() };
721 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
722 hash_map::Entry::Occupied(mut entry) => {
723 if !entry.get().contains(&new_event) {
724 entry.get_mut().push(new_event);
727 hash_map::Entry::Vacant(entry) => {
728 entry.insert(vec![new_event]);
734 // If this is our transaction (or our counterparty spent all the outputs
735 // before we could anyway with same inputs order than us), wait for
736 // ANTI_REORG_DELAY and clean the RBF tracking map.
738 clean_claim_request_after_safety_delay!();
739 } else { // If false, generate new claim request with update outpoint set
740 let mut at_least_one_drop = false;
741 for input in tx.input.iter() {
742 if let Some(input_material) = claim_material.per_input_material.remove(&input.previous_output) {
743 claimed_outputs_material.push((input.previous_output, input_material));
744 at_least_one_drop = true;
746 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
747 if claim_material.per_input_material.is_empty() {
748 clean_claim_request_after_safety_delay!();
751 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
752 if at_least_one_drop {
753 bump_candidates.insert(first_claim_txid_height.0.clone(), claim_material.clone());
756 break; //No need to iterate further, either tx is our or their
758 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
762 for (outpoint, input_material) in claimed_outputs_material.drain(..) {
763 let new_event = OnchainEvent::ContentiousOutpoint { outpoint, input_material };
764 match self.onchain_events_waiting_threshold_conf.entry(height + ANTI_REORG_DELAY - 1) {
765 hash_map::Entry::Occupied(mut entry) => {
766 if !entry.get().contains(&new_event) {
767 entry.get_mut().push(new_event);
770 hash_map::Entry::Vacant(entry) => {
771 entry.insert(vec![new_event]);
777 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
778 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&height) {
781 OnchainEvent::Claim { claim_request } => {
782 // We may remove a whole set of claim outpoints here, as these one may have
783 // been aggregated in a single tx and claimed so atomically
784 if let Some(bump_material) = self.pending_claim_requests.remove(&claim_request) {
785 for outpoint in bump_material.per_input_material.keys() {
786 self.claimable_outpoints.remove(&outpoint);
790 OnchainEvent::ContentiousOutpoint { outpoint, .. } => {
791 self.claimable_outpoints.remove(&outpoint);
797 // Check if any pending claim request must be rescheduled
798 for (first_claim_txid, ref claim_data) in self.pending_claim_requests.iter() {
799 if let Some(h) = claim_data.height_timer {
801 bump_candidates.insert(*first_claim_txid, (*claim_data).clone());
806 // Build, bump and rebroadcast tx accordingly
807 log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
808 for (first_claim_txid, claim_material) in bump_candidates.iter() {
809 if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &claim_material, &*fee_estimator, &*logger) {
810 log_trace!(logger, "Broadcast onchain {}", log_tx!(bump_tx));
811 broadcaster.broadcast_transaction(&bump_tx);
812 if let Some(claim_material) = self.pending_claim_requests.get_mut(first_claim_txid) {
813 claim_material.height_timer = new_timer;
814 claim_material.feerate_previous = new_feerate;
820 pub(super) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: F, logger: L)
821 where B::Target: BroadcasterInterface,
822 F::Target: FeeEstimator,
825 let mut bump_candidates = HashMap::new();
826 if let Some(events) = self.onchain_events_waiting_threshold_conf.remove(&(height + ANTI_REORG_DELAY - 1)) {
827 //- our claim tx on a commitment tx output
828 //- resurect outpoint back in its claimable set and regenerate tx
831 OnchainEvent::ContentiousOutpoint { outpoint, input_material } => {
832 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&outpoint) {
833 if let Some(claim_material) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
834 claim_material.per_input_material.insert(outpoint, input_material);
835 // Using a HashMap guarantee us than if we have multiple outpoints getting
836 // resurrected only one bump claim tx is going to be broadcast
837 bump_candidates.insert(ancestor_claimable_txid.clone(), claim_material.clone());
845 for (_, claim_material) in bump_candidates.iter_mut() {
846 if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &claim_material, &*fee_estimator, &*logger) {
847 claim_material.height_timer = new_timer;
848 claim_material.feerate_previous = new_feerate;
849 broadcaster.broadcast_transaction(&bump_tx);
852 for (ancestor_claim_txid, claim_material) in bump_candidates.drain() {
853 self.pending_claim_requests.insert(ancestor_claim_txid.0, claim_material);
855 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
856 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
857 let mut remove_request = Vec::new();
858 self.claimable_outpoints.retain(|_, ref v|
860 remove_request.push(v.0.clone());
863 for req in remove_request {
864 self.pending_claim_requests.remove(&req);
868 pub(super) fn provide_latest_local_tx(&mut self, tx: LocalCommitmentTransaction) -> Result<(), ()> {
869 // To prevent any unsafe state discrepancy between offchain and onchain, once local
870 // commitment transaction has been signed due to an event (either block height for
871 // HTLC-timeout or channel force-closure), don't allow any further update of local
872 // commitment transaction view to avoid delivery of revocation secret to counterparty
873 // for the aformentionned signed transaction.
874 if self.local_htlc_sigs.is_some() || self.prev_local_htlc_sigs.is_some() {
877 self.prev_local_commitment = self.local_commitment.take();
878 self.local_commitment = Some(tx);
882 fn sign_latest_local_htlcs(&mut self) {
883 if let Some(ref local_commitment) = self.local_commitment {
884 if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, self.local_csv, &self.secp_ctx) {
885 self.local_htlc_sigs = Some(Vec::new());
886 let ret = self.local_htlc_sigs.as_mut().unwrap();
887 for (htlc_idx, (local_sig, &(ref htlc, _))) in sigs.iter().zip(local_commitment.per_htlc.iter()).enumerate() {
888 if let Some(tx_idx) = htlc.transaction_output_index {
889 if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
890 ret[tx_idx as usize] = Some((htlc_idx, local_sig.expect("Did not receive a signature for a non-dust HTLC")));
892 assert!(local_sig.is_none(), "Received a signature for a dust HTLC");
898 fn sign_prev_local_htlcs(&mut self) {
899 if let Some(ref local_commitment) = self.prev_local_commitment {
900 if let Ok(sigs) = self.key_storage.sign_local_commitment_htlc_transactions(local_commitment, self.local_csv, &self.secp_ctx) {
901 self.prev_local_htlc_sigs = Some(Vec::new());
902 let ret = self.prev_local_htlc_sigs.as_mut().unwrap();
903 for (htlc_idx, (local_sig, &(ref htlc, _))) in sigs.iter().zip(local_commitment.per_htlc.iter()).enumerate() {
904 if let Some(tx_idx) = htlc.transaction_output_index {
905 if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
906 ret[tx_idx as usize] = Some((htlc_idx, local_sig.expect("Did not receive a signature for a non-dust HTLC")));
908 assert!(local_sig.is_none(), "Received a signature for a dust HTLC");
915 //TODO: getting lastest local transactions should be infaillible and result in us "force-closing the channel", but we may
916 // have empty local commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
917 // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
918 // to monitor before.
919 pub(super) fn get_fully_signed_local_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
920 if let Some(ref mut local_commitment) = self.local_commitment {
921 match self.key_storage.sign_local_commitment(local_commitment, &self.secp_ctx) {
922 Ok(sig) => Some(local_commitment.add_local_sig(funding_redeemscript, sig)),
923 Err(_) => return None,
930 pub(super) fn provide_latest_remote_tx(&mut self, commitment_txid: Sha256dHash, htlcs: Vec<HTLCOutputInCommitment>) {
931 self.remote_tx_cache.per_htlc.insert(commitment_txid, htlcs);
935 pub(super) fn get_fully_signed_copy_local_tx(&mut self, funding_redeemscript: &Script) -> Option<Transaction> {
936 if let Some(ref mut local_commitment) = self.local_commitment {
937 let local_commitment = local_commitment.clone();
938 match self.key_storage.sign_local_commitment(&local_commitment, &self.secp_ctx) {
939 Ok(sig) => Some(local_commitment.add_local_sig(funding_redeemscript, sig)),
940 Err(_) => return None,
947 pub(super) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
948 let mut htlc_tx = None;
949 if self.local_commitment.is_some() {
950 let commitment_txid = self.local_commitment.as_ref().unwrap().txid();
951 if commitment_txid == outp.txid {
952 self.sign_latest_local_htlcs();
953 if let &Some(ref htlc_sigs) = &self.local_htlc_sigs {
954 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
955 htlc_tx = Some(self.local_commitment.as_ref().unwrap()
956 .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.local_csv));
960 if self.prev_local_commitment.is_some() {
961 let commitment_txid = self.prev_local_commitment.as_ref().unwrap().txid();
962 if commitment_txid == outp.txid {
963 self.sign_prev_local_htlcs();
964 if let &Some(ref htlc_sigs) = &self.prev_local_htlc_sigs {
965 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
966 htlc_tx = Some(self.prev_local_commitment.as_ref().unwrap()
967 .get_signed_htlc_tx(*htlc_idx, htlc_sig, preimage, self.local_csv));
975 pub(super) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
976 let latest_had_sigs = self.local_htlc_sigs.is_some();
977 let prev_had_sigs = self.prev_local_htlc_sigs.is_some();
978 let ret = self.get_fully_signed_htlc_tx(outp, preimage);
979 if !latest_had_sigs {
980 self.local_htlc_sigs = None;
983 self.prev_local_htlc_sigs = None;