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 //! The logic to build claims and bump in-flight transactions until confirmations.
12 //! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
13 //! building, tracking, bumping and notifications functions.
15 use bitcoin::blockdata::transaction::Transaction;
16 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
17 use bitcoin::blockdata::script::Script;
19 use bitcoin::hash_types::Txid;
21 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
22 use bitcoin::secp256k1;
24 use crate::ln::msgs::DecodeError;
25 use crate::ln::PaymentPreimage;
27 use crate::ln::chan_utils;
28 use crate::ln::chan_utils::{ChannelTransactionParameters, HolderCommitmentTransaction};
30 use crate::chain::chaininterface::ConfirmationTarget;
31 use crate::chain::chaininterface::{FeeEstimator, BroadcasterInterface, LowerBoundedFeeEstimator};
32 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER};
33 use crate::chain::keysinterface::{Sign, KeysInterface};
35 use crate::chain::package::PackageSolvingData;
36 use crate::chain::package::PackageTemplate;
37 use crate::util::logger::Logger;
38 use crate::util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter};
39 use crate::util::byte_utils;
42 use crate::prelude::*;
43 use alloc::collections::BTreeMap;
46 use core::mem::replace;
49 use bitcoin::hashes::Hash;
51 const MAX_ALLOC_SIZE: usize = 64*1024;
53 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
54 /// transaction causing it.
56 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
57 #[derive(Clone, PartialEq, Eq)]
58 struct OnchainEventEntry {
64 impl OnchainEventEntry {
65 fn confirmation_threshold(&self) -> u32 {
66 self.height + ANTI_REORG_DELAY - 1
69 fn has_reached_confirmation_threshold(&self, height: u32) -> bool {
70 height >= self.confirmation_threshold()
74 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
75 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
76 #[derive(Clone, PartialEq, Eq)]
78 /// Outpoint under claim process by our own tx, once this one get enough confirmations, we remove it from
79 /// bump-txn candidate buffer.
83 /// Claim tx aggregate multiple claimable outpoints. One of the outpoint may be claimed by a counterparty party tx.
84 /// In this case, we need to drop the outpoint and regenerate a new claim tx. By safety, we keep tracking
85 /// the outpoint to be sure to resurect it back to the claim tx if reorgs happen.
87 package: PackageTemplate,
91 impl Writeable for OnchainEventEntry {
92 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
93 write_tlv_fields!(writer, {
94 (0, self.txid, required),
95 (2, self.height, required),
96 (4, self.event, required),
102 impl MaybeReadable for OnchainEventEntry {
103 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
104 let mut txid = Txid::all_zeros();
106 let mut event = None;
107 read_tlv_fields!(reader, {
109 (2, height, required),
110 (4, event, ignorable),
112 if let Some(ev) = event {
113 Ok(Some(Self { txid, height, event: ev }))
120 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
122 (0, claim_request, required),
124 (1, ContentiousOutpoint) => {
125 (0, package, required),
129 impl Readable for Option<Vec<Option<(usize, Signature)>>> {
130 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
131 match Readable::read(reader)? {
134 let vlen: u64 = Readable::read(reader)?;
135 let mut ret = Vec::with_capacity(cmp::min(vlen as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<Option<(usize, Signature)>>()));
137 ret.push(match Readable::read(reader)? {
139 1u8 => Some((<u64 as Readable>::read(reader)? as usize, Readable::read(reader)?)),
140 _ => return Err(DecodeError::InvalidValue)
145 _ => Err(DecodeError::InvalidValue),
150 impl Writeable for Option<Vec<Option<(usize, Signature)>>> {
151 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
155 (vec.len() as u64).write(writer)?;
156 for opt in vec.iter() {
158 &Some((ref idx, ref sig)) => {
160 (*idx as u64).write(writer)?;
163 &None => 0u8.write(writer)?,
167 &None => 0u8.write(writer)?,
173 // Represents the different types of claims for which events are yielded externally to satisfy said
176 pub(crate) enum ClaimEvent {
177 /// Event yielded to signal that the commitment transaction fee must be bumped to claim any
178 /// encumbered funds and proceed to HTLC resolution, if any HTLCs exist.
180 package_target_feerate_sat_per_1000_weight: u32,
181 commitment_tx: Transaction,
182 anchor_output_idx: u32,
186 /// Represents the different ways an output can be claimed (i.e., spent to an address under our
187 /// control) onchain.
188 pub(crate) enum OnchainClaim {
189 /// A finalized transaction pending confirmation spending the output to claim.
192 /// An event yielded externally to signal additional inputs must be added to a transaction
193 /// pending confirmation spending the output to claim.
197 /// OnchainTxHandler receives claiming requests, aggregates them if it's sound, broadcast and
198 /// do RBF bumping if possible.
200 pub struct OnchainTxHandler<ChannelSigner: Sign> {
201 destination_script: Script,
202 holder_commitment: HolderCommitmentTransaction,
203 // holder_htlc_sigs and prev_holder_htlc_sigs are in the order as they appear in the commitment
204 // transaction outputs (hence the Option<>s inside the Vec). The first usize is the index in
205 // the set of HTLCs in the HolderCommitmentTransaction.
206 holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
207 prev_holder_commitment: Option<HolderCommitmentTransaction>,
208 prev_holder_htlc_sigs: Option<Vec<Option<(usize, Signature)>>>,
210 pub(super) signer: ChannelSigner,
211 pub(crate) channel_transaction_parameters: ChannelTransactionParameters,
213 // Used to track claiming requests. If claim tx doesn't confirm before height timer expiration we need to bump
214 // it (RBF or CPFP). If an input has been part of an aggregate tx at first claim try, we need to keep it within
215 // another bumped aggregate tx to comply with RBF rules. We may have multiple claiming txn in the flight for the
216 // same set of outpoints. One of the outpoints may be spent by a transaction not issued by us. That's why at
217 // block connection we scan all inputs and if any of them is among a set of a claiming request we test for set
218 // equality between spending transaction and claim request. If true, it means transaction was one our claiming one
219 // after a security delay of 6 blocks we remove pending claim request. If false, it means transaction wasn't and
220 // we need to regenerate new claim request with reduced set of still-claimable outpoints.
221 // Key is identifier of the pending claim request, i.e the txid of the initial claiming transaction generated by
222 // us and is immutable until all outpoint of the claimable set are post-anti-reorg-delay solved.
223 // Entry is cache of elements need to generate a bumped claiming transaction (see ClaimTxBumpMaterial)
224 #[cfg(test)] // Used in functional_test to verify sanitization
225 pub(crate) pending_claim_requests: HashMap<Txid, PackageTemplate>,
227 pending_claim_requests: HashMap<Txid, PackageTemplate>,
229 pending_claim_events: HashMap<Txid, ClaimEvent>,
231 // Used to link outpoints claimed in a connected block to a pending claim request.
232 // Key is outpoint than monitor parsing has detected we have keys/scripts to claim
233 // Value is (pending claim request identifier, confirmation_block), identifier
234 // is txid of the initial claiming transaction and is immutable until outpoint is
235 // post-anti-reorg-delay solved, confirmaiton_block is used to erase entry if
236 // block with output gets disconnected.
237 #[cfg(test)] // Used in functional_test to verify sanitization
238 pub claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
240 claimable_outpoints: HashMap<BitcoinOutPoint, (Txid, u32)>,
242 locktimed_packages: BTreeMap<u32, Vec<PackageTemplate>>,
244 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
246 pub(super) secp_ctx: Secp256k1<secp256k1::All>,
249 const SERIALIZATION_VERSION: u8 = 1;
250 const MIN_SERIALIZATION_VERSION: u8 = 1;
252 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
253 pub(crate) fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
254 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
256 self.destination_script.write(writer)?;
257 self.holder_commitment.write(writer)?;
258 self.holder_htlc_sigs.write(writer)?;
259 self.prev_holder_commitment.write(writer)?;
260 self.prev_holder_htlc_sigs.write(writer)?;
262 self.channel_transaction_parameters.write(writer)?;
264 let mut key_data = VecWriter(Vec::new());
265 self.signer.write(&mut key_data)?;
266 assert!(key_data.0.len() < core::usize::MAX);
267 assert!(key_data.0.len() < core::u32::MAX as usize);
268 (key_data.0.len() as u32).write(writer)?;
269 writer.write_all(&key_data.0[..])?;
271 writer.write_all(&byte_utils::be64_to_array(self.pending_claim_requests.len() as u64))?;
272 for (ref ancestor_claim_txid, request) in self.pending_claim_requests.iter() {
273 ancestor_claim_txid.write(writer)?;
274 request.write(writer)?;
277 writer.write_all(&byte_utils::be64_to_array(self.claimable_outpoints.len() as u64))?;
278 for (ref outp, ref claim_and_height) in self.claimable_outpoints.iter() {
280 claim_and_height.0.write(writer)?;
281 claim_and_height.1.write(writer)?;
284 writer.write_all(&byte_utils::be64_to_array(self.locktimed_packages.len() as u64))?;
285 for (ref locktime, ref packages) in self.locktimed_packages.iter() {
286 locktime.write(writer)?;
287 writer.write_all(&byte_utils::be64_to_array(packages.len() as u64))?;
288 for ref package in packages.iter() {
289 package.write(writer)?;
293 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
294 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
295 entry.write(writer)?;
298 write_tlv_fields!(writer, {});
303 impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler<K::Signer> {
304 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
305 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
307 let destination_script = Readable::read(reader)?;
309 let holder_commitment = Readable::read(reader)?;
310 let holder_htlc_sigs = Readable::read(reader)?;
311 let prev_holder_commitment = Readable::read(reader)?;
312 let prev_holder_htlc_sigs = Readable::read(reader)?;
314 let channel_parameters = Readable::read(reader)?;
316 let keys_len: u32 = Readable::read(reader)?;
317 let mut keys_data = Vec::with_capacity(cmp::min(keys_len as usize, MAX_ALLOC_SIZE));
318 while keys_data.len() != keys_len as usize {
319 // Read 1KB at a time to avoid accidentally allocating 4GB on corrupted channel keys
320 let mut data = [0; 1024];
321 let read_slice = &mut data[0..cmp::min(1024, keys_len as usize - keys_data.len())];
322 reader.read_exact(read_slice)?;
323 keys_data.extend_from_slice(read_slice);
325 let signer = keys_manager.read_chan_signer(&keys_data)?;
327 let pending_claim_requests_len: u64 = Readable::read(reader)?;
328 let mut pending_claim_requests = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
329 for _ in 0..pending_claim_requests_len {
330 pending_claim_requests.insert(Readable::read(reader)?, Readable::read(reader)?);
333 let claimable_outpoints_len: u64 = Readable::read(reader)?;
334 let mut claimable_outpoints = HashMap::with_capacity(cmp::min(pending_claim_requests_len as usize, MAX_ALLOC_SIZE / 128));
335 for _ in 0..claimable_outpoints_len {
336 let outpoint = Readable::read(reader)?;
337 let ancestor_claim_txid = Readable::read(reader)?;
338 let height = Readable::read(reader)?;
339 claimable_outpoints.insert(outpoint, (ancestor_claim_txid, height));
342 let locktimed_packages_len: u64 = Readable::read(reader)?;
343 let mut locktimed_packages = BTreeMap::new();
344 for _ in 0..locktimed_packages_len {
345 let locktime = Readable::read(reader)?;
346 let packages_len: u64 = Readable::read(reader)?;
347 let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::<PackageTemplate>()));
348 for _ in 0..packages_len {
349 packages.push(Readable::read(reader)?);
351 locktimed_packages.insert(locktime, packages);
354 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
355 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
356 for _ in 0..waiting_threshold_conf_len {
357 if let Some(val) = MaybeReadable::read(reader)? {
358 onchain_events_awaiting_threshold_conf.push(val);
362 read_tlv_fields!(reader, {});
364 let mut secp_ctx = Secp256k1::new();
365 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
367 Ok(OnchainTxHandler {
371 prev_holder_commitment,
372 prev_holder_htlc_sigs,
374 channel_transaction_parameters: channel_parameters,
377 pending_claim_requests,
378 onchain_events_awaiting_threshold_conf,
380 pending_claim_events: HashMap::new(),
386 impl<ChannelSigner: Sign> OnchainTxHandler<ChannelSigner> {
387 pub(crate) fn new(destination_script: Script, signer: ChannelSigner, channel_parameters: ChannelTransactionParameters, holder_commitment: HolderCommitmentTransaction, secp_ctx: Secp256k1<secp256k1::All>) -> Self {
391 holder_htlc_sigs: None,
392 prev_holder_commitment: None,
393 prev_holder_htlc_sigs: None,
395 channel_transaction_parameters: channel_parameters,
396 pending_claim_requests: HashMap::new(),
397 claimable_outpoints: HashMap::new(),
398 locktimed_packages: BTreeMap::new(),
399 onchain_events_awaiting_threshold_conf: Vec::new(),
401 pending_claim_events: HashMap::new(),
407 pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option<u64> {
408 self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat())
411 pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 {
412 self.holder_commitment.to_broadcaster_value_sat()
416 pub(crate) fn get_and_clear_pending_claim_events(&mut self) -> Vec<ClaimEvent> {
417 let mut ret = HashMap::new();
418 swap(&mut ret, &mut self.pending_claim_events);
419 ret.into_iter().map(|(_, event)| event).collect::<Vec<_>>()
422 /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize counterparty
423 /// onchain) lays on the assumption of claim transactions getting confirmed before timelock
424 /// expiration (CSV or CLTV following cases). In case of high-fee spikes, claim tx may get stuck
425 /// in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or
426 /// Child-Pay-For-Parent.
428 /// Panics if there are signing errors, because signing operations in reaction to on-chain
429 /// events are not expected to fail, and if they do, we may lose funds.
430 fn generate_claim<F: Deref, L: Deref>(&mut self, cur_height: u32, cached_request: &PackageTemplate, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L) -> Option<(Option<u32>, u64, OnchainClaim)>
431 where F::Target: FeeEstimator,
434 if cached_request.outpoints().len() == 0 { return None } // But don't prune pending claiming request yet, we may have to resurrect HTLCs
436 // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we
437 // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it).
438 let new_timer = Some(cached_request.get_height_timer(cur_height));
439 if cached_request.is_malleable() {
440 let predicted_weight = cached_request.package_weight(&self.destination_script);
441 if let Some((output_value, new_feerate)) =
442 cached_request.compute_package_output(predicted_weight, self.destination_script.dust_value().to_sat(), fee_estimator, logger) {
443 assert!(new_feerate != 0);
445 let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
446 log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
447 assert!(predicted_weight >= transaction.weight());
448 return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)))
451 // Untractable packages cannot have their fees bumped through Replace-By-Fee. Some
452 // packages may support fee bumping through Child-Pays-For-Parent, indicated by those
453 // which require external funding.
455 let inputs = cached_request.inputs();
457 let mut inputs = cached_request.inputs();
458 debug_assert_eq!(inputs.len(), 1);
459 let tx = match cached_request.finalize_untractable_package(self, logger) {
463 if !cached_request.requires_external_funding() {
464 return Some((None, 0, OnchainClaim::Tx(tx)));
467 return inputs.find_map(|input| match input {
468 // Commitment inputs with anchors support are the only untractable inputs supported
469 // thus far that require external funding.
470 PackageSolvingData::HolderFundingOutput(..) => {
471 debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
472 "Holder commitment transaction mismatch");
473 // We'll locate an anchor output we can spend within the commitment transaction.
474 let funding_pubkey = &self.channel_transaction_parameters.holder_pubkeys.funding_pubkey;
475 match chan_utils::get_anchor_output(&tx, funding_pubkey) {
476 // An anchor output was found, so we should yield a funding event externally.
478 // TODO: Use a lower confirmation target when both our and the
479 // counterparty's latest commitment don't have any HTLCs present.
480 let conf_target = ConfirmationTarget::HighPriority;
481 let package_target_feerate_sat_per_1000_weight = cached_request
482 .compute_package_feerate(fee_estimator, conf_target);
485 package_target_feerate_sat_per_1000_weight as u64,
486 OnchainClaim::Event(ClaimEvent::BumpCommitment {
487 package_target_feerate_sat_per_1000_weight,
488 commitment_tx: tx.clone(),
489 anchor_output_idx: idx,
493 // An anchor output was not found. There's nothing we can do other than
494 // attempt to broadcast the transaction with its current fee rate and hope
495 // it confirms. This is essentially the same behavior as a commitment
496 // transaction without anchor outputs.
497 None => Some((None, 0, OnchainClaim::Tx(tx.clone()))),
501 debug_assert!(false, "Only HolderFundingOutput inputs should be untractable and require external funding");
509 /// Upon channelmonitor.block_connected(..) or upon provision of a preimage on the forward link
510 /// for this channel, provide new relevant on-chain transactions and/or new claim requests.
511 /// Formerly this was named `block_connected`, but it is now also used for claiming an HTLC output
512 /// if we receive a preimage after force-close.
513 /// `conf_height` represents the height at which the transactions in `txn_matched` were
514 /// confirmed. This does not need to equal the current blockchain tip height, which should be
515 /// provided via `cur_height`, however it must never be higher than `cur_height`.
516 pub(crate) fn update_claims_view<B: Deref, F: Deref, L: Deref>(&mut self, txn_matched: &[&Transaction], requests: Vec<PackageTemplate>, conf_height: u32, cur_height: u32, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
517 where B::Target: BroadcasterInterface,
518 F::Target: FeeEstimator,
521 log_debug!(logger, "Updating claims view at height {} with {} matched transactions in block {} and {} claim requests", cur_height, txn_matched.len(), conf_height, requests.len());
522 let mut preprocessed_requests = Vec::with_capacity(requests.len());
523 let mut aggregated_request = None;
525 // Try to aggregate outputs if their timelock expiration isn't imminent (package timelock
526 // <= CLTV_SHARED_CLAIM_BUFFER) and they don't require an immediate nLockTime (aggregable).
527 for req in requests {
528 // Don't claim a outpoint twice that would be bad for privacy and may uselessly lock a CPFP input for a while
529 if let Some(_) = self.claimable_outpoints.get(req.outpoints()[0]) {
530 log_info!(logger, "Ignoring second claim for outpoint {}:{}, already registered its claiming request", req.outpoints()[0].txid, req.outpoints()[0].vout);
532 let timelocked_equivalent_package = self.locktimed_packages.iter().map(|v| v.1.iter()).flatten()
533 .find(|locked_package| locked_package.outpoints() == req.outpoints());
534 if let Some(package) = timelocked_equivalent_package {
535 log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
536 req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
540 if req.package_timelock() > cur_height + 1 {
541 log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
542 for outpoint in req.outpoints() {
543 log_info!(logger, " Outpoint {}", outpoint);
545 self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
549 log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER);
550 if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() {
551 // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable
552 preprocessed_requests.push(req);
553 } else if aggregated_request.is_none() {
554 aggregated_request = Some(req);
556 aggregated_request.as_mut().unwrap().merge_package(req);
560 if let Some(req) = aggregated_request {
561 preprocessed_requests.push(req);
564 // Claim everything up to and including cur_height + 1
565 let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 2));
566 for (pop_height, mut entry) in self.locktimed_packages.iter_mut() {
567 log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height);
568 preprocessed_requests.append(&mut entry);
570 self.locktimed_packages = remaining_locked_packages;
572 // Generate claim transactions and track them to bump if necessary at
573 // height timer expiration (i.e in how many blocks we're going to take action).
574 for mut req in preprocessed_requests {
575 if let Some((new_timer, new_feerate, claim)) = self.generate_claim(cur_height, &req, &*fee_estimator, &*logger) {
576 req.set_timer(new_timer);
577 req.set_feerate(new_feerate);
578 let txid = match claim {
579 OnchainClaim::Tx(tx) => {
580 log_info!(logger, "Broadcasting onchain {}", log_tx!(tx));
581 broadcaster.broadcast_transaction(&tx);
585 OnchainClaim::Event(claim_event) => {
586 log_info!(logger, "Yielding onchain event to spend inputs {:?}", req.outpoints());
587 let txid = match claim_event {
588 ClaimEvent::BumpCommitment { ref commitment_tx, .. } => commitment_tx.txid(),
590 self.pending_claim_events.insert(txid, claim_event);
594 for k in req.outpoints() {
595 log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout);
596 self.claimable_outpoints.insert(k.clone(), (txid, conf_height));
598 self.pending_claim_requests.insert(txid, req);
602 let mut bump_candidates = HashMap::new();
603 for tx in txn_matched {
604 // Scan all input to verify is one of the outpoint spent is of interest for us
605 let mut claimed_outputs_material = Vec::new();
606 for inp in &tx.input {
607 if let Some(first_claim_txid_height) = self.claimable_outpoints.get(&inp.previous_output) {
608 // If outpoint has claim request pending on it...
609 if let Some(request) = self.pending_claim_requests.get_mut(&first_claim_txid_height.0) {
610 //... we need to verify equality between transaction outpoints and claim request
611 // outpoints to know if transaction is the original claim or a bumped one issued
613 let mut set_equality = true;
614 if request.outpoints().len() != tx.input.len() {
615 set_equality = false;
617 for (claim_inp, tx_inp) in request.outpoints().iter().zip(tx.input.iter()) {
618 if **claim_inp != tx_inp.previous_output {
619 set_equality = false;
624 macro_rules! clean_claim_request_after_safety_delay {
626 let entry = OnchainEventEntry {
629 event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() }
631 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
632 self.onchain_events_awaiting_threshold_conf.push(entry);
637 // If this is our transaction (or our counterparty spent all the outputs
638 // before we could anyway with same inputs order than us), wait for
639 // ANTI_REORG_DELAY and clean the RBF tracking map.
641 clean_claim_request_after_safety_delay!();
642 } else { // If false, generate new claim request with update outpoint set
643 let mut at_least_one_drop = false;
644 for input in tx.input.iter() {
645 if let Some(package) = request.split_package(&input.previous_output) {
646 claimed_outputs_material.push(package);
647 at_least_one_drop = true;
649 // If there are no outpoints left to claim in this request, drop it entirely after ANTI_REORG_DELAY.
650 if request.outpoints().is_empty() {
651 clean_claim_request_after_safety_delay!();
654 //TODO: recompute soonest_timelock to avoid wasting a bit on fees
655 if at_least_one_drop {
656 bump_candidates.insert(first_claim_txid_height.0.clone(), request.clone());
659 break; //No need to iterate further, either tx is our or their
661 panic!("Inconsistencies between pending_claim_requests map and claimable_outpoints map");
665 for package in claimed_outputs_material.drain(..) {
666 let entry = OnchainEventEntry {
669 event: OnchainEvent::ContentiousOutpoint { package },
671 if !self.onchain_events_awaiting_threshold_conf.contains(&entry) {
672 self.onchain_events_awaiting_threshold_conf.push(entry);
677 // After security delay, either our claim tx got enough confs or outpoint is definetely out of reach
678 let onchain_events_awaiting_threshold_conf =
679 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
680 for entry in onchain_events_awaiting_threshold_conf {
681 if entry.has_reached_confirmation_threshold(cur_height) {
683 OnchainEvent::Claim { claim_request } => {
684 // We may remove a whole set of claim outpoints here, as these one may have
685 // been aggregated in a single tx and claimed so atomically
686 if let Some(request) = self.pending_claim_requests.remove(&claim_request) {
687 for outpoint in request.outpoints() {
688 log_debug!(logger, "Removing claim tracking for {} due to maturation of claim tx {}.", outpoint, claim_request);
689 self.claimable_outpoints.remove(&outpoint);
691 self.pending_claim_events.remove(&claim_request);
695 OnchainEvent::ContentiousOutpoint { package } => {
696 log_debug!(logger, "Removing claim tracking due to maturation of claim tx for outpoints:");
697 log_debug!(logger, " {:?}", package.outpoints());
698 self.claimable_outpoints.remove(&package.outpoints()[0]);
702 self.onchain_events_awaiting_threshold_conf.push(entry);
706 // Check if any pending claim request must be rescheduled
707 for (first_claim_txid, ref request) in self.pending_claim_requests.iter() {
708 if let Some(h) = request.timer() {
710 bump_candidates.insert(*first_claim_txid, (*request).clone());
715 // Build, bump and rebroadcast tx accordingly
716 log_trace!(logger, "Bumping {} candidates", bump_candidates.len());
717 for (first_claim_txid, request) in bump_candidates.iter() {
718 if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(cur_height, &request, &*fee_estimator, &*logger) {
720 OnchainClaim::Tx(bump_tx) => {
721 log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx));
722 broadcaster.broadcast_transaction(&bump_tx);
725 OnchainClaim::Event(claim_event) => {
726 log_info!(logger, "Yielding RBF-bumped onchain event to spend inputs {:?}", request.outpoints());
727 self.pending_claim_events.insert(*first_claim_txid, claim_event);
730 if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) {
731 request.set_timer(new_timer);
732 request.set_feerate(new_feerate);
738 pub(crate) fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
742 fee_estimator: &LowerBoundedFeeEstimator<F>,
745 B::Target: BroadcasterInterface,
746 F::Target: FeeEstimator,
749 let mut height = None;
750 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
751 if entry.txid == *txid {
752 height = Some(entry.height);
757 if let Some(height) = height {
758 self.block_disconnected(height, broadcaster, fee_estimator, logger);
762 pub(crate) fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, height: u32, broadcaster: B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: L)
763 where B::Target: BroadcasterInterface,
764 F::Target: FeeEstimator,
767 let mut bump_candidates = HashMap::new();
768 let onchain_events_awaiting_threshold_conf =
769 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
770 for entry in onchain_events_awaiting_threshold_conf {
771 if entry.height >= height {
772 //- our claim tx on a commitment tx output
773 //- resurect outpoint back in its claimable set and regenerate tx
775 OnchainEvent::ContentiousOutpoint { package } => {
776 if let Some(ancestor_claimable_txid) = self.claimable_outpoints.get(&package.outpoints()[0]) {
777 if let Some(request) = self.pending_claim_requests.get_mut(&ancestor_claimable_txid.0) {
778 request.merge_package(package);
779 // Using a HashMap guarantee us than if we have multiple outpoints getting
780 // resurrected only one bump claim tx is going to be broadcast
781 bump_candidates.insert(ancestor_claimable_txid.clone(), request.clone());
788 self.onchain_events_awaiting_threshold_conf.push(entry);
791 for (_first_claim_txid_height, request) in bump_candidates.iter_mut() {
792 if let Some((new_timer, new_feerate, bump_claim)) = self.generate_claim(height, &request, fee_estimator, &&*logger) {
793 request.set_timer(new_timer);
794 request.set_feerate(new_feerate);
796 OnchainClaim::Tx(bump_tx) => {
797 log_info!(logger, "Broadcasting onchain {}", log_tx!(bump_tx));
798 broadcaster.broadcast_transaction(&bump_tx);
801 OnchainClaim::Event(claim_event) => {
802 log_info!(logger, "Yielding onchain event after reorg to spend inputs {:?}", request.outpoints());
803 self.pending_claim_events.insert(_first_claim_txid_height.0, claim_event);
808 for (ancestor_claim_txid, request) in bump_candidates.drain() {
809 self.pending_claim_requests.insert(ancestor_claim_txid.0, request);
811 //TODO: if we implement cross-block aggregated claim transaction we need to refresh set of outpoints and regenerate tx but
812 // right now if one of the outpoint get disconnected, just erase whole pending claim request.
813 let mut remove_request = Vec::new();
814 self.claimable_outpoints.retain(|_, ref v|
816 remove_request.push(v.0.clone());
819 for req in remove_request {
820 self.pending_claim_requests.remove(&req);
824 pub(crate) fn is_output_spend_pending(&self, outpoint: &BitcoinOutPoint) -> bool {
825 self.claimable_outpoints.get(outpoint).is_some()
828 pub(crate) fn get_relevant_txids(&self) -> Vec<Txid> {
829 let mut txids: Vec<Txid> = self.onchain_events_awaiting_threshold_conf
831 .map(|entry| entry.txid)
833 txids.sort_unstable();
838 pub(crate) fn provide_latest_holder_tx(&mut self, tx: HolderCommitmentTransaction) {
839 self.prev_holder_commitment = Some(replace(&mut self.holder_commitment, tx));
840 self.holder_htlc_sigs = None;
843 // Normally holder HTLCs are signed at the same time as the holder commitment tx. However,
844 // in some configurations, the holder commitment tx has been signed and broadcast by a
845 // ChannelMonitor replica, so we handle that case here.
846 fn sign_latest_holder_htlcs(&mut self) {
847 if self.holder_htlc_sigs.is_none() {
848 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
849 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, sigs));
853 // Normally only the latest commitment tx and HTLCs need to be signed. However, in some
854 // configurations we may have updated our holder commitment but a replica of the ChannelMonitor
855 // broadcast the previous one before we sync with it. We handle that case here.
856 fn sign_prev_holder_htlcs(&mut self) {
857 if self.prev_holder_htlc_sigs.is_none() {
858 if let Some(ref holder_commitment) = self.prev_holder_commitment {
859 let (_sig, sigs) = self.signer.sign_holder_commitment_and_htlcs(holder_commitment, &self.secp_ctx).expect("sign previous holder commitment");
860 self.prev_holder_htlc_sigs = Some(Self::extract_holder_sigs(holder_commitment, sigs));
865 fn extract_holder_sigs(holder_commitment: &HolderCommitmentTransaction, sigs: Vec<Signature>) -> Vec<Option<(usize, Signature)>> {
866 let mut ret = Vec::new();
867 for (htlc_idx, (holder_sig, htlc)) in sigs.iter().zip(holder_commitment.htlcs().iter()).enumerate() {
868 let tx_idx = htlc.transaction_output_index.unwrap();
869 if ret.len() <= tx_idx as usize { ret.resize(tx_idx as usize + 1, None); }
870 ret[tx_idx as usize] = Some((htlc_idx, holder_sig.clone()));
875 //TODO: getting lastest holder transactions should be infallible and result in us "force-closing the channel", but we may
876 // have empty holder commitment transaction if a ChannelMonitor is asked to force-close just after Channel::get_outbound_funding_created,
877 // before providing a initial commitment transaction. For outbound channel, init ChannelMonitor at Channel::funding_signed, there is nothing
878 // to monitor before.
879 pub(crate) fn get_fully_signed_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
880 let (sig, htlc_sigs) = self.signer.sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("signing holder commitment");
881 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
882 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
885 #[cfg(any(test, feature="unsafe_revoked_tx_signing"))]
886 pub(crate) fn get_fully_signed_copy_holder_tx(&mut self, funding_redeemscript: &Script) -> Transaction {
887 let (sig, htlc_sigs) = self.signer.unsafe_sign_holder_commitment_and_htlcs(&self.holder_commitment, &self.secp_ctx).expect("sign holder commitment");
888 self.holder_htlc_sigs = Some(Self::extract_holder_sigs(&self.holder_commitment, htlc_sigs));
889 self.holder_commitment.add_holder_sig(funding_redeemscript, sig)
892 pub(crate) fn get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
893 let mut htlc_tx = None;
894 let commitment_txid = self.holder_commitment.trust().txid();
895 // Check if the HTLC spends from the current holder commitment
896 if commitment_txid == outp.txid {
897 self.sign_latest_holder_htlcs();
898 if let &Some(ref htlc_sigs) = &self.holder_htlc_sigs {
899 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
900 let trusted_tx = self.holder_commitment.trust();
901 let counterparty_htlc_sig = self.holder_commitment.counterparty_htlc_sigs[*htlc_idx];
902 htlc_tx = Some(trusted_tx
903 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
906 // If the HTLC doesn't spend the current holder commitment, check if it spends the previous one
907 if htlc_tx.is_none() && self.prev_holder_commitment.is_some() {
908 let commitment_txid = self.prev_holder_commitment.as_ref().unwrap().trust().txid();
909 if commitment_txid == outp.txid {
910 self.sign_prev_holder_htlcs();
911 if let &Some(ref htlc_sigs) = &self.prev_holder_htlc_sigs {
912 let &(ref htlc_idx, ref htlc_sig) = htlc_sigs[outp.vout as usize].as_ref().unwrap();
913 let holder_commitment = self.prev_holder_commitment.as_ref().unwrap();
914 let trusted_tx = holder_commitment.trust();
915 let counterparty_htlc_sig = holder_commitment.counterparty_htlc_sigs[*htlc_idx];
916 htlc_tx = Some(trusted_tx
917 .get_signed_htlc_tx(&self.channel_transaction_parameters.as_holder_broadcastable(), *htlc_idx, &counterparty_htlc_sig, htlc_sig, preimage));
924 pub(crate) fn opt_anchors(&self) -> bool {
925 self.channel_transaction_parameters.opt_anchors.is_some()
928 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
929 pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option<PaymentPreimage>) -> Option<Transaction> {
930 let latest_had_sigs = self.holder_htlc_sigs.is_some();
931 let prev_had_sigs = self.prev_holder_htlc_sigs.is_some();
932 let ret = self.get_fully_signed_htlc_tx(outp, preimage);
933 if !latest_had_sigs {
934 self.holder_htlc_sigs = None;
937 self.prev_holder_htlc_sigs = None;