X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Fchain%2Fonchaintx.rs;h=6f64f3eec56210b3e383dd0a15b87368946a2201;hb=88a86d126f1bab0af8270a6388843dcc4a354e70;hp=23b05afe687f92b4b67033191afe9d246f2f47f0;hpb=e75d41be7a22e4d9477c52842b8adff8983eeafb;p=rust-lightning diff --git a/lightning/src/chain/onchaintx.rs b/lightning/src/chain/onchaintx.rs index 23b05afe..6f64f3ee 100644 --- a/lightning/src/chain/onchaintx.rs +++ b/lightning/src/chain/onchaintx.rs @@ -29,9 +29,10 @@ use chain::channelmonitor::{ANTI_REORG_DELAY, CLTV_SHARED_CLAIM_BUFFER}; use chain::keysinterface::{Sign, KeysInterface}; use chain::package::PackageTemplate; use util::logger::Logger; -use util::ser::{Readable, ReadableArgs, Writer, Writeable, VecWriter}; +use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, VecWriter}; use util::byte_utils; +use io; use prelude::*; use alloc::collections::BTreeMap; use core::cmp; @@ -78,23 +79,46 @@ enum OnchainEvent { } } -impl_writeable_tlv_based!(OnchainEventEntry, { - (0, txid, required), - (2, height, required), - (4, event, required), -}); +impl Writeable for OnchainEventEntry { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { + write_tlv_fields!(writer, { + (0, self.txid, required), + (2, self.height, required), + (4, self.event, required), + }); + Ok(()) + } +} + +impl MaybeReadable for OnchainEventEntry { + fn read(reader: &mut R) -> Result, DecodeError> { + let mut txid = Default::default(); + let mut height = 0; + let mut event = None; + read_tlv_fields!(reader, { + (0, txid, required), + (2, height, required), + (4, event, ignorable), + }); + if let Some(ev) = event { + Ok(Some(Self { txid, height, event: ev })) + } else { + Ok(None) + } + } +} -impl_writeable_tlv_based_enum!(OnchainEvent, +impl_writeable_tlv_based_enum_upgradable!(OnchainEvent, (0, Claim) => { (0, claim_request, required), }, (1, ContentiousOutpoint) => { (0, package, required), }, -;); +); impl Readable for Option>> { - fn read(reader: &mut R) -> Result { + fn read(reader: &mut R) -> Result { match Readable::read(reader)? { 0u8 => Ok(None), 1u8 => { @@ -115,7 +139,7 @@ impl Readable for Option>> { } impl Writeable for Option>> { - fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + fn write(&self, writer: &mut W) -> Result<(), io::Error> { match self { &Some(ref vec) => { 1u8.write(writer)?; @@ -191,7 +215,7 @@ const SERIALIZATION_VERSION: u8 = 1; const MIN_SERIALIZATION_VERSION: u8 = 1; impl OnchainTxHandler { - pub(crate) fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { + pub(crate) fn write(&self, writer: &mut W) -> Result<(), io::Error> { write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION); self.destination_script.write(writer)?; @@ -242,7 +266,7 @@ impl OnchainTxHandler { } impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { - fn read(reader: &mut R, keys_manager: &'a K) -> Result { + fn read(reader: &mut R, keys_manager: &'a K) -> Result { let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION); let destination_script = Readable::read(reader)?; @@ -285,7 +309,7 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { for _ in 0..locktimed_packages_len { let locktime = Readable::read(reader)?; let packages_len: u64 = Readable::read(reader)?; - let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / std::mem::size_of::())); + let mut packages = Vec::with_capacity(cmp::min(packages_len as usize, MAX_ALLOC_SIZE / core::mem::size_of::())); for _ in 0..packages_len { packages.push(Readable::read(reader)?); } @@ -295,7 +319,9 @@ impl<'a, K: KeysInterface> ReadableArgs<&'a K> for OnchainTxHandler { let waiting_threshold_conf_len: u64 = Readable::read(reader)?; let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128)); for _ in 0..waiting_threshold_conf_len { - onchain_events_awaiting_threshold_conf.push(Readable::read(reader)?); + if let Some(val) = MaybeReadable::read(reader)? { + onchain_events_awaiting_threshold_conf.push(val); + } } read_tlv_fields!(reader, {}); @@ -339,11 +365,19 @@ impl OnchainTxHandler { } } + pub(crate) fn get_prev_holder_commitment_to_self_value(&self) -> Option { + self.prev_holder_commitment.as_ref().map(|commitment| commitment.to_broadcaster_value_sat()) + } + + pub(crate) fn get_cur_holder_commitment_to_self_value(&self) -> u64 { + self.holder_commitment.to_broadcaster_value_sat() + } + /// Lightning security model (i.e being able to redeem/timeout HTLC or penalize coutnerparty onchain) lays on the assumption of claim transactions getting confirmed before timelock expiration /// (CSV or CLTV following cases). In case of high-fee spikes, claim tx may stuck in the mempool, so you need to bump its feerate quickly using Replace-By-Fee or Child-Pay-For-Parent. /// Panics if there are signing errors, because signing operations in reaction to on-chain events /// are not expected to fail, and if they do, we may lose funds. - fn generate_claim_tx(&mut self, height: u32, cached_request: &PackageTemplate, fee_estimator: &F, logger: &L) -> Option<(Option, u64, Transaction)> + fn generate_claim_tx(&mut self, cur_height: u32, cached_request: &PackageTemplate, fee_estimator: &F, logger: &L) -> Option<(Option, u64, Transaction)> where F::Target: FeeEstimator, L::Target: Logger, { @@ -351,10 +385,11 @@ impl OnchainTxHandler { // Compute new height timer to decide when we need to regenerate a new bumped version of the claim tx (if we // didn't receive confirmation of it before, or not enough reorg-safe depth on top of it). - let new_timer = Some(cached_request.get_height_timer(height)); + let new_timer = Some(cached_request.get_height_timer(cur_height)); if cached_request.is_malleable() { let predicted_weight = cached_request.package_weight(&self.destination_script); - if let Some((output_value, new_feerate)) = cached_request.compute_package_output(predicted_weight, fee_estimator, logger) { + if let Some((output_value, new_feerate)) = + cached_request.compute_package_output(predicted_weight, self.destination_script.dust_value().as_sat(), fee_estimator, logger) { assert!(new_feerate != 0); let transaction = cached_request.finalize_package(self, output_value, self.destination_script.clone(), logger).unwrap(); @@ -377,12 +412,15 @@ impl OnchainTxHandler { /// for this channel, provide new relevant on-chain transactions and/or new claim requests. /// Formerly this was named `block_connected`, but it is now also used for claiming an HTLC output /// if we receive a preimage after force-close. - pub(crate) fn update_claims_view(&mut self, txn_matched: &[&Transaction], requests: Vec, height: u32, broadcaster: &B, fee_estimator: &F, logger: &L) + /// `conf_height` represents the height at which the transactions in `txn_matched` were + /// confirmed. This does not need to equal the current blockchain tip height, which should be + /// provided via `cur_height`, however it must never be higher than `cur_height`. + pub(crate) fn update_claims_view(&mut self, txn_matched: &[&Transaction], requests: Vec, conf_height: u32, cur_height: u32, broadcaster: &B, fee_estimator: &F, logger: &L) where B::Target: BroadcasterInterface, F::Target: FeeEstimator, L::Target: Logger, { - log_debug!(logger, "Updating claims view at height {} with {} matched transactions and {} claim requests", height, txn_matched.len(), requests.len()); + 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()); let mut preprocessed_requests = Vec::with_capacity(requests.len()); let mut aggregated_request = None; @@ -401,8 +439,8 @@ impl OnchainTxHandler { continue; } - if req.package_timelock() > height + 1 { - log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), height); + if req.package_timelock() > cur_height + 1 { + log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height); for outpoint in req.outpoints() { log_info!(logger, " Outpoint {}", outpoint); } @@ -410,8 +448,8 @@ impl OnchainTxHandler { continue; } - log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), height + CLTV_SHARED_CLAIM_BUFFER); - if req.timelock() <= height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() { + log_trace!(logger, "Test if outpoint can be aggregated with expiration {} against {}", req.timelock(), cur_height + CLTV_SHARED_CLAIM_BUFFER); + if req.timelock() <= cur_height + CLTV_SHARED_CLAIM_BUFFER || !req.aggregable() { // Don't aggregate if outpoint package timelock is soon or marked as non-aggregable preprocessed_requests.push(req); } else if aggregated_request.is_none() { @@ -425,8 +463,8 @@ impl OnchainTxHandler { preprocessed_requests.push(req); } - // Claim everything up to and including height + 1 - let remaining_locked_packages = self.locktimed_packages.split_off(&(height + 2)); + // Claim everything up to and including cur_height + 1 + let remaining_locked_packages = self.locktimed_packages.split_off(&(cur_height + 2)); for (pop_height, mut entry) in self.locktimed_packages.iter_mut() { log_trace!(logger, "Restoring delayed claim of package(s) at their timelock at {}.", pop_height); preprocessed_requests.append(&mut entry); @@ -436,13 +474,13 @@ impl OnchainTxHandler { // Generate claim transactions and track them to bump if necessary at // height timer expiration (i.e in how many blocks we're going to take action). for mut req in preprocessed_requests { - if let Some((new_timer, new_feerate, tx)) = self.generate_claim_tx(height, &req, &*fee_estimator, &*logger) { + if let Some((new_timer, new_feerate, tx)) = self.generate_claim_tx(cur_height, &req, &*fee_estimator, &*logger) { req.set_timer(new_timer); req.set_feerate(new_feerate); let txid = tx.txid(); for k in req.outpoints() { log_info!(logger, "Registering claiming request for {}:{}", k.txid, k.vout); - self.claimable_outpoints.insert(k.clone(), (txid, height)); + self.claimable_outpoints.insert(k.clone(), (txid, conf_height)); } self.pending_claim_requests.insert(txid, req); log_info!(logger, "Broadcasting onchain {}", log_tx!(tx)); @@ -476,7 +514,7 @@ impl OnchainTxHandler { () => { let entry = OnchainEventEntry { txid: tx.txid(), - height, + height: conf_height, event: OnchainEvent::Claim { claim_request: first_claim_txid_height.0.clone() } }; if !self.onchain_events_awaiting_threshold_conf.contains(&entry) { @@ -516,7 +554,7 @@ impl OnchainTxHandler { for package in claimed_outputs_material.drain(..) { let entry = OnchainEventEntry { txid: tx.txid(), - height, + height: conf_height, event: OnchainEvent::ContentiousOutpoint { package }, }; if !self.onchain_events_awaiting_threshold_conf.contains(&entry) { @@ -529,7 +567,7 @@ impl OnchainTxHandler { let onchain_events_awaiting_threshold_conf = self.onchain_events_awaiting_threshold_conf.drain(..).collect::>(); for entry in onchain_events_awaiting_threshold_conf { - if entry.has_reached_confirmation_threshold(height) { + if entry.has_reached_confirmation_threshold(cur_height) { match entry.event { OnchainEvent::Claim { claim_request } => { // We may remove a whole set of claim outpoints here, as these one may have @@ -555,7 +593,7 @@ impl OnchainTxHandler { // Check if any pending claim request must be rescheduled for (first_claim_txid, ref request) in self.pending_claim_requests.iter() { if let Some(h) = request.timer() { - if height >= h { + if cur_height >= h { bump_candidates.insert(*first_claim_txid, (*request).clone()); } } @@ -564,7 +602,7 @@ impl OnchainTxHandler { // Build, bump and rebroadcast tx accordingly log_trace!(logger, "Bumping {} candidates", bump_candidates.len()); for (first_claim_txid, request) in bump_candidates.iter() { - if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(height, &request, &*fee_estimator, &*logger) { + if let Some((new_timer, new_feerate, bump_tx)) = self.generate_claim_tx(cur_height, &request, &*fee_estimator, &*logger) { log_info!(logger, "Broadcasting RBF-bumped onchain {}", log_tx!(bump_tx)); broadcaster.broadcast_transaction(&bump_tx); if let Some(request) = self.pending_claim_requests.get_mut(first_claim_txid) { @@ -748,6 +786,10 @@ impl OnchainTxHandler { htlc_tx } + pub(crate) fn opt_anchors(&self) -> bool { + self.channel_transaction_parameters.opt_anchors.is_some() + } + #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))] pub(crate) fn unsafe_get_fully_signed_htlc_tx(&mut self, outp: &::bitcoin::OutPoint, preimage: &Option) -> Option { let latest_had_sigs = self.holder_htlc_sigs.is_some();