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 monitor for on-chain transactions and create the relevant claim responses lives
13 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
14 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
15 //! be made in responding to certain messages, see [`chain::Watch`] for more.
17 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
18 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
19 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
20 //! security-domain-separated system design, you should consider having multiple paths for
21 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
23 use bitcoin::blockdata::block::BlockHeader;
24 use bitcoin::blockdata::transaction::{TxOut,Transaction};
25 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
26 use bitcoin::blockdata::script::{Script, Builder};
27 use bitcoin::blockdata::opcodes;
29 use bitcoin::hashes::Hash;
30 use bitcoin::hashes::sha256::Hash as Sha256;
31 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
33 use bitcoin::secp256k1::{Secp256k1, ecdsa::Signature};
34 use bitcoin::secp256k1::{SecretKey, PublicKey};
35 use bitcoin::secp256k1;
37 use ln::{PaymentHash, PaymentPreimage};
38 use ln::msgs::DecodeError;
40 use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCType, ChannelTransactionParameters, HolderCommitmentTransaction};
41 use ln::channelmanager::HTLCSource;
43 use chain::{BestBlock, WatchedOutput};
44 use chain::chaininterface::{BroadcasterInterface, FeeEstimator, LowerBoundedFeeEstimator};
45 use chain::transaction::{OutPoint, TransactionData};
46 use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
47 use chain::onchaintx::OnchainTxHandler;
48 use chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
50 use util::logger::Logger;
51 use util::ser::{Readable, ReadableArgs, MaybeReadable, Writer, Writeable, U48, OptionDeserWrapper};
53 use util::events::Event;
57 use io::{self, Error};
58 use core::convert::TryInto;
62 /// An update generated by the underlying Channel itself which contains some new information the
63 /// ChannelMonitor should be made aware of.
64 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
67 pub struct ChannelMonitorUpdate {
68 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
69 /// The sequence number of this update. Updates *must* be replayed in-order according to this
70 /// sequence number (and updates may panic if they are not). The update_id values are strictly
71 /// increasing and increase by one for each new update, with one exception specified below.
73 /// This sequence number is also used to track up to which points updates which returned
74 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
75 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
77 /// The only instance where update_id values are not strictly increasing is the case where we
78 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
79 /// its docs for more details.
84 /// (1) a channel has been force closed and
85 /// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
86 /// this channel's (the backward link's) broadcasted commitment transaction
87 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
88 /// with the update providing said payment preimage. No other update types are allowed after
90 pub const CLOSED_CHANNEL_UPDATE_ID: u64 = core::u64::MAX;
92 impl Writeable for ChannelMonitorUpdate {
93 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
94 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
95 self.update_id.write(w)?;
96 (self.updates.len() as u64).write(w)?;
97 for update_step in self.updates.iter() {
98 update_step.write(w)?;
100 write_tlv_fields!(w, {});
104 impl Readable for ChannelMonitorUpdate {
105 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
106 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
107 let update_id: u64 = Readable::read(r)?;
108 let len: u64 = Readable::read(r)?;
109 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
111 if let Some(upd) = MaybeReadable::read(r)? {
115 read_tlv_fields!(r, {});
116 Ok(Self { update_id, updates })
120 /// An event to be processed by the ChannelManager.
121 #[derive(Clone, PartialEq)]
122 pub enum MonitorEvent {
123 /// A monitor event containing an HTLCUpdate.
124 HTLCEvent(HTLCUpdate),
126 /// A monitor event that the Channel's commitment transaction was confirmed.
127 CommitmentTxConfirmed(OutPoint),
129 /// Indicates a [`ChannelMonitor`] update has completed. See
130 /// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used.
132 /// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure
134 /// The funding outpoint of the [`ChannelMonitor`] that was updated
135 funding_txo: OutPoint,
136 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
137 /// [`ChannelMonitor::get_latest_update_id`].
139 /// Note that this should only be set to a given update's ID if all previous updates for the
140 /// same [`ChannelMonitor`] have been applied and persisted.
141 monitor_update_id: u64,
144 /// Indicates a [`ChannelMonitor`] update has failed. See
145 /// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used.
147 /// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure
148 UpdateFailed(OutPoint),
150 impl_writeable_tlv_based_enum_upgradable!(MonitorEvent,
151 // Note that UpdateCompleted and UpdateFailed are currently never serialized to disk as they are
152 // generated only in ChainMonitor
153 (0, UpdateCompleted) => {
154 (0, funding_txo, required),
155 (2, monitor_update_id, required),
159 (4, CommitmentTxConfirmed),
163 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
164 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
165 /// preimage claim backward will lead to loss of funds.
166 #[derive(Clone, PartialEq)]
167 pub struct HTLCUpdate {
168 pub(crate) payment_hash: PaymentHash,
169 pub(crate) payment_preimage: Option<PaymentPreimage>,
170 pub(crate) source: HTLCSource,
171 pub(crate) htlc_value_satoshis: Option<u64>,
173 impl_writeable_tlv_based!(HTLCUpdate, {
174 (0, payment_hash, required),
175 (1, htlc_value_satoshis, option),
176 (2, source, required),
177 (4, payment_preimage, option),
180 /// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
181 /// instead claiming it in its own individual transaction.
182 pub(crate) const CLTV_SHARED_CLAIM_BUFFER: u32 = 12;
183 /// If an HTLC expires within this many blocks, force-close the channel to broadcast the
184 /// HTLC-Success transaction.
185 /// In other words, this is an upper bound on how many blocks we think it can take us to get a
186 /// transaction confirmed (and we use it in a few more, equivalent, places).
187 pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
188 /// Number of blocks by which point we expect our counterparty to have seen new blocks on the
189 /// network and done a full update_fail_htlc/commitment_signed dance (+ we've updated all our
190 /// copies of ChannelMonitors, including watchtowers). We could enforce the contract by failing
191 /// at CLTV expiration height but giving a grace period to our peer may be profitable for us if he
192 /// can provide an over-late preimage. Nevertheless, grace period has to be accounted in our
193 /// CLTV_EXPIRY_DELTA to be secure. Following this policy we may decrease the rate of channel failures
194 /// due to expiration but increase the cost of funds being locked longuer in case of failure.
195 /// This delay also cover a low-power peer being slow to process blocks and so being behind us on
196 /// accurate block height.
197 /// In case of onchain failure to be pass backward we may see the last block of ANTI_REORG_DELAY
198 /// with at worst this delay, so we are not only using this value as a mercy for them but also
199 /// us as a safeguard to delay with enough time.
200 pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
201 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
202 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
205 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
206 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
207 /// by a [`ChannelMonitor`] may be incorrect.
208 // We also use this delay to be sure we can remove our in-flight claim txn from bump candidates buffer.
209 // It may cause spurious generation of bumped claim txn but that's alright given the outpoint is already
210 // solved by a previous claim tx. What we want to avoid is reorg evicting our claim tx and us not
211 // keep bumping another claim tx to solve the outpoint.
212 pub const ANTI_REORG_DELAY: u32 = 6;
213 /// Number of blocks before confirmation at which we fail back an un-relayed HTLC or at which we
214 /// refuse to accept a new HTLC.
216 /// This is used for a few separate purposes:
217 /// 1) if we've received an MPP HTLC to us and it expires within this many blocks and we are
218 /// waiting on additional parts (or waiting on the preimage for any HTLC from the user), we will
220 /// 2) if we receive an HTLC within this many blocks of its expiry (plus one to avoid a race
221 /// condition with the above), we will fail this HTLC without telling the user we received it,
223 /// (1) is all about protecting us - we need enough time to update the channel state before we hit
224 /// CLTV_CLAIM_BUFFER, at which point we'd go on chain to claim the HTLC with the preimage.
226 /// (2) is the same, but with an additional buffer to avoid accepting an HTLC which is immediately
227 /// in a race condition between the user connecting a block (which would fail it) and the user
228 /// providing us the preimage (which would claim it).
229 pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
231 // TODO(devrandom) replace this with HolderCommitmentTransaction
232 #[derive(Clone, PartialEq)]
233 struct HolderSignedTx {
234 /// txid of the transaction in tx, just used to make comparison faster
236 revocation_key: PublicKey,
237 a_htlc_key: PublicKey,
238 b_htlc_key: PublicKey,
239 delayed_payment_key: PublicKey,
240 per_commitment_point: PublicKey,
241 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
242 to_self_value_sat: u64,
245 impl_writeable_tlv_based!(HolderSignedTx, {
247 // Note that this is filled in with data from OnchainTxHandler if it's missing.
248 // For HolderSignedTx objects serialized with 0.0.100+, this should be filled in.
249 (1, to_self_value_sat, (default_value, u64::max_value())),
250 (2, revocation_key, required),
251 (4, a_htlc_key, required),
252 (6, b_htlc_key, required),
253 (8, delayed_payment_key, required),
254 (10, per_commitment_point, required),
255 (12, feerate_per_kw, required),
256 (14, htlc_outputs, vec_type)
259 /// We use this to track static counterparty commitment transaction data and to generate any
260 /// justice or 2nd-stage preimage/timeout transactions.
262 struct CounterpartyCommitmentParameters {
263 counterparty_delayed_payment_base_key: PublicKey,
264 counterparty_htlc_base_key: PublicKey,
265 on_counterparty_tx_csv: u16,
268 impl Writeable for CounterpartyCommitmentParameters {
269 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
270 w.write_all(&byte_utils::be64_to_array(0))?;
271 write_tlv_fields!(w, {
272 (0, self.counterparty_delayed_payment_base_key, required),
273 (2, self.counterparty_htlc_base_key, required),
274 (4, self.on_counterparty_tx_csv, required),
279 impl Readable for CounterpartyCommitmentParameters {
280 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
281 let counterparty_commitment_transaction = {
282 // Versions prior to 0.0.100 had some per-HTLC state stored here, which is no longer
283 // used. Read it for compatibility.
284 let per_htlc_len: u64 = Readable::read(r)?;
285 for _ in 0..per_htlc_len {
286 let _txid: Txid = Readable::read(r)?;
287 let htlcs_count: u64 = Readable::read(r)?;
288 for _ in 0..htlcs_count {
289 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
293 let mut counterparty_delayed_payment_base_key = OptionDeserWrapper(None);
294 let mut counterparty_htlc_base_key = OptionDeserWrapper(None);
295 let mut on_counterparty_tx_csv: u16 = 0;
296 read_tlv_fields!(r, {
297 (0, counterparty_delayed_payment_base_key, required),
298 (2, counterparty_htlc_base_key, required),
299 (4, on_counterparty_tx_csv, required),
301 CounterpartyCommitmentParameters {
302 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
303 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
304 on_counterparty_tx_csv,
307 Ok(counterparty_commitment_transaction)
311 /// An entry for an [`OnchainEvent`], stating the block height when the event was observed and the
312 /// transaction causing it.
314 /// Used to determine when the on-chain event can be considered safe from a chain reorganization.
316 struct OnchainEventEntry {
320 transaction: Option<Transaction>, // Added as optional, but always filled in, in LDK 0.0.110
323 impl OnchainEventEntry {
324 fn confirmation_threshold(&self) -> u32 {
325 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
327 OnchainEvent::MaturingOutput {
328 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
330 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
331 // it's broadcastable when we see the previous block.
332 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
334 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
335 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
336 // A CSV'd transaction is confirmable in block (input height) + CSV delay, which means
337 // it's broadcastable when we see the previous block.
338 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
345 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
346 best_block.height() >= self.confirmation_threshold()
350 /// The (output index, sats value) for the counterparty's output in a commitment transaction.
352 /// This was added as an `Option` in 0.0.110.
353 type CommitmentTxCounterpartyOutputInfo = Option<(u32, u64)>;
355 /// Upon discovering of some classes of onchain tx by ChannelMonitor, we may have to take actions on it
356 /// once they mature to enough confirmations (ANTI_REORG_DELAY)
359 /// An outbound HTLC failing after a transaction is confirmed. Used
360 /// * when an outbound HTLC output is spent by us after the HTLC timed out
361 /// * an outbound HTLC which was not present in the commitment transaction which appeared
362 /// on-chain (either because it was not fully committed to or it was dust).
363 /// Note that this is *not* used for preimage claims, as those are passed upstream immediately,
364 /// appearing only as an `HTLCSpendConfirmation`, below.
367 payment_hash: PaymentHash,
368 htlc_value_satoshis: Option<u64>,
369 /// None in the second case, above, ie when there is no relevant output in the commitment
370 /// transaction which appeared on chain.
371 commitment_tx_output_idx: Option<u32>,
373 /// An output waiting on [`ANTI_REORG_DELAY`] confirmations before we hand the user the
374 /// [`SpendableOutputDescriptor`].
376 descriptor: SpendableOutputDescriptor,
378 /// A spend of the funding output, either a commitment transaction or a cooperative closing
380 FundingSpendConfirmation {
381 /// The CSV delay for the output of the funding spend transaction (implying it is a local
382 /// commitment transaction, and this is the delay on the to_self output).
383 on_local_output_csv: Option<u16>,
384 /// If the funding spend transaction was a known remote commitment transaction, we track
385 /// the output index and amount of the counterparty's `to_self` output here.
387 /// This allows us to generate a [`Balance::CounterpartyRevokedOutputClaimable`] for the
388 /// counterparty output.
389 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
391 /// A spend of a commitment transaction HTLC output, set in the cases where *no* `HTLCUpdate`
392 /// is constructed. This is used when
393 /// * an outbound HTLC is claimed by our counterparty with a preimage, causing us to
394 /// immediately claim the HTLC on the inbound edge and track the resolution here,
395 /// * an inbound HTLC is claimed by our counterparty (with a timeout),
396 /// * an inbound HTLC is claimed by us (with a preimage).
397 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by the revocation
399 /// * a revoked-state HTLC transaction was broadcasted, which was claimed by an
400 /// HTLC-Success/HTLC-Failure transaction (and is still claimable with a revocation
402 HTLCSpendConfirmation {
403 commitment_tx_output_idx: u32,
404 /// If the claim was made by either party with a preimage, this is filled in
405 preimage: Option<PaymentPreimage>,
406 /// If the claim was made by us on an inbound HTLC against a local commitment transaction,
407 /// we set this to the output CSV value which we will have to wait until to spend the
408 /// output (and generate a SpendableOutput event).
409 on_to_local_output_csv: Option<u16>,
413 impl Writeable for OnchainEventEntry {
414 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
415 write_tlv_fields!(writer, {
416 (0, self.txid, required),
417 (1, self.transaction, option),
418 (2, self.height, required),
419 (4, self.event, required),
425 impl MaybeReadable for OnchainEventEntry {
426 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
427 let mut txid = Txid::all_zeros();
428 let mut transaction = None;
430 let mut event = None;
431 read_tlv_fields!(reader, {
433 (1, transaction, option),
434 (2, height, required),
435 (4, event, ignorable),
437 if let Some(ev) = event {
438 Ok(Some(Self { txid, transaction, height, event: ev }))
445 impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
447 (0, source, required),
448 (1, htlc_value_satoshis, option),
449 (2, payment_hash, required),
450 (3, commitment_tx_output_idx, option),
452 (1, MaturingOutput) => {
453 (0, descriptor, required),
455 (3, FundingSpendConfirmation) => {
456 (0, on_local_output_csv, option),
457 (1, commitment_tx_to_counterparty_output, option),
459 (5, HTLCSpendConfirmation) => {
460 (0, commitment_tx_output_idx, required),
461 (2, preimage, option),
462 (4, on_to_local_output_csv, option),
467 #[cfg_attr(any(test, fuzzing, feature = "_test_utils"), derive(PartialEq))]
469 pub(crate) enum ChannelMonitorUpdateStep {
470 LatestHolderCommitmentTXInfo {
471 commitment_tx: HolderCommitmentTransaction,
472 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
474 LatestCounterpartyCommitmentTXInfo {
475 commitment_txid: Txid,
476 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
477 commitment_number: u64,
478 their_per_commitment_point: PublicKey,
481 payment_preimage: PaymentPreimage,
487 /// Used to indicate that the no future updates will occur, and likely that the latest holder
488 /// commitment transaction(s) should be broadcast, as the channel has been force-closed.
490 /// If set to false, we shouldn't broadcast the latest holder commitment transaction as we
491 /// think we've fallen behind!
492 should_broadcast: bool,
495 scriptpubkey: Script,
499 impl ChannelMonitorUpdateStep {
500 fn variant_name(&self) -> &'static str {
502 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
503 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
504 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
505 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
506 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
507 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
512 impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
513 (0, LatestHolderCommitmentTXInfo) => {
514 (0, commitment_tx, required),
515 (2, htlc_outputs, vec_type),
517 (1, LatestCounterpartyCommitmentTXInfo) => {
518 (0, commitment_txid, required),
519 (2, commitment_number, required),
520 (4, their_per_commitment_point, required),
521 (6, htlc_outputs, vec_type),
523 (2, PaymentPreimage) => {
524 (0, payment_preimage, required),
526 (3, CommitmentSecret) => {
528 (2, secret, required),
530 (4, ChannelForceClosed) => {
531 (0, should_broadcast, required),
533 (5, ShutdownScript) => {
534 (0, scriptpubkey, required),
538 /// Details about the balance(s) available for spending once the channel appears on chain.
540 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
542 #[derive(Clone, Debug, PartialEq, Eq)]
543 #[cfg_attr(test, derive(PartialOrd, Ord))]
545 /// The channel is not yet closed (or the commitment or closing transaction has not yet
546 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
547 /// force-closed now.
548 ClaimableOnChannelClose {
549 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
550 /// required to do so.
551 claimable_amount_satoshis: u64,
553 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
554 /// we consider it spendable.
555 ClaimableAwaitingConfirmations {
556 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
557 /// were spent in broadcasting the transaction.
558 claimable_amount_satoshis: u64,
559 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
561 confirmation_height: u32,
563 /// The channel has been closed, and the given balance should be ours but awaiting spending
564 /// transaction confirmation. If the spending transaction does not confirm in time, it is
565 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
567 /// Once the spending transaction confirms, before it has reached enough confirmations to be
568 /// considered safe from chain reorganizations, the balance will instead be provided via
569 /// [`Balance::ClaimableAwaitingConfirmations`].
570 ContentiousClaimable {
571 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
572 /// required to do so.
573 claimable_amount_satoshis: u64,
574 /// The height at which the counterparty may be able to claim the balance if we have not
578 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
579 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
580 /// likely to be claimed by our counterparty before we do.
581 MaybeTimeoutClaimableHTLC {
582 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
583 /// which will be required to do so.
584 claimable_amount_satoshis: u64,
585 /// The height at which we will be able to claim the balance if our counterparty has not
587 claimable_height: u32,
589 /// HTLCs which we received from our counterparty which are claimable with a preimage which we
590 /// do not currently have. This will only be claimable if we receive the preimage from the node
591 /// to which we forwarded this HTLC before the timeout.
592 MaybePreimageClaimableHTLC {
593 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
594 /// which will be required to do so.
595 claimable_amount_satoshis: u64,
596 /// The height at which our counterparty will be able to claim the balance if we have not
597 /// yet received the preimage and claimed it ourselves.
600 /// The channel has been closed, and our counterparty broadcasted a revoked commitment
603 /// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
604 /// following amount.
605 CounterpartyRevokedOutputClaimable {
606 /// The amount, in satoshis, of the output which we can claim.
608 /// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
609 /// were already spent.
610 claimable_amount_satoshis: u64,
614 /// An HTLC which has been irrevocably resolved on-chain, and has reached ANTI_REORG_DELAY.
616 struct IrrevocablyResolvedHTLC {
617 commitment_tx_output_idx: u32,
618 /// The txid of the transaction which resolved the HTLC, this may be a commitment (if the HTLC
619 /// was not present in the confirmed commitment transaction), HTLC-Success, or HTLC-Timeout
621 resolving_txid: Option<Txid>, // Added as optional, but always filled in, in 0.0.110
622 /// Only set if the HTLC claim was ours using a payment preimage
623 payment_preimage: Option<PaymentPreimage>,
626 impl_writeable_tlv_based!(IrrevocablyResolvedHTLC, {
627 (0, commitment_tx_output_idx, required),
628 (1, resolving_txid, option),
629 (2, payment_preimage, option),
632 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
633 /// on-chain transactions to ensure no loss of funds occurs.
635 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
636 /// information and are actively monitoring the chain.
638 /// Pending Events or updated HTLCs which have not yet been read out by
639 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
640 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
641 /// gotten are fully handled before re-serializing the new state.
643 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
644 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
645 /// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
646 /// returned block hash and the the current chain and then reconnecting blocks to get to the
647 /// best chain) upon deserializing the object!
648 pub struct ChannelMonitor<Signer: Sign> {
650 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
652 inner: Mutex<ChannelMonitorImpl<Signer>>,
655 pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
656 latest_update_id: u64,
657 commitment_transaction_number_obscure_factor: u64,
659 destination_script: Script,
660 broadcasted_holder_revokable_script: Option<(Script, PublicKey, PublicKey)>,
661 counterparty_payment_script: Script,
662 shutdown_script: Option<Script>,
664 channel_keys_id: [u8; 32],
665 holder_revocation_basepoint: PublicKey,
666 funding_info: (OutPoint, Script),
667 current_counterparty_commitment_txid: Option<Txid>,
668 prev_counterparty_commitment_txid: Option<Txid>,
670 counterparty_commitment_params: CounterpartyCommitmentParameters,
671 funding_redeemscript: Script,
672 channel_value_satoshis: u64,
673 // first is the idx of the first of the two per-commitment points
674 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
676 on_holder_tx_csv: u16,
678 commitment_secrets: CounterpartyCommitmentSecrets,
679 /// The set of outpoints in each counterparty commitment transaction. We always need at least
680 /// the payment hash from `HTLCOutputInCommitment` to claim even a revoked commitment
681 /// transaction broadcast as we need to be able to construct the witness script in all cases.
682 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
683 /// We cannot identify HTLC-Success or HTLC-Timeout transactions by themselves on the chain.
684 /// Nor can we figure out their commitment numbers without the commitment transaction they are
685 /// spending. Thus, in order to claim them via revocation key, we track all the counterparty
686 /// commitment transactions which we find on-chain, mapping them to the commitment number which
687 /// can be used to derive the revocation key and claim the transactions.
688 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
689 /// Cache used to make pruning of payment_preimages faster.
690 /// Maps payment_hash values to commitment numbers for counterparty transactions for non-revoked
691 /// counterparty transactions (ie should remain pretty small).
692 /// Serialized to disk but should generally not be sent to Watchtowers.
693 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
695 // We store two holder commitment transactions to avoid any race conditions where we may update
696 // some monitors (potentially on watchtowers) but then fail to update others, resulting in the
697 // various monitors for one channel being out of sync, and us broadcasting a holder
698 // transaction for which we have deleted claim information on some watchtowers.
699 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
700 current_holder_commitment_tx: HolderSignedTx,
702 // Used just for ChannelManager to make sure it has the latest channel data during
704 current_counterparty_commitment_number: u64,
705 // Used just for ChannelManager to make sure it has the latest channel data during
707 current_holder_commitment_number: u64,
709 /// The set of payment hashes from inbound payments for which we know the preimage. Payment
710 /// preimages that are not included in any unrevoked local commitment transaction or unrevoked
711 /// remote commitment transactions are automatically removed when commitment transactions are
713 payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
715 // Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
716 // during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
717 // presumably user implementations thereof as well) where we update the in-memory channel
718 // object, then before the persistence finishes (as it's all under a read-lock), we return
719 // pending events to the user or to the relevant `ChannelManager`. Then, on reload, we'll have
720 // the pre-event state here, but have processed the event in the `ChannelManager`.
721 // Note that because the `event_lock` in `ChainMonitor` is only taken in
722 // block/transaction-connected events and *not* during block/transaction-disconnected events,
723 // we further MUST NOT generate events during block/transaction-disconnection.
724 pending_monitor_events: Vec<MonitorEvent>,
726 pending_events: Vec<Event>,
728 // Used to track on-chain events (i.e., transactions part of channels confirmed on chain) on
729 // which to take actions once they reach enough confirmations. Each entry includes the
730 // transaction's id and the height when the transaction was confirmed on chain.
731 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
733 // If we get serialized out and re-read, we need to make sure that the chain monitoring
734 // interface knows about the TXOs that we want to be notified of spends of. We could probably
735 // be smart and derive them from the above storage fields, but its much simpler and more
736 // Obviously Correct (tm) if we just keep track of them explicitly.
737 outputs_to_watch: HashMap<Txid, Vec<(u32, Script)>>,
740 pub onchain_tx_handler: OnchainTxHandler<Signer>,
742 onchain_tx_handler: OnchainTxHandler<Signer>,
744 // This is set when the Channel[Manager] generated a ChannelMonitorUpdate which indicated the
745 // channel has been force-closed. After this is set, no further holder commitment transaction
746 // updates may occur, and we panic!() if one is provided.
747 lockdown_from_offchain: bool,
749 // Set once we've signed a holder commitment transaction and handed it over to our
750 // OnchainTxHandler. After this is set, no future updates to our holder commitment transactions
751 // may occur, and we fail any such monitor updates.
753 // In case of update rejection due to a locally already signed commitment transaction, we
754 // nevertheless store update content to track in case of concurrent broadcast by another
755 // remote monitor out-of-order with regards to the block view.
756 holder_tx_signed: bool,
758 // If a spend of the funding output is seen, we set this to true and reject any further
759 // updates. This prevents any further changes in the offchain state no matter the order
760 // of block connection between ChannelMonitors and the ChannelManager.
761 funding_spend_seen: bool,
763 funding_spend_confirmed: Option<Txid>,
764 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
765 /// The set of HTLCs which have been either claimed or failed on chain and have reached
766 /// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
767 /// spending CSV for revocable outputs).
768 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
770 // We simply modify best_block in Channel's block_connected so that serialization is
771 // consistent but hopefully the users' copy handles block_connected in a consistent way.
772 // (we do *not*, however, update them in update_monitor to ensure any local user copies keep
773 // their best_block from its state and not based on updated copies that didn't run through
774 // the full block_connected).
775 best_block: BestBlock,
777 /// The node_id of our counterparty
778 counterparty_node_id: Option<PublicKey>,
780 secp_ctx: Secp256k1<secp256k1::All>, //TODO: dedup this a bit...
783 /// Transaction outputs to watch for on-chain spends.
784 pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
786 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
787 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
789 impl<Signer: Sign> PartialEq for ChannelMonitor<Signer> {
790 fn eq(&self, other: &Self) -> bool {
791 let inner = self.inner.lock().unwrap();
792 let other = other.inner.lock().unwrap();
797 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
798 /// Used only in testing and fuzzing to check serialization roundtrips don't change the underlying
800 impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
801 fn eq(&self, other: &Self) -> bool {
802 if self.latest_update_id != other.latest_update_id ||
803 self.commitment_transaction_number_obscure_factor != other.commitment_transaction_number_obscure_factor ||
804 self.destination_script != other.destination_script ||
805 self.broadcasted_holder_revokable_script != other.broadcasted_holder_revokable_script ||
806 self.counterparty_payment_script != other.counterparty_payment_script ||
807 self.channel_keys_id != other.channel_keys_id ||
808 self.holder_revocation_basepoint != other.holder_revocation_basepoint ||
809 self.funding_info != other.funding_info ||
810 self.current_counterparty_commitment_txid != other.current_counterparty_commitment_txid ||
811 self.prev_counterparty_commitment_txid != other.prev_counterparty_commitment_txid ||
812 self.counterparty_commitment_params != other.counterparty_commitment_params ||
813 self.funding_redeemscript != other.funding_redeemscript ||
814 self.channel_value_satoshis != other.channel_value_satoshis ||
815 self.their_cur_per_commitment_points != other.their_cur_per_commitment_points ||
816 self.on_holder_tx_csv != other.on_holder_tx_csv ||
817 self.commitment_secrets != other.commitment_secrets ||
818 self.counterparty_claimable_outpoints != other.counterparty_claimable_outpoints ||
819 self.counterparty_commitment_txn_on_chain != other.counterparty_commitment_txn_on_chain ||
820 self.counterparty_hash_commitment_number != other.counterparty_hash_commitment_number ||
821 self.prev_holder_signed_commitment_tx != other.prev_holder_signed_commitment_tx ||
822 self.current_counterparty_commitment_number != other.current_counterparty_commitment_number ||
823 self.current_holder_commitment_number != other.current_holder_commitment_number ||
824 self.current_holder_commitment_tx != other.current_holder_commitment_tx ||
825 self.payment_preimages != other.payment_preimages ||
826 self.pending_monitor_events != other.pending_monitor_events ||
827 self.pending_events.len() != other.pending_events.len() || // We trust events to round-trip properly
828 self.onchain_events_awaiting_threshold_conf != other.onchain_events_awaiting_threshold_conf ||
829 self.outputs_to_watch != other.outputs_to_watch ||
830 self.lockdown_from_offchain != other.lockdown_from_offchain ||
831 self.holder_tx_signed != other.holder_tx_signed ||
832 self.funding_spend_seen != other.funding_spend_seen ||
833 self.funding_spend_confirmed != other.funding_spend_confirmed ||
834 self.confirmed_commitment_tx_counterparty_output != other.confirmed_commitment_tx_counterparty_output ||
835 self.htlcs_resolved_on_chain != other.htlcs_resolved_on_chain
844 impl<Signer: Sign> Writeable for ChannelMonitor<Signer> {
845 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
846 self.inner.lock().unwrap().write(writer)
850 // These are also used for ChannelMonitorUpdate, above.
851 const SERIALIZATION_VERSION: u8 = 1;
852 const MIN_SERIALIZATION_VERSION: u8 = 1;
854 impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
855 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
856 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
858 self.latest_update_id.write(writer)?;
860 // Set in initial Channel-object creation, so should always be set by now:
861 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
863 self.destination_script.write(writer)?;
864 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
865 writer.write_all(&[0; 1])?;
866 broadcasted_holder_revokable_script.0.write(writer)?;
867 broadcasted_holder_revokable_script.1.write(writer)?;
868 broadcasted_holder_revokable_script.2.write(writer)?;
870 writer.write_all(&[1; 1])?;
873 self.counterparty_payment_script.write(writer)?;
874 match &self.shutdown_script {
875 Some(script) => script.write(writer)?,
876 None => Script::new().write(writer)?,
879 self.channel_keys_id.write(writer)?;
880 self.holder_revocation_basepoint.write(writer)?;
881 writer.write_all(&self.funding_info.0.txid[..])?;
882 writer.write_all(&byte_utils::be16_to_array(self.funding_info.0.index))?;
883 self.funding_info.1.write(writer)?;
884 self.current_counterparty_commitment_txid.write(writer)?;
885 self.prev_counterparty_commitment_txid.write(writer)?;
887 self.counterparty_commitment_params.write(writer)?;
888 self.funding_redeemscript.write(writer)?;
889 self.channel_value_satoshis.write(writer)?;
891 match self.their_cur_per_commitment_points {
892 Some((idx, pubkey, second_option)) => {
893 writer.write_all(&byte_utils::be48_to_array(idx))?;
894 writer.write_all(&pubkey.serialize())?;
895 match second_option {
896 Some(second_pubkey) => {
897 writer.write_all(&second_pubkey.serialize())?;
900 writer.write_all(&[0; 33])?;
905 writer.write_all(&byte_utils::be48_to_array(0))?;
909 writer.write_all(&byte_utils::be16_to_array(self.on_holder_tx_csv))?;
911 self.commitment_secrets.write(writer)?;
913 macro_rules! serialize_htlc_in_commitment {
914 ($htlc_output: expr) => {
915 writer.write_all(&[$htlc_output.offered as u8; 1])?;
916 writer.write_all(&byte_utils::be64_to_array($htlc_output.amount_msat))?;
917 writer.write_all(&byte_utils::be32_to_array($htlc_output.cltv_expiry))?;
918 writer.write_all(&$htlc_output.payment_hash.0[..])?;
919 $htlc_output.transaction_output_index.write(writer)?;
923 writer.write_all(&byte_utils::be64_to_array(self.counterparty_claimable_outpoints.len() as u64))?;
924 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
925 writer.write_all(&txid[..])?;
926 writer.write_all(&byte_utils::be64_to_array(htlc_infos.len() as u64))?;
927 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
928 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
929 || Some(**txid) == self.prev_counterparty_commitment_txid,
930 "HTLC Sources for all revoked commitment transactions should be none!");
931 serialize_htlc_in_commitment!(htlc_output);
932 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
936 writer.write_all(&byte_utils::be64_to_array(self.counterparty_commitment_txn_on_chain.len() as u64))?;
937 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
938 writer.write_all(&txid[..])?;
939 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
942 writer.write_all(&byte_utils::be64_to_array(self.counterparty_hash_commitment_number.len() as u64))?;
943 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
944 writer.write_all(&payment_hash.0[..])?;
945 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
948 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
949 writer.write_all(&[1; 1])?;
950 prev_holder_tx.write(writer)?;
952 writer.write_all(&[0; 1])?;
955 self.current_holder_commitment_tx.write(writer)?;
957 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
958 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
960 writer.write_all(&byte_utils::be64_to_array(self.payment_preimages.len() as u64))?;
961 for payment_preimage in self.payment_preimages.values() {
962 writer.write_all(&payment_preimage.0[..])?;
965 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
966 MonitorEvent::HTLCEvent(_) => true,
967 MonitorEvent::CommitmentTxConfirmed(_) => true,
969 }).count() as u64).to_be_bytes())?;
970 for event in self.pending_monitor_events.iter() {
972 MonitorEvent::HTLCEvent(upd) => {
976 MonitorEvent::CommitmentTxConfirmed(_) => 1u8.write(writer)?,
977 _ => {}, // Covered in the TLV writes below
981 writer.write_all(&byte_utils::be64_to_array(self.pending_events.len() as u64))?;
982 for event in self.pending_events.iter() {
983 event.write(writer)?;
986 self.best_block.block_hash().write(writer)?;
987 writer.write_all(&byte_utils::be32_to_array(self.best_block.height()))?;
989 writer.write_all(&byte_utils::be64_to_array(self.onchain_events_awaiting_threshold_conf.len() as u64))?;
990 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
991 entry.write(writer)?;
994 (self.outputs_to_watch.len() as u64).write(writer)?;
995 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
997 (idx_scripts.len() as u64).write(writer)?;
998 for (idx, script) in idx_scripts.iter() {
1000 script.write(writer)?;
1003 self.onchain_tx_handler.write(writer)?;
1005 self.lockdown_from_offchain.write(writer)?;
1006 self.holder_tx_signed.write(writer)?;
1008 write_tlv_fields!(writer, {
1009 (1, self.funding_spend_confirmed, option),
1010 (3, self.htlcs_resolved_on_chain, vec_type),
1011 (5, self.pending_monitor_events, vec_type),
1012 (7, self.funding_spend_seen, required),
1013 (9, self.counterparty_node_id, option),
1014 (11, self.confirmed_commitment_tx_counterparty_output, option),
1021 impl<Signer: Sign> ChannelMonitor<Signer> {
1022 /// For lockorder enforcement purposes, we need to have a single site which constructs the
1023 /// `inner` mutex, otherwise cases where we lock two monitors at the same time (eg in our
1024 /// PartialEq implementation) we may decide a lockorder violation has occurred.
1025 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1026 ChannelMonitor { inner: Mutex::new(imp) }
1029 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<Script>,
1030 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, Script),
1031 channel_parameters: &ChannelTransactionParameters,
1032 funding_redeemscript: Script, channel_value_satoshis: u64,
1033 commitment_transaction_number_obscure_factor: u64,
1034 initial_holder_commitment_tx: HolderCommitmentTransaction,
1035 best_block: BestBlock, counterparty_node_id: PublicKey) -> ChannelMonitor<Signer> {
1037 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1038 let payment_key_hash = WPubkeyHash::hash(&keys.pubkeys().payment_point.serialize());
1039 let counterparty_payment_script = Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&payment_key_hash[..]).into_script();
1041 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1042 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1043 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1044 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1046 let channel_keys_id = keys.channel_keys_id();
1047 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1049 // block for Rust 1.34 compat
1050 let (holder_commitment_tx, current_holder_commitment_number) = {
1051 let trusted_tx = initial_holder_commitment_tx.trust();
1052 let txid = trusted_tx.txid();
1054 let tx_keys = trusted_tx.keys();
1055 let holder_commitment_tx = HolderSignedTx {
1057 revocation_key: tx_keys.revocation_key,
1058 a_htlc_key: tx_keys.broadcaster_htlc_key,
1059 b_htlc_key: tx_keys.countersignatory_htlc_key,
1060 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1061 per_commitment_point: tx_keys.per_commitment_point,
1062 htlc_outputs: Vec::new(), // There are never any HTLCs in the initial commitment transactions
1063 to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1064 feerate_per_kw: trusted_tx.feerate_per_kw(),
1066 (holder_commitment_tx, trusted_tx.commitment_number())
1069 let onchain_tx_handler =
1070 OnchainTxHandler::new(destination_script.clone(), keys,
1071 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx.clone());
1073 let mut outputs_to_watch = HashMap::new();
1074 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1076 Self::from_impl(ChannelMonitorImpl {
1077 latest_update_id: 0,
1078 commitment_transaction_number_obscure_factor,
1080 destination_script: destination_script.clone(),
1081 broadcasted_holder_revokable_script: None,
1082 counterparty_payment_script,
1086 holder_revocation_basepoint,
1088 current_counterparty_commitment_txid: None,
1089 prev_counterparty_commitment_txid: None,
1091 counterparty_commitment_params,
1092 funding_redeemscript,
1093 channel_value_satoshis,
1094 their_cur_per_commitment_points: None,
1096 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1098 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1099 counterparty_claimable_outpoints: HashMap::new(),
1100 counterparty_commitment_txn_on_chain: HashMap::new(),
1101 counterparty_hash_commitment_number: HashMap::new(),
1103 prev_holder_signed_commitment_tx: None,
1104 current_holder_commitment_tx: holder_commitment_tx,
1105 current_counterparty_commitment_number: 1 << 48,
1106 current_holder_commitment_number,
1108 payment_preimages: HashMap::new(),
1109 pending_monitor_events: Vec::new(),
1110 pending_events: Vec::new(),
1112 onchain_events_awaiting_threshold_conf: Vec::new(),
1117 lockdown_from_offchain: false,
1118 holder_tx_signed: false,
1119 funding_spend_seen: false,
1120 funding_spend_confirmed: None,
1121 confirmed_commitment_tx_counterparty_output: None,
1122 htlcs_resolved_on_chain: Vec::new(),
1125 counterparty_node_id: Some(counterparty_node_id),
1132 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1133 self.inner.lock().unwrap().provide_secret(idx, secret)
1136 /// Informs this monitor of the latest counterparty (ie non-broadcastable) commitment transaction.
1137 /// The monitor watches for it to be broadcasted and then uses the HTLC information (and
1138 /// possibly future revocation/preimage information) to claim outputs where possible.
1139 /// We cache also the mapping hash:commitment number to lighten pruning of old preimages by watchtowers.
1140 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(
1143 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1144 commitment_number: u64,
1145 their_per_commitment_point: PublicKey,
1147 ) where L::Target: Logger {
1148 self.inner.lock().unwrap().provide_latest_counterparty_commitment_tx(
1149 txid, htlc_outputs, commitment_number, their_per_commitment_point, logger)
1153 fn provide_latest_holder_commitment_tx(
1154 &self, holder_commitment_tx: HolderCommitmentTransaction,
1155 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1156 ) -> Result<(), ()> {
1157 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs).map_err(|_| ())
1160 /// This is used to provide payment preimage(s) out-of-band during startup without updating the
1161 /// off-chain state with a new commitment transaction.
1162 pub(crate) fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
1164 payment_hash: &PaymentHash,
1165 payment_preimage: &PaymentPreimage,
1167 fee_estimator: &LowerBoundedFeeEstimator<F>,
1170 B::Target: BroadcasterInterface,
1171 F::Target: FeeEstimator,
1174 self.inner.lock().unwrap().provide_payment_preimage(
1175 payment_hash, payment_preimage, broadcaster, fee_estimator, logger)
1178 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(
1183 B::Target: BroadcasterInterface,
1186 self.inner.lock().unwrap().broadcast_latest_holder_commitment_txn(broadcaster, logger)
1189 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
1192 /// panics if the given update is not the next update by update_id.
1193 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1195 updates: &ChannelMonitorUpdate,
1201 B::Target: BroadcasterInterface,
1202 F::Target: FeeEstimator,
1205 self.inner.lock().unwrap().update_monitor(updates, broadcaster, fee_estimator, logger)
1208 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
1210 pub fn get_latest_update_id(&self) -> u64 {
1211 self.inner.lock().unwrap().get_latest_update_id()
1214 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
1215 pub fn get_funding_txo(&self) -> (OutPoint, Script) {
1216 self.inner.lock().unwrap().get_funding_txo().clone()
1219 /// Gets a list of txids, with their output scripts (in the order they appear in the
1220 /// transaction), which we must learn about spends of via block_connected().
1221 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, Script)>)> {
1222 self.inner.lock().unwrap().get_outputs_to_watch()
1223 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1226 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
1227 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
1228 /// have been registered.
1229 pub fn load_outputs_to_watch<F: Deref>(&self, filter: &F) where F::Target: chain::Filter {
1230 let lock = self.inner.lock().unwrap();
1231 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1232 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1233 for (index, script_pubkey) in outputs.iter() {
1234 assert!(*index <= u16::max_value() as u32);
1235 filter.register_output(WatchedOutput {
1237 outpoint: OutPoint { txid: *txid, index: *index as u16 },
1238 script_pubkey: script_pubkey.clone(),
1244 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
1245 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
1246 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1247 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1250 /// Gets the list of pending events which were generated by previous actions, clearing the list
1253 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
1254 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
1255 /// no internal locking in ChannelMonitors.
1256 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1257 self.inner.lock().unwrap().get_and_clear_pending_events()
1260 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1261 self.inner.lock().unwrap().get_min_seen_secret()
1264 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1265 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1268 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1269 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1272 /// Gets the `node_id` of the counterparty for this channel.
1274 /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1276 pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1277 self.inner.lock().unwrap().counterparty_node_id
1280 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
1281 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
1282 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
1283 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
1284 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
1285 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
1286 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
1287 /// out-of-band the other node operator to coordinate with him if option is available to you.
1288 /// In any-case, choice is up to the user.
1289 pub fn get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1290 where L::Target: Logger {
1291 self.inner.lock().unwrap().get_latest_holder_commitment_txn(logger)
1294 /// Unsafe test-only version of get_latest_holder_commitment_txn used by our test framework
1295 /// to bypass HolderCommitmentTransaction state update lockdown after signature and generate
1296 /// revoked commitment transaction.
1297 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1298 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1299 where L::Target: Logger {
1300 self.inner.lock().unwrap().unsafe_get_latest_holder_commitment_txn(logger)
1303 /// Processes transactions in a newly connected block, which may result in any of the following:
1304 /// - update the monitor's state against resolved HTLCs
1305 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1306 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1307 /// - detect settled outputs for later spending
1308 /// - schedule and bump any in-flight claims
1310 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1311 /// [`get_outputs_to_watch`].
1313 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1314 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1316 header: &BlockHeader,
1317 txdata: &TransactionData,
1322 ) -> Vec<TransactionOutputs>
1324 B::Target: BroadcasterInterface,
1325 F::Target: FeeEstimator,
1328 self.inner.lock().unwrap().block_connected(
1329 header, txdata, height, broadcaster, fee_estimator, logger)
1332 /// Determines if the disconnected block contained any transactions of interest and updates
1334 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1336 header: &BlockHeader,
1342 B::Target: BroadcasterInterface,
1343 F::Target: FeeEstimator,
1346 self.inner.lock().unwrap().block_disconnected(
1347 header, height, broadcaster, fee_estimator, logger)
1350 /// Processes transactions confirmed in a block with the given header and height, returning new
1351 /// outputs to watch. See [`block_connected`] for details.
1353 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1354 /// blocks. See [`chain::Confirm`] for calling expectations.
1356 /// [`block_connected`]: Self::block_connected
1357 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1359 header: &BlockHeader,
1360 txdata: &TransactionData,
1365 ) -> Vec<TransactionOutputs>
1367 B::Target: BroadcasterInterface,
1368 F::Target: FeeEstimator,
1371 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1372 self.inner.lock().unwrap().transactions_confirmed(
1373 header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
1376 /// Processes a transaction that was reorganized out of the chain.
1378 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1379 /// than blocks. See [`chain::Confirm`] for calling expectations.
1381 /// [`block_disconnected`]: Self::block_disconnected
1382 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1389 B::Target: BroadcasterInterface,
1390 F::Target: FeeEstimator,
1393 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1394 self.inner.lock().unwrap().transaction_unconfirmed(
1395 txid, broadcaster, &bounded_fee_estimator, logger);
1398 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1399 /// [`block_connected`] for details.
1401 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1402 /// blocks. See [`chain::Confirm`] for calling expectations.
1404 /// [`block_connected`]: Self::block_connected
1405 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1407 header: &BlockHeader,
1412 ) -> Vec<TransactionOutputs>
1414 B::Target: BroadcasterInterface,
1415 F::Target: FeeEstimator,
1418 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1419 self.inner.lock().unwrap().best_block_updated(
1420 header, height, broadcaster, &bounded_fee_estimator, logger)
1423 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1424 pub fn get_relevant_txids(&self) -> Vec<Txid> {
1425 let inner = self.inner.lock().unwrap();
1426 let mut txids: Vec<Txid> = inner.onchain_events_awaiting_threshold_conf
1428 .map(|entry| entry.txid)
1429 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1431 txids.sort_unstable();
1436 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1437 /// [`chain::Confirm`] interfaces.
1438 pub fn current_best_block(&self) -> BestBlock {
1439 self.inner.lock().unwrap().best_block.clone()
1443 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1444 /// Helper for get_claimable_balances which does the work for an individual HTLC, generating up
1445 /// to one `Balance` for the HTLC.
1446 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, holder_commitment: bool,
1447 counterparty_revoked_commitment: bool, confirmed_txid: Option<Txid>)
1448 -> Option<Balance> {
1449 let htlc_commitment_tx_output_idx =
1450 if let Some(v) = htlc.transaction_output_index { v } else { return None; };
1452 let mut htlc_spend_txid_opt = None;
1453 let mut holder_timeout_spend_pending = None;
1454 let mut htlc_spend_pending = None;
1455 let mut holder_delayed_output_pending = None;
1456 for event in self.onchain_events_awaiting_threshold_conf.iter() {
1458 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
1459 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
1460 debug_assert!(htlc_spend_txid_opt.is_none());
1461 htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
1462 debug_assert!(holder_timeout_spend_pending.is_none());
1463 debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
1464 holder_timeout_spend_pending = Some(event.confirmation_threshold());
1466 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
1467 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
1468 debug_assert!(htlc_spend_txid_opt.is_none());
1469 htlc_spend_txid_opt = event.transaction.as_ref().map(|tx| tx.txid());
1470 debug_assert!(htlc_spend_pending.is_none());
1471 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
1473 OnchainEvent::MaturingOutput {
1474 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
1475 if descriptor.outpoint.index as u32 == htlc_commitment_tx_output_idx => {
1476 debug_assert!(holder_delayed_output_pending.is_none());
1477 holder_delayed_output_pending = Some(event.confirmation_threshold());
1482 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
1483 .find(|v| if v.commitment_tx_output_idx == htlc_commitment_tx_output_idx {
1484 debug_assert!(htlc_spend_txid_opt.is_none());
1485 htlc_spend_txid_opt = v.resolving_txid;
1488 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved.is_some() as u8 <= 1);
1490 let htlc_output_to_spend =
1491 if let Some(txid) = htlc_spend_txid_opt {
1493 self.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_none(),
1494 "This code needs updating for anchors");
1495 BitcoinOutPoint::new(txid, 0)
1497 BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx)
1499 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
1501 if let Some(conf_thresh) = holder_delayed_output_pending {
1502 debug_assert!(holder_commitment);
1503 return Some(Balance::ClaimableAwaitingConfirmations {
1504 claimable_amount_satoshis: htlc.amount_msat / 1000,
1505 confirmation_height: conf_thresh,
1507 } else if htlc_resolved.is_some() && !htlc_output_spend_pending {
1508 // Funding transaction spends should be fully confirmed by the time any
1509 // HTLC transactions are resolved, unless we're talking about a holder
1510 // commitment tx, whose resolution is delayed until the CSV timeout is
1511 // reached, even though HTLCs may be resolved after only
1512 // ANTI_REORG_DELAY confirmations.
1513 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
1514 } else if counterparty_revoked_commitment {
1515 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1516 if let OnchainEvent::MaturingOutput {
1517 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
1519 if event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
1520 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
1521 Some(tx.txid()) == htlc_spend_txid_opt ||
1522 inp.previous_output.txid == htlc_spend_txid
1524 Some(inp.previous_output.txid) == confirmed_txid &&
1525 inp.previous_output.vout == htlc_commitment_tx_output_idx
1527 })).unwrap_or(false) {
1532 if htlc_output_claim_pending.is_some() {
1533 // We already push `Balance`s onto the `res` list for every
1534 // `StaticOutput` in a `MaturingOutput` in the revoked
1535 // counterparty commitment transaction case generally, so don't
1536 // need to do so again here.
1538 debug_assert!(holder_timeout_spend_pending.is_none(),
1539 "HTLCUpdate OnchainEvents should never appear for preimage claims");
1540 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
1541 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
1542 return Some(Balance::CounterpartyRevokedOutputClaimable {
1543 claimable_amount_satoshis: htlc.amount_msat / 1000,
1546 } else if htlc.offered == holder_commitment {
1547 // If the payment was outbound, check if there's an HTLCUpdate
1548 // indicating we have spent this HTLC with a timeout, claiming it back
1549 // and awaiting confirmations on it.
1550 if let Some(conf_thresh) = holder_timeout_spend_pending {
1551 return Some(Balance::ClaimableAwaitingConfirmations {
1552 claimable_amount_satoshis: htlc.amount_msat / 1000,
1553 confirmation_height: conf_thresh,
1556 return Some(Balance::MaybeTimeoutClaimableHTLC {
1557 claimable_amount_satoshis: htlc.amount_msat / 1000,
1558 claimable_height: htlc.cltv_expiry,
1561 } else if self.payment_preimages.get(&htlc.payment_hash).is_some() {
1562 // Otherwise (the payment was inbound), only expose it as claimable if
1563 // we know the preimage.
1564 // Note that if there is a pending claim, but it did not use the
1565 // preimage, we lost funds to our counterparty! We will then continue
1566 // to show it as ContentiousClaimable until ANTI_REORG_DELAY.
1567 debug_assert!(holder_timeout_spend_pending.is_none());
1568 if let Some((conf_thresh, true)) = htlc_spend_pending {
1569 return Some(Balance::ClaimableAwaitingConfirmations {
1570 claimable_amount_satoshis: htlc.amount_msat / 1000,
1571 confirmation_height: conf_thresh,
1574 return Some(Balance::ContentiousClaimable {
1575 claimable_amount_satoshis: htlc.amount_msat / 1000,
1576 timeout_height: htlc.cltv_expiry,
1579 } else if htlc_resolved.is_none() {
1580 return Some(Balance::MaybePreimageClaimableHTLC {
1581 claimable_amount_satoshis: htlc.amount_msat / 1000,
1582 expiry_height: htlc.cltv_expiry,
1589 impl<Signer: Sign> ChannelMonitor<Signer> {
1590 /// Gets the balances in this channel which are either claimable by us if we were to
1591 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1594 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1595 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1596 /// balance, or until our counterparty has claimed the balance and accrued several
1597 /// confirmations on the claim transaction.
1599 /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1600 /// LDK prior to 0.0.108, balances may not be fully captured if our counterparty broadcasted
1601 /// a revoked state.
1603 /// See [`Balance`] for additional details on the types of claimable balances which
1604 /// may be returned here and their meanings.
1605 pub fn get_claimable_balances(&self) -> Vec<Balance> {
1606 let mut res = Vec::new();
1607 let us = self.inner.lock().unwrap();
1609 let mut confirmed_txid = us.funding_spend_confirmed;
1610 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
1611 let mut pending_commitment_tx_conf_thresh = None;
1612 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1613 if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
1616 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
1617 Some((event.txid, event.confirmation_threshold()))
1620 if let Some((txid, conf_thresh)) = funding_spend_pending {
1621 debug_assert!(us.funding_spend_confirmed.is_none(),
1622 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
1623 confirmed_txid = Some(txid);
1624 pending_commitment_tx_conf_thresh = Some(conf_thresh);
1627 macro_rules! walk_htlcs {
1628 ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
1629 for htlc in $htlc_iter {
1630 if htlc.transaction_output_index.is_some() {
1632 if let Some(bal) = us.get_htlc_balance(htlc, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid) {
1640 if let Some(txid) = confirmed_txid {
1641 let mut found_commitment_tx = false;
1642 if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
1643 // First look for the to_remote output back to us.
1644 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1645 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1646 if let OnchainEvent::MaturingOutput {
1647 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
1649 Some(descriptor.output.value)
1652 res.push(Balance::ClaimableAwaitingConfirmations {
1653 claimable_amount_satoshis: value,
1654 confirmation_height: conf_thresh,
1657 // If a counterparty commitment transaction is awaiting confirmation, we
1658 // should either have a StaticPaymentOutput MaturingOutput event awaiting
1659 // confirmation with the same height or have never met our dust amount.
1662 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1663 walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1665 walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, _)| a));
1666 // The counterparty broadcasted a revoked state!
1667 // Look for any StaticOutputs first, generating claimable balances for those.
1668 // If any match the confirmed counterparty revoked to_self output, skip
1669 // generating a CounterpartyRevokedOutputClaimable.
1670 let mut spent_counterparty_output = false;
1671 for event in us.onchain_events_awaiting_threshold_conf.iter() {
1672 if let OnchainEvent::MaturingOutput {
1673 descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
1675 res.push(Balance::ClaimableAwaitingConfirmations {
1676 claimable_amount_satoshis: output.value,
1677 confirmation_height: event.confirmation_threshold(),
1679 if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
1680 if event.transaction.as_ref().map(|tx|
1681 tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
1682 ).unwrap_or(false) {
1683 spent_counterparty_output = true;
1689 if spent_counterparty_output {
1690 } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
1691 let output_spendable = us.onchain_tx_handler
1692 .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
1693 if output_spendable {
1694 res.push(Balance::CounterpartyRevokedOutputClaimable {
1695 claimable_amount_satoshis: amt,
1699 // Counterparty output is missing, either it was broadcasted on a
1700 // previous version of LDK or the counterparty hadn't met dust.
1703 found_commitment_tx = true;
1704 } else if txid == us.current_holder_commitment_tx.txid {
1705 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, _)| a));
1706 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1707 res.push(Balance::ClaimableAwaitingConfirmations {
1708 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1709 confirmation_height: conf_thresh,
1712 found_commitment_tx = true;
1713 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1714 if txid == prev_commitment.txid {
1715 walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, _)| a));
1716 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1717 res.push(Balance::ClaimableAwaitingConfirmations {
1718 claimable_amount_satoshis: prev_commitment.to_self_value_sat,
1719 confirmation_height: conf_thresh,
1722 found_commitment_tx = true;
1725 if !found_commitment_tx {
1726 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
1727 // We blindly assume this is a cooperative close transaction here, and that
1728 // neither us nor our counterparty misbehaved. At worst we've under-estimated
1729 // the amount we can claim as we'll punish a misbehaving counterparty.
1730 res.push(Balance::ClaimableAwaitingConfirmations {
1731 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
1732 confirmation_height: conf_thresh,
1737 let mut claimable_inbound_htlc_value_sat = 0;
1738 for (htlc, _, _) in us.current_holder_commitment_tx.htlc_outputs.iter() {
1739 if htlc.transaction_output_index.is_none() { continue; }
1741 res.push(Balance::MaybeTimeoutClaimableHTLC {
1742 claimable_amount_satoshis: htlc.amount_msat / 1000,
1743 claimable_height: htlc.cltv_expiry,
1745 } else if us.payment_preimages.get(&htlc.payment_hash).is_some() {
1746 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
1748 // As long as the HTLC is still in our latest commitment state, treat
1749 // it as potentially claimable, even if it has long-since expired.
1750 res.push(Balance::MaybePreimageClaimableHTLC {
1751 claimable_amount_satoshis: htlc.amount_msat / 1000,
1752 expiry_height: htlc.cltv_expiry,
1756 res.push(Balance::ClaimableOnChannelClose {
1757 claimable_amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
1764 /// Gets the set of outbound HTLCs which are pending resolution in this channel.
1765 /// This is used to reconstruct pending outbound payments on restart in the ChannelManager.
1766 pub(crate) fn get_pending_outbound_htlcs(&self) -> HashMap<HTLCSource, HTLCOutputInCommitment> {
1767 let mut res = HashMap::new();
1768 let us = self.inner.lock().unwrap();
1770 macro_rules! walk_htlcs {
1771 ($holder_commitment: expr, $htlc_iter: expr) => {
1772 for (htlc, source) in $htlc_iter {
1773 if us.htlcs_resolved_on_chain.iter().any(|v| Some(v.commitment_tx_output_idx) == htlc.transaction_output_index) {
1774 // We should assert that funding_spend_confirmed is_some() here, but we
1775 // have some unit tests which violate HTLC transaction CSVs entirely and
1777 // TODO: Once tests all connect transactions at consensus-valid times, we
1778 // should assert here like we do in `get_claimable_balances`.
1779 } else if htlc.offered == $holder_commitment {
1780 // If the payment was outbound, check if there's an HTLCUpdate
1781 // indicating we have spent this HTLC with a timeout, claiming it back
1782 // and awaiting confirmations on it.
1783 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
1784 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
1785 // If the HTLC was timed out, we wait for ANTI_REORG_DELAY blocks
1786 // before considering it "no longer pending" - this matches when we
1787 // provide the ChannelManager an HTLC failure event.
1788 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
1789 us.best_block.height() >= event.height + ANTI_REORG_DELAY - 1
1790 } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
1791 // If the HTLC was fulfilled with a preimage, we consider the HTLC
1792 // immediately non-pending, matching when we provide ChannelManager
1794 Some(commitment_tx_output_idx) == htlc.transaction_output_index
1797 if !htlc_update_confd {
1798 res.insert(source.clone(), htlc.clone());
1805 // We're only concerned with the confirmation count of HTLC transactions, and don't
1806 // actually care how many confirmations a commitment transaction may or may not have. Thus,
1807 // we look for either a FundingSpendConfirmation event or a funding_spend_confirmed.
1808 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
1809 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
1810 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
1815 if let Some(txid) = confirmed_txid {
1816 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
1817 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
1818 if let &Some(ref source) = b {
1819 Some((a, &**source))
1822 } else if txid == us.current_holder_commitment_tx.txid {
1823 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
1824 if let Some(source) = c { Some((a, source)) } else { None }
1826 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
1827 if txid == prev_commitment.txid {
1828 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
1829 if let Some(source) = c { Some((a, source)) } else { None }
1834 // If we have not seen a commitment transaction on-chain (ie the channel is not yet
1835 // closed), just examine the available counterparty commitment transactions. See docs
1836 // on `fail_unbroadcast_htlcs`, below, for justification.
1837 macro_rules! walk_counterparty_commitment {
1839 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
1840 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1841 if let &Some(ref source) = source_option {
1842 res.insert((**source).clone(), htlc.clone());
1848 if let Some(ref txid) = us.current_counterparty_commitment_txid {
1849 walk_counterparty_commitment!(txid);
1851 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
1852 walk_counterparty_commitment!(txid);
1859 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, PaymentPreimage> {
1860 self.inner.lock().unwrap().payment_preimages.clone()
1864 /// Compares a broadcasted commitment transaction's HTLCs with those in the latest state,
1865 /// failing any HTLCs which didn't make it into the broadcasted commitment transaction back
1866 /// after ANTI_REORG_DELAY blocks.
1868 /// We always compare against the set of HTLCs in counterparty commitment transactions, as those
1869 /// are the commitment transactions which are generated by us. The off-chain state machine in
1870 /// `Channel` will automatically resolve any HTLCs which were never included in a commitment
1871 /// transaction when it detects channel closure, but it is up to us to ensure any HTLCs which were
1872 /// included in a remote commitment transaction are failed back if they are not present in the
1873 /// broadcasted commitment transaction.
1875 /// Specifically, the removal process for HTLCs in `Channel` is always based on the counterparty
1876 /// sending a `revoke_and_ack`, which causes us to clear `prev_counterparty_commitment_txid`. Thus,
1877 /// as long as we examine both the current counterparty commitment transaction and, if it hasn't
1878 /// been revoked yet, the previous one, we we will never "forget" to resolve an HTLC.
1879 macro_rules! fail_unbroadcast_htlcs {
1880 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
1881 $commitment_tx_conf_height: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
1882 debug_assert_eq!($commitment_tx_confirmed.txid(), $commitment_txid_confirmed);
1884 macro_rules! check_htlc_fails {
1885 ($txid: expr, $commitment_tx: expr) => {
1886 if let Some(ref latest_outpoints) = $self.counterparty_claimable_outpoints.get($txid) {
1887 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
1888 if let &Some(ref source) = source_option {
1889 // Check if the HTLC is present in the commitment transaction that was
1890 // broadcast, but not if it was below the dust limit, which we should
1891 // fail backwards immediately as there is no way for us to learn the
1892 // payment_preimage.
1893 // Note that if the dust limit were allowed to change between
1894 // commitment transactions we'd want to be check whether *any*
1895 // broadcastable commitment transaction has the HTLC in it, but it
1896 // cannot currently change after channel initialization, so we don't
1898 let confirmed_htlcs_iter: &mut Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
1900 let mut matched_htlc = false;
1901 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
1902 if broadcast_htlc.transaction_output_index.is_some() &&
1903 (Some(&**source) == *broadcast_source ||
1904 (broadcast_source.is_none() &&
1905 broadcast_htlc.payment_hash == htlc.payment_hash &&
1906 broadcast_htlc.amount_msat == htlc.amount_msat)) {
1907 matched_htlc = true;
1911 if matched_htlc { continue; }
1912 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
1913 if entry.height != $commitment_tx_conf_height { return true; }
1915 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
1916 *update_source != **source
1921 let entry = OnchainEventEntry {
1922 txid: $commitment_txid_confirmed,
1923 transaction: Some($commitment_tx_confirmed.clone()),
1924 height: $commitment_tx_conf_height,
1925 event: OnchainEvent::HTLCUpdate {
1926 source: (**source).clone(),
1927 payment_hash: htlc.payment_hash.clone(),
1928 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
1929 commitment_tx_output_idx: None,
1932 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
1933 log_bytes!(htlc.payment_hash.0), $commitment_tx, $commitment_tx_type,
1934 $commitment_txid_confirmed, entry.confirmation_threshold());
1935 $self.onchain_events_awaiting_threshold_conf.push(entry);
1941 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
1942 check_htlc_fails!(txid, "current");
1944 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
1945 check_htlc_fails!(txid, "previous");
1950 // In the `test_invalid_funding_tx` test, we need a bogus script which matches the HTLC-Accepted
1951 // witness length match (ie is 136 bytes long). We generate one here which we also use in some
1952 // in-line tests later.
1955 pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
1956 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
1957 ret[131] = opcodes::all::OP_DROP.to_u8();
1958 ret[132] = opcodes::all::OP_DROP.to_u8();
1959 ret[133] = opcodes::all::OP_DROP.to_u8();
1960 ret[134] = opcodes::all::OP_DROP.to_u8();
1961 ret[135] = opcodes::OP_TRUE.to_u8();
1966 pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
1967 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
1970 impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1971 /// Inserts a revocation secret into this channel monitor. Prunes old preimages if neither
1972 /// needed by holder commitment transactions HTCLs nor by counterparty ones. Unless we haven't already seen
1973 /// counterparty commitment transaction's secret, they are de facto pruned (we can use revocation key).
1974 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1975 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
1976 return Err("Previous secret did not match new one");
1979 // Prune HTLCs from the previous counterparty commitment tx so we don't generate failure/fulfill
1980 // events for now-revoked/fulfilled HTLCs.
1981 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
1982 for &mut (_, ref mut source) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
1987 if !self.payment_preimages.is_empty() {
1988 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
1989 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
1990 let min_idx = self.get_min_seen_secret();
1991 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
1993 self.payment_preimages.retain(|&k, _| {
1994 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
1995 if k == htlc.payment_hash {
1999 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2000 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2001 if k == htlc.payment_hash {
2006 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2013 counterparty_hash_commitment_number.remove(&k);
2022 pub(crate) fn provide_latest_counterparty_commitment_tx<L: Deref>(&mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>, commitment_number: u64, their_per_commitment_point: PublicKey, logger: &L) where L::Target: Logger {
2023 // TODO: Encrypt the htlc_outputs data with the single-hash of the commitment transaction
2024 // so that a remote monitor doesn't learn anything unless there is a malicious close.
2025 // (only maybe, sadly we cant do the same for local info, as we need to be aware of
2027 for &(ref htlc, _) in &htlc_outputs {
2028 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2031 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2032 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2033 self.current_counterparty_commitment_txid = Some(txid);
2034 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2035 self.current_counterparty_commitment_number = commitment_number;
2036 //TODO: Merge this into the other per-counterparty-transaction output storage stuff
2037 match self.their_cur_per_commitment_points {
2038 Some(old_points) => {
2039 if old_points.0 == commitment_number + 1 {
2040 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2041 } else if old_points.0 == commitment_number + 2 {
2042 if let Some(old_second_point) = old_points.2 {
2043 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2045 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2048 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2052 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2055 let mut htlcs = Vec::with_capacity(htlc_outputs.len());
2056 for htlc in htlc_outputs {
2057 if htlc.0.transaction_output_index.is_some() {
2063 /// Informs this monitor of the latest holder (ie broadcastable) commitment transaction. The
2064 /// monitor watches for timeouts and may broadcast it if we approach such a timeout. Thus, it
2065 /// is important that any clones of this channel monitor (including remote clones) by kept
2066 /// up-to-date as our holder commitment transaction is updated.
2067 /// Panics if set_on_holder_tx_csv has never been called.
2068 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>) -> Result<(), &'static str> {
2069 // block for Rust 1.34 compat
2070 let mut new_holder_commitment_tx = {
2071 let trusted_tx = holder_commitment_tx.trust();
2072 let txid = trusted_tx.txid();
2073 let tx_keys = trusted_tx.keys();
2074 self.current_holder_commitment_number = trusted_tx.commitment_number();
2077 revocation_key: tx_keys.revocation_key,
2078 a_htlc_key: tx_keys.broadcaster_htlc_key,
2079 b_htlc_key: tx_keys.countersignatory_htlc_key,
2080 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2081 per_commitment_point: tx_keys.per_commitment_point,
2083 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2084 feerate_per_kw: trusted_tx.feerate_per_kw(),
2087 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2088 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2089 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2090 if self.holder_tx_signed {
2091 return Err("Latest holder commitment signed has already been signed, update is rejected");
2096 /// Provides a payment_hash->payment_preimage mapping. Will be automatically pruned when all
2097 /// commitment_tx_infos which contain the payment hash have been revoked.
2098 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2099 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage, broadcaster: &B,
2100 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L)
2101 where B::Target: BroadcasterInterface,
2102 F::Target: FeeEstimator,
2105 self.payment_preimages.insert(payment_hash.clone(), payment_preimage.clone());
2107 // If the channel is force closed, try to claim the output from this preimage.
2108 // First check if a counterparty commitment transaction has been broadcasted:
2109 macro_rules! claim_htlcs {
2110 ($commitment_number: expr, $txid: expr) => {
2111 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None);
2112 self.onchain_tx_handler.update_claims_view(&Vec::new(), htlc_claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2115 if let Some(txid) = self.current_counterparty_commitment_txid {
2116 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2117 claim_htlcs!(*commitment_number, txid);
2121 if let Some(txid) = self.prev_counterparty_commitment_txid {
2122 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
2123 claim_htlcs!(*commitment_number, txid);
2128 // Then if a holder commitment transaction has been seen on-chain, broadcast transactions
2129 // claiming the HTLC output from each of the holder commitment transactions.
2130 // Note that we can't just use `self.holder_tx_signed`, because that only covers the case where
2131 // *we* sign a holder commitment transaction, not when e.g. a watchtower broadcasts one of our
2132 // holder commitment transactions.
2133 if self.broadcasted_holder_revokable_script.is_some() {
2134 // Assume that the broadcasted commitment transaction confirmed in the current best
2135 // block. Even if not, its a reasonable metric for the bump criteria on the HTLC
2137 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2138 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2139 if let Some(ref tx) = self.prev_holder_signed_commitment_tx {
2140 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&tx, self.best_block.height());
2141 self.onchain_tx_handler.update_claims_view(&Vec::new(), claim_reqs, self.best_block.height(), self.best_block.height(), broadcaster, fee_estimator, logger);
2146 pub(crate) fn broadcast_latest_holder_commitment_txn<B: Deref, L: Deref>(&mut self, broadcaster: &B, logger: &L)
2147 where B::Target: BroadcasterInterface,
2150 for tx in self.get_latest_holder_commitment_txn(logger).iter() {
2151 log_info!(logger, "Broadcasting local {}", log_tx!(tx));
2152 broadcaster.broadcast_transaction(tx);
2154 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2157 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
2158 where B::Target: BroadcasterInterface,
2159 F::Target: FeeEstimator,
2162 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} changes.",
2163 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
2164 // ChannelMonitor updates may be applied after force close if we receive a
2165 // preimage for a broadcasted commitment transaction HTLC output that we'd
2166 // like to claim on-chain. If this is the case, we no longer have guaranteed
2167 // access to the monitor's update ID, so we use a sentinel value instead.
2168 if updates.update_id == CLOSED_CHANNEL_UPDATE_ID {
2169 assert_eq!(updates.updates.len(), 1);
2170 match updates.updates[0] {
2171 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
2173 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
2174 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
2177 } else if self.latest_update_id + 1 != updates.update_id {
2178 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
2180 let mut ret = Ok(());
2181 for update in updates.updates.iter() {
2183 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs } => {
2184 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
2185 if self.lockdown_from_offchain { panic!(); }
2186 if let Err(e) = self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone()) {
2187 log_error!(logger, "Providing latest holder commitment transaction failed/was refused:");
2188 log_error!(logger, " {}", e);
2192 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point } => {
2193 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
2194 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
2196 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage } => {
2197 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
2198 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
2199 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner()), &payment_preimage, broadcaster, &bounded_fee_estimator, logger)
2201 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
2202 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
2203 if let Err(e) = self.provide_secret(*idx, *secret) {
2204 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
2205 log_error!(logger, " {}", e);
2209 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
2210 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
2211 self.lockdown_from_offchain = true;
2212 if *should_broadcast {
2213 self.broadcast_latest_holder_commitment_txn(broadcaster, logger);
2214 } else if !self.holder_tx_signed {
2215 log_error!(logger, "You have a toxic holder commitment transaction avaible in channel monitor, read comment in ChannelMonitor::get_latest_holder_commitment_txn to be informed of manual action to take");
2217 // If we generated a MonitorEvent::CommitmentTxConfirmed, the ChannelManager
2218 // will still give us a ChannelForceClosed event with !should_broadcast, but we
2219 // shouldn't print the scary warning above.
2220 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
2223 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
2224 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
2225 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
2226 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
2231 self.latest_update_id = updates.update_id;
2233 if ret.is_ok() && self.funding_spend_seen {
2234 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
2239 pub fn get_latest_update_id(&self) -> u64 {
2240 self.latest_update_id
2243 pub fn get_funding_txo(&self) -> &(OutPoint, Script) {
2247 pub fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, Script)>> {
2248 // If we've detected a counterparty commitment tx on chain, we must include it in the set
2249 // of outputs to watch for spends of, otherwise we're likely to lose user funds. Because
2250 // its trivial to do, double-check that here.
2251 for (txid, _) in self.counterparty_commitment_txn_on_chain.iter() {
2252 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
2254 &self.outputs_to_watch
2257 pub fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
2258 let mut ret = Vec::new();
2259 mem::swap(&mut ret, &mut self.pending_monitor_events);
2263 pub fn get_and_clear_pending_events(&mut self) -> Vec<Event> {
2264 let mut ret = Vec::new();
2265 mem::swap(&mut ret, &mut self.pending_events);
2269 /// Can only fail if idx is < get_min_seen_secret
2270 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
2271 self.commitment_secrets.get_secret(idx)
2274 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2275 self.commitment_secrets.get_min_seen_secret()
2278 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2279 self.current_counterparty_commitment_number
2282 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2283 self.current_holder_commitment_number
2286 /// Attempts to claim a counterparty commitment transaction's outputs using the revocation key and
2287 /// data in counterparty_claimable_outpoints. Will directly claim any HTLC outputs which expire at a
2288 /// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
2289 /// HTLC-Success/HTLC-Timeout transactions.
2291 /// Returns packages to claim the revoked output(s), as well as additional outputs to watch and
2292 /// general information about the output that is to the counterparty in the commitment
2294 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L)
2295 -> (Vec<PackageTemplate>, TransactionOutputs, CommitmentTxCounterpartyOutputInfo)
2296 where L::Target: Logger {
2297 // Most secp and related errors trying to create keys means we have no hope of constructing
2298 // a spend transaction...so we return no transactions to broadcast
2299 let mut claimable_outpoints = Vec::new();
2300 let mut watch_outputs = Vec::new();
2301 let mut to_counterparty_output_info = None;
2303 let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
2304 let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
2306 macro_rules! ignore_error {
2307 ( $thing : expr ) => {
2310 Err(_) => return (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2315 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence.0 as u64 & 0xffffff) << 3*8) | (tx.lock_time.0 as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
2316 if commitment_number >= self.get_min_seen_secret() {
2317 let secret = self.get_secret(commitment_number).unwrap();
2318 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2319 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2320 let revocation_pubkey = ignore_error!(chan_utils::derive_public_revocation_key(&self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint));
2321 let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.counterparty_commitment_params.counterparty_delayed_payment_base_key));
2323 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
2324 let revokeable_p2wsh = revokeable_redeemscript.to_v0_p2wsh();
2326 // First, process non-htlc outputs (to_holder & to_counterparty)
2327 for (idx, outp) in tx.output.iter().enumerate() {
2328 if outp.script_pubkey == revokeable_p2wsh {
2329 let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, outp.value, self.counterparty_commitment_params.on_counterparty_tx_csv);
2330 let justice_package = PackageTemplate::build_package(commitment_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height);
2331 claimable_outpoints.push(justice_package);
2332 to_counterparty_output_info =
2333 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
2337 // Then, try to find revoked htlc outputs
2338 if let Some(ref per_commitment_data) = per_commitment_option {
2339 for (_, &(ref htlc, _)) in per_commitment_data.iter().enumerate() {
2340 if let Some(transaction_output_index) = htlc.transaction_output_index {
2341 if transaction_output_index as usize >= tx.output.len() ||
2342 tx.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2343 // per_commitment_data is corrupt or our commitment signing key leaked!
2344 return (claimable_outpoints, (commitment_txid, watch_outputs),
2345 to_counterparty_output_info);
2347 let revk_htlc_outp = RevokedHTLCOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, htlc.amount_msat / 1000, htlc.clone(), self.onchain_tx_handler.channel_transaction_parameters.opt_anchors.is_some());
2348 let justice_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp), htlc.cltv_expiry, true, height);
2349 claimable_outpoints.push(justice_package);
2354 // Last, track onchain revoked commitment transaction and fail backward outgoing HTLCs as payment path is broken
2355 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { // ie we're confident this is actually ours
2356 // We're definitely a counterparty commitment transaction!
2357 log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
2358 for (idx, outp) in tx.output.iter().enumerate() {
2359 watch_outputs.push((idx as u32, outp.clone()));
2361 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2363 if let Some(per_commitment_data) = per_commitment_option {
2364 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
2365 per_commitment_data.iter().map(|(htlc, htlc_source)|
2366 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2369 debug_assert!(false, "We should have per-commitment option for any recognized old commitment txn");
2370 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
2371 [].iter().map(|reference| *reference), logger);
2374 } else if let Some(per_commitment_data) = per_commitment_option {
2375 // While this isn't useful yet, there is a potential race where if a counterparty
2376 // revokes a state at the same time as the commitment transaction for that state is
2377 // confirmed, and the watchtower receives the block before the user, the user could
2378 // upload a new ChannelMonitor with the revocation secret but the watchtower has
2379 // already processed the block, resulting in the counterparty_commitment_txn_on_chain entry
2380 // not being generated by the above conditional. Thus, to be safe, we go ahead and
2382 for (idx, outp) in tx.output.iter().enumerate() {
2383 watch_outputs.push((idx as u32, outp.clone()));
2385 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
2387 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
2388 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height,
2389 per_commitment_data.iter().map(|(htlc, htlc_source)|
2390 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
2393 let (htlc_claim_reqs, counterparty_output_info) =
2394 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx));
2395 to_counterparty_output_info = counterparty_output_info;
2396 for req in htlc_claim_reqs {
2397 claimable_outpoints.push(req);
2401 (claimable_outpoints, (commitment_txid, watch_outputs), to_counterparty_output_info)
2404 /// Returns the HTLC claim package templates and the counterparty output info
2405 fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>)
2406 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
2407 let mut claimable_outpoints = Vec::new();
2408 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
2410 let htlc_outputs = match self.counterparty_claimable_outpoints.get(&commitment_txid) {
2411 Some(outputs) => outputs,
2412 None => return (claimable_outpoints, to_counterparty_output_info),
2414 let per_commitment_points = match self.their_cur_per_commitment_points {
2415 Some(points) => points,
2416 None => return (claimable_outpoints, to_counterparty_output_info),
2419 let per_commitment_point =
2420 // If the counterparty commitment tx is the latest valid state, use their latest
2421 // per-commitment point
2422 if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
2423 else if let Some(point) = per_commitment_points.2.as_ref() {
2424 // If counterparty commitment tx is the state previous to the latest valid state, use
2425 // their previous per-commitment point (non-atomicity of revocation means it's valid for
2426 // them to temporarily have two valid commitment txns from our viewpoint)
2427 if per_commitment_points.0 == commitment_number + 1 {
2429 } else { return (claimable_outpoints, to_counterparty_output_info); }
2430 } else { return (claimable_outpoints, to_counterparty_output_info); };
2432 if let Some(transaction) = tx {
2433 let revokeable_p2wsh_opt =
2434 if let Ok(revocation_pubkey) = chan_utils::derive_public_revocation_key(
2435 &self.secp_ctx, &per_commitment_point, &self.holder_revocation_basepoint)
2437 if let Ok(delayed_key) = chan_utils::derive_public_key(&self.secp_ctx,
2438 &per_commitment_point,
2439 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key)
2441 Some(chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
2442 self.counterparty_commitment_params.on_counterparty_tx_csv,
2443 &delayed_key).to_v0_p2wsh())
2445 debug_assert!(false, "Failed to derive a delayed payment key for a commitment state we accepted");
2449 debug_assert!(false, "Failed to derive a revocation pubkey key for a commitment state we accepted");
2452 if let Some(revokeable_p2wsh) = revokeable_p2wsh_opt {
2453 for (idx, outp) in transaction.output.iter().enumerate() {
2454 if outp.script_pubkey == revokeable_p2wsh {
2455 to_counterparty_output_info =
2456 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
2462 for (_, &(ref htlc, _)) in htlc_outputs.iter().enumerate() {
2463 if let Some(transaction_output_index) = htlc.transaction_output_index {
2464 if let Some(transaction) = tx {
2465 if transaction_output_index as usize >= transaction.output.len() ||
2466 transaction.output[transaction_output_index as usize].value != htlc.amount_msat / 1000 {
2467 // per_commitment_data is corrupt or our commitment signing key leaked!
2468 return (claimable_outpoints, to_counterparty_output_info);
2471 let preimage = if htlc.offered { if let Some(p) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
2472 if preimage.is_some() || !htlc.offered {
2473 let counterparty_htlc_outp = if htlc.offered {
2474 PackageSolvingData::CounterpartyOfferedHTLCOutput(
2475 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
2476 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2477 self.counterparty_commitment_params.counterparty_htlc_base_key,
2478 preimage.unwrap(), htlc.clone()))
2480 PackageSolvingData::CounterpartyReceivedHTLCOutput(
2481 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
2482 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
2483 self.counterparty_commitment_params.counterparty_htlc_base_key,
2486 let aggregation = if !htlc.offered { false } else { true };
2487 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry,aggregation, 0);
2488 claimable_outpoints.push(counterparty_package);
2493 (claimable_outpoints, to_counterparty_output_info)
2496 /// Attempts to claim a counterparty HTLC-Success/HTLC-Timeout's outputs using the revocation key
2497 fn check_spend_counterparty_htlc<L: Deref>(&mut self, tx: &Transaction, commitment_number: u64, height: u32, logger: &L) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
2498 let htlc_txid = tx.txid();
2499 if tx.input.len() != 1 || tx.output.len() != 1 || tx.input[0].witness.len() != 5 {
2500 return (Vec::new(), None)
2503 macro_rules! ignore_error {
2504 ( $thing : expr ) => {
2507 Err(_) => return (Vec::new(), None)
2512 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
2513 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
2514 let per_commitment_point = PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key);
2516 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, 0);
2517 let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, tx.output[0].value, self.counterparty_commitment_params.on_counterparty_tx_csv);
2518 let justice_package = PackageTemplate::build_package(htlc_txid, 0, PackageSolvingData::RevokedOutput(revk_outp), height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32, true, height);
2519 let claimable_outpoints = vec!(justice_package);
2520 let outputs = vec![(0, tx.output[0].clone())];
2521 (claimable_outpoints, Some((htlc_txid, outputs)))
2524 // Returns (1) `PackageTemplate`s that can be given to the OnChainTxHandler, so that the handler can
2525 // broadcast transactions claiming holder HTLC commitment outputs and (2) a holder revokable
2526 // script so we can detect whether a holder transaction has been seen on-chain.
2527 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(Script, PublicKey, PublicKey)>) {
2528 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
2530 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
2531 let broadcasted_holder_revokable_script = Some((redeemscript.to_v0_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
2533 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2534 if let Some(transaction_output_index) = htlc.transaction_output_index {
2535 let htlc_output = if htlc.offered {
2536 HolderHTLCOutput::build_offered(htlc.amount_msat, htlc.cltv_expiry)
2538 let payment_preimage = if let Some(preimage) = self.payment_preimages.get(&htlc.payment_hash) {
2541 // We can't build an HTLC-Success transaction without the preimage
2544 HolderHTLCOutput::build_accepted(payment_preimage, htlc.amount_msat)
2546 let htlc_package = PackageTemplate::build_package(holder_tx.txid, transaction_output_index, PackageSolvingData::HolderHTLCOutput(htlc_output), htlc.cltv_expiry, false, conf_height);
2547 claim_requests.push(htlc_package);
2551 (claim_requests, broadcasted_holder_revokable_script)
2554 // Returns holder HTLC outputs to watch and react to in case of spending.
2555 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
2556 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
2557 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
2558 if let Some(transaction_output_index) = htlc.transaction_output_index {
2559 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
2565 /// Attempts to claim any claimable HTLCs in a commitment transaction which was not (yet)
2566 /// revoked using data in holder_claimable_outpoints.
2567 /// Should not be used if check_spend_revoked_transaction succeeds.
2568 /// Returns None unless the transaction is definitely one of our commitment transactions.
2569 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
2570 let commitment_txid = tx.txid();
2571 let mut claim_requests = Vec::new();
2572 let mut watch_outputs = Vec::new();
2574 macro_rules! append_onchain_update {
2575 ($updates: expr, $to_watch: expr) => {
2576 claim_requests = $updates.0;
2577 self.broadcasted_holder_revokable_script = $updates.1;
2578 watch_outputs.append(&mut $to_watch);
2582 // HTLCs set may differ between last and previous holder commitment txn, in case of one them hitting chain, ensure we cancel all HTLCs backward
2583 let mut is_holder_tx = false;
2585 if self.current_holder_commitment_tx.txid == commitment_txid {
2586 is_holder_tx = true;
2587 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2588 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
2589 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
2590 append_onchain_update!(res, to_watch);
2591 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
2592 self.current_holder_commitment_tx.htlc_outputs.iter()
2593 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
2594 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
2595 if holder_tx.txid == commitment_txid {
2596 is_holder_tx = true;
2597 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
2598 let res = self.get_broadcasted_holder_claims(holder_tx, height);
2599 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
2600 append_onchain_update!(res, to_watch);
2601 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height,
2602 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
2608 Some((claim_requests, (commitment_txid, watch_outputs)))
2614 pub fn get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2615 log_debug!(logger, "Getting signed latest holder commitment transaction!");
2616 self.holder_tx_signed = true;
2617 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2618 let txid = commitment_tx.txid();
2619 let mut holder_transactions = vec![commitment_tx];
2620 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2621 if let Some(vout) = htlc.0.transaction_output_index {
2622 let preimage = if !htlc.0.offered {
2623 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2624 // We can't build an HTLC-Success transaction without the preimage
2627 } else if htlc.0.cltv_expiry > self.best_block.height() + 1 {
2628 // Don't broadcast HTLC-Timeout transactions immediately as they don't meet the
2629 // current locktime requirements on-chain. We will broadcast them in
2630 // `block_confirmed` when `should_broadcast_holder_commitment_txn` returns true.
2631 // Note that we add + 1 as transactions are broadcastable when they can be
2632 // confirmed in the next block.
2635 if let Some(htlc_tx) = self.onchain_tx_handler.get_fully_signed_htlc_tx(
2636 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2637 holder_transactions.push(htlc_tx);
2641 // We throw away the generated waiting_first_conf data as we aren't (yet) confirmed and we don't actually know what the caller wants to do.
2642 // The data will be re-generated and tracked in check_spend_holder_transaction if we get a confirmation.
2646 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
2647 /// Note that this includes possibly-locktimed-in-the-future transactions!
2648 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&mut self, logger: &L) -> Vec<Transaction> where L::Target: Logger {
2649 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
2650 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
2651 let txid = commitment_tx.txid();
2652 let mut holder_transactions = vec![commitment_tx];
2653 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
2654 if let Some(vout) = htlc.0.transaction_output_index {
2655 let preimage = if !htlc.0.offered {
2656 if let Some(preimage) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
2657 // We can't build an HTLC-Success transaction without the preimage
2661 if let Some(htlc_tx) = self.onchain_tx_handler.unsafe_get_fully_signed_htlc_tx(
2662 &::bitcoin::OutPoint { txid, vout }, &preimage) {
2663 holder_transactions.push(htlc_tx);
2670 pub fn block_connected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, txdata: &TransactionData, height: u32, broadcaster: B, fee_estimator: F, logger: L) -> Vec<TransactionOutputs>
2671 where B::Target: BroadcasterInterface,
2672 F::Target: FeeEstimator,
2675 let block_hash = header.block_hash();
2676 self.best_block = BestBlock::new(block_hash, height);
2678 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2679 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
2682 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2684 header: &BlockHeader,
2687 fee_estimator: &LowerBoundedFeeEstimator<F>,
2689 ) -> Vec<TransactionOutputs>
2691 B::Target: BroadcasterInterface,
2692 F::Target: FeeEstimator,
2695 let block_hash = header.block_hash();
2697 if height > self.best_block.height() {
2698 self.best_block = BestBlock::new(block_hash, height);
2699 self.block_confirmed(height, vec![], vec![], vec![], &broadcaster, &fee_estimator, &logger)
2700 } else if block_hash != self.best_block.block_hash() {
2701 self.best_block = BestBlock::new(block_hash, height);
2702 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
2703 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, fee_estimator, logger);
2705 } else { Vec::new() }
2708 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2710 header: &BlockHeader,
2711 txdata: &TransactionData,
2714 fee_estimator: &LowerBoundedFeeEstimator<F>,
2716 ) -> Vec<TransactionOutputs>
2718 B::Target: BroadcasterInterface,
2719 F::Target: FeeEstimator,
2722 let txn_matched = self.filter_block(txdata);
2723 for tx in &txn_matched {
2724 let mut output_val = 0;
2725 for out in tx.output.iter() {
2726 if out.value > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2727 output_val += out.value;
2728 if output_val > 21_000_000_0000_0000 { panic!("Value-overflowing transaction provided to block connected"); }
2732 let block_hash = header.block_hash();
2734 let mut watch_outputs = Vec::new();
2735 let mut claimable_outpoints = Vec::new();
2736 for tx in &txn_matched {
2737 if tx.input.len() == 1 {
2738 // Assuming our keys were not leaked (in which case we're screwed no matter what),
2739 // commitment transactions and HTLC transactions will all only ever have one input,
2740 // which is an easy way to filter out any potential non-matching txn for lazy
2742 let prevout = &tx.input[0].previous_output;
2743 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
2744 let mut balance_spendable_csv = None;
2745 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
2746 log_bytes!(self.funding_info.0.to_channel_id()), tx.txid());
2747 self.funding_spend_seen = true;
2748 let mut commitment_tx_to_counterparty_output = None;
2749 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.0 >> 8*3) as u8 == 0x20 {
2750 let (mut new_outpoints, new_outputs, counterparty_output_idx_sats) =
2751 self.check_spend_counterparty_transaction(&tx, height, &logger);
2752 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
2753 if !new_outputs.1.is_empty() {
2754 watch_outputs.push(new_outputs);
2756 claimable_outpoints.append(&mut new_outpoints);
2757 if new_outpoints.is_empty() {
2758 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &logger) {
2759 debug_assert!(commitment_tx_to_counterparty_output.is_none(),
2760 "A commitment transaction matched as both a counterparty and local commitment tx?");
2761 if !new_outputs.1.is_empty() {
2762 watch_outputs.push(new_outputs);
2764 claimable_outpoints.append(&mut new_outpoints);
2765 balance_spendable_csv = Some(self.on_holder_tx_csv);
2769 let txid = tx.txid();
2770 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
2772 transaction: Some((*tx).clone()),
2774 event: OnchainEvent::FundingSpendConfirmation {
2775 on_local_output_csv: balance_spendable_csv,
2776 commitment_tx_to_counterparty_output,
2780 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&prevout.txid) {
2781 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(&tx, commitment_number, height, &logger);
2782 claimable_outpoints.append(&mut new_outpoints);
2783 if let Some(new_outputs) = new_outputs_option {
2784 watch_outputs.push(new_outputs);
2789 // While all commitment/HTLC-Success/HTLC-Timeout transactions have one input, HTLCs
2790 // can also be resolved in a few other ways which can have more than one output. Thus,
2791 // we call is_resolving_htlc_output here outside of the tx.input.len() == 1 check.
2792 self.is_resolving_htlc_output(&tx, height, &logger);
2794 self.is_paying_spendable_output(&tx, height, &logger);
2797 if height > self.best_block.height() {
2798 self.best_block = BestBlock::new(block_hash, height);
2801 self.block_confirmed(height, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, &logger)
2804 /// Update state for new block(s)/transaction(s) confirmed. Note that the caller must update
2805 /// `self.best_block` before calling if a new best blockchain tip is available. More
2806 /// concretely, `self.best_block` must never be at a lower height than `conf_height`, avoiding
2807 /// complexity especially in `OnchainTx::update_claims_view`.
2809 /// `conf_height` should be set to the height at which any new transaction(s)/block(s) were
2810 /// confirmed at, even if it is not the current best height.
2811 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
2814 txn_matched: Vec<&Transaction>,
2815 mut watch_outputs: Vec<TransactionOutputs>,
2816 mut claimable_outpoints: Vec<PackageTemplate>,
2818 fee_estimator: &LowerBoundedFeeEstimator<F>,
2820 ) -> Vec<TransactionOutputs>
2822 B::Target: BroadcasterInterface,
2823 F::Target: FeeEstimator,
2826 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
2827 debug_assert!(self.best_block.height() >= conf_height);
2829 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
2830 if should_broadcast {
2831 let funding_outp = HolderFundingOutput::build(self.funding_redeemscript.clone());
2832 let commitment_package = PackageTemplate::build_package(self.funding_info.0.txid.clone(), self.funding_info.0.index as u32, PackageSolvingData::HolderFundingOutput(funding_outp), self.best_block.height(), false, self.best_block.height());
2833 claimable_outpoints.push(commitment_package);
2834 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(self.funding_info.0));
2835 let commitment_tx = self.onchain_tx_handler.get_fully_signed_holder_tx(&self.funding_redeemscript);
2836 self.holder_tx_signed = true;
2837 // Because we're broadcasting a commitment transaction, we should construct the package
2838 // assuming it gets confirmed in the next block. Sadly, we have code which considers
2839 // "not yet confirmed" things as discardable, so we cannot do that here.
2840 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, self.best_block.height());
2841 let new_outputs = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, &commitment_tx);
2842 if !new_outputs.is_empty() {
2843 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
2845 claimable_outpoints.append(&mut new_outpoints);
2848 // Find which on-chain events have reached their confirmation threshold.
2849 let onchain_events_awaiting_threshold_conf =
2850 self.onchain_events_awaiting_threshold_conf.drain(..).collect::<Vec<_>>();
2851 let mut onchain_events_reaching_threshold_conf = Vec::new();
2852 for entry in onchain_events_awaiting_threshold_conf {
2853 if entry.has_reached_confirmation_threshold(&self.best_block) {
2854 onchain_events_reaching_threshold_conf.push(entry);
2856 self.onchain_events_awaiting_threshold_conf.push(entry);
2860 // Used to check for duplicate HTLC resolutions.
2861 #[cfg(debug_assertions)]
2862 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
2864 .filter_map(|entry| match &entry.event {
2865 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
2869 #[cfg(debug_assertions)]
2870 let mut matured_htlcs = Vec::new();
2872 // Produce actionable events from on-chain events having reached their threshold.
2873 for entry in onchain_events_reaching_threshold_conf.drain(..) {
2875 OnchainEvent::HTLCUpdate { ref source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
2876 // Check for duplicate HTLC resolutions.
2877 #[cfg(debug_assertions)]
2880 unmatured_htlcs.iter().find(|&htlc| htlc == &source).is_none(),
2881 "An unmature HTLC transaction conflicts with a maturing one; failed to \
2882 call either transaction_unconfirmed for the conflicting transaction \
2883 or block_disconnected for a block containing it.");
2885 matured_htlcs.iter().find(|&htlc| htlc == source).is_none(),
2886 "A matured HTLC transaction conflicts with a maturing one; failed to \
2887 call either transaction_unconfirmed for the conflicting transaction \
2888 or block_disconnected for a block containing it.");
2889 matured_htlcs.push(source.clone());
2892 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
2893 log_bytes!(payment_hash.0), entry.txid);
2894 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
2896 payment_preimage: None,
2897 source: source.clone(),
2898 htlc_value_satoshis,
2900 if let Some(idx) = commitment_tx_output_idx {
2901 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
2902 commitment_tx_output_idx: idx, resolving_txid: Some(entry.txid),
2903 payment_preimage: None,
2907 OnchainEvent::MaturingOutput { descriptor } => {
2908 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
2909 self.pending_events.push(Event::SpendableOutputs {
2910 outputs: vec![descriptor]
2913 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
2914 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
2915 commitment_tx_output_idx, resolving_txid: Some(entry.txid),
2916 payment_preimage: preimage,
2919 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
2920 self.funding_spend_confirmed = Some(entry.txid);
2921 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
2926 self.onchain_tx_handler.update_claims_view(&txn_matched, claimable_outpoints, conf_height, self.best_block.height(), broadcaster, fee_estimator, logger);
2928 // Determine new outputs to watch by comparing against previously known outputs to watch,
2929 // updating the latter in the process.
2930 watch_outputs.retain(|&(ref txid, ref txouts)| {
2931 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
2932 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
2936 // If we see a transaction for which we registered outputs previously,
2937 // make sure the registered scriptpubkey at the expected index match
2938 // the actual transaction output one. We failed this case before #653.
2939 for tx in &txn_matched {
2940 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.txid()) {
2941 for idx_and_script in outputs.iter() {
2942 assert!((idx_and_script.0 as usize) < tx.output.len());
2943 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
2951 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(&mut self, header: &BlockHeader, height: u32, broadcaster: B, fee_estimator: F, logger: L)
2952 where B::Target: BroadcasterInterface,
2953 F::Target: FeeEstimator,
2956 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
2959 //- htlc update there as failure-trigger tx (revoked commitment tx, non-revoked commitment tx, HTLC-timeout tx) has been disconnected
2960 //- maturing spendable output has transaction paying us has been disconnected
2961 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
2963 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2964 self.onchain_tx_handler.block_disconnected(height, broadcaster, &bounded_fee_estimator, logger);
2966 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
2969 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2973 fee_estimator: &LowerBoundedFeeEstimator<F>,
2976 B::Target: BroadcasterInterface,
2977 F::Target: FeeEstimator,
2980 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.txid == *txid {
2981 log_info!(logger, "Removing onchain event with txid {}", txid);
2984 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, fee_estimator, logger);
2987 /// Filters a block's `txdata` for transactions spending watched outputs or for any child
2988 /// transactions thereof.
2989 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
2990 let mut matched_txn = HashSet::new();
2991 txdata.iter().filter(|&&(_, tx)| {
2992 let mut matches = self.spends_watched_output(tx);
2993 for input in tx.input.iter() {
2994 if matches { break; }
2995 if matched_txn.contains(&input.previous_output.txid) {
3000 matched_txn.insert(tx.txid());
3003 }).map(|(_, tx)| *tx).collect()
3006 /// Checks if a given transaction spends any watched outputs.
3007 fn spends_watched_output(&self, tx: &Transaction) -> bool {
3008 for input in tx.input.iter() {
3009 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
3010 for (idx, _script_pubkey) in outputs.iter() {
3011 if *idx == input.previous_output.vout {
3014 // If the expected script is a known type, check that the witness
3015 // appears to be spending the correct type (ie that the match would
3016 // actually succeed in BIP 158/159-style filters).
3017 if _script_pubkey.is_v0_p2wsh() {
3018 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
3019 // In at least one test we use a deliberately bogus witness
3020 // script which hit an old panic. Thus, we check for that here
3021 // and avoid the assert if its the expected bogus script.
3025 assert_eq!(&bitcoin::Address::p2wsh(&Script::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
3026 } else if _script_pubkey.is_v0_p2wpkh() {
3027 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap(), bitcoin::Network::Bitcoin).unwrap().script_pubkey(), _script_pubkey);
3028 } else { panic!(); }
3039 fn should_broadcast_holder_commitment_txn<L: Deref>(&self, logger: &L) -> bool where L::Target: Logger {
3040 // We need to consider all HTLCs which are:
3041 // * in any unrevoked counterparty commitment transaction, as they could broadcast said
3042 // transactions and we'd end up in a race, or
3043 // * are in our latest holder commitment transaction, as this is the thing we will
3044 // broadcast if we go on-chain.
3045 // Note that we consider HTLCs which were below dust threshold here - while they don't
3046 // strictly imply that we need to fail the channel, we need to go ahead and fail them back
3047 // to the source, and if we don't fail the channel we will have to ensure that the next
3048 // updates that peer sends us are update_fails, failing the channel if not. It's probably
3049 // easier to just fail the channel as this case should be rare enough anyway.
3050 let height = self.best_block.height();
3051 macro_rules! scan_commitment {
3052 ($htlcs: expr, $holder_tx: expr) => {
3053 for ref htlc in $htlcs {
3054 // For inbound HTLCs which we know the preimage for, we have to ensure we hit the
3055 // chain with enough room to claim the HTLC without our counterparty being able to
3056 // time out the HTLC first.
3057 // For outbound HTLCs which our counterparty hasn't failed/claimed, our primary
3058 // concern is being able to claim the corresponding inbound HTLC (on another
3059 // channel) before it expires. In fact, we don't even really care if our
3060 // counterparty here claims such an outbound HTLC after it expired as long as we
3061 // can still claim the corresponding HTLC. Thus, to avoid needlessly hitting the
3062 // chain when our counterparty is waiting for expiration to off-chain fail an HTLC
3063 // we give ourselves a few blocks of headroom after expiration before going
3064 // on-chain for an expired HTLC.
3065 // Note that, to avoid a potential attack whereby a node delays claiming an HTLC
3066 // from us until we've reached the point where we go on-chain with the
3067 // corresponding inbound HTLC, we must ensure that outbound HTLCs go on chain at
3068 // least CLTV_CLAIM_BUFFER blocks prior to the inbound HTLC.
3069 // aka outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS == height - CLTV_CLAIM_BUFFER
3070 // inbound_cltv == height + CLTV_CLAIM_BUFFER
3071 // outbound_cltv + LATENCY_GRACE_PERIOD_BLOCKS + CLTV_CLAIM_BUFFER <= inbound_cltv - CLTV_CLAIM_BUFFER
3072 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= inbound_cltv - outbound_cltv
3073 // CLTV_EXPIRY_DELTA <= inbound_cltv - outbound_cltv (by check in ChannelManager::decode_update_add_htlc_onion)
3074 // LATENCY_GRACE_PERIOD_BLOCKS + 2*CLTV_CLAIM_BUFFER <= CLTV_EXPIRY_DELTA
3075 // The final, above, condition is checked for statically in channelmanager
3076 // with CHECK_CLTV_EXPIRY_SANITY_2.
3077 let htlc_outbound = $holder_tx == htlc.offered;
3078 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
3079 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
3080 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
3087 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
3089 if let Some(ref txid) = self.current_counterparty_commitment_txid {
3090 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3091 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3094 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
3095 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
3096 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
3103 /// Check if any transaction broadcasted is resolving HTLC output by a success or timeout on a holder
3104 /// or counterparty commitment tx, if so send back the source, preimage if found and payment_hash of resolved HTLC
3105 fn is_resolving_htlc_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3106 'outer_loop: for input in &tx.input {
3107 let mut payment_data = None;
3108 let witness_items = input.witness.len();
3109 let htlctype = input.witness.last().map(|w| w.len()).and_then(HTLCType::scriptlen_to_htlctype);
3110 let prev_last_witness_len = input.witness.second_to_last().map(|w| w.len()).unwrap_or(0);
3111 let revocation_sig_claim = (witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) && prev_last_witness_len == 33)
3112 || (witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && prev_last_witness_len == 33);
3113 let accepted_preimage_claim = witness_items == 5 && htlctype == Some(HTLCType::AcceptedHTLC)
3114 && input.witness.second_to_last().unwrap().len() == 32;
3115 #[cfg(not(fuzzing))]
3116 let accepted_timeout_claim = witness_items == 3 && htlctype == Some(HTLCType::AcceptedHTLC) && !revocation_sig_claim;
3117 let offered_preimage_claim = witness_items == 3 && htlctype == Some(HTLCType::OfferedHTLC) &&
3118 !revocation_sig_claim && input.witness.second_to_last().unwrap().len() == 32;
3120 #[cfg(not(fuzzing))]
3121 let offered_timeout_claim = witness_items == 5 && htlctype == Some(HTLCType::OfferedHTLC);
3123 let mut payment_preimage = PaymentPreimage([0; 32]);
3124 if accepted_preimage_claim {
3125 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3126 } else if offered_preimage_claim {
3127 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
3130 macro_rules! log_claim {
3131 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
3132 let outbound_htlc = $holder_tx == $htlc.offered;
3133 // HTLCs must either be claimed by a matching script type or through the
3135 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3136 debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
3137 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3138 debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
3139 // Further, only exactly one of the possible spend paths should have been
3140 // matched by any HTLC spend:
3141 #[cfg(not(fuzzing))] // Note that the fuzzer is not bound by pesky things like "signatures"
3142 debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
3143 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
3144 revocation_sig_claim as u8, 1);
3145 if ($holder_tx && revocation_sig_claim) ||
3146 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
3147 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
3148 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3149 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
3150 if revocation_sig_claim { "revocation sig" } else { "preimage claim after we'd passed the HTLC resolution back. We can likely claim the HTLC output with a revocation claim" });
3152 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
3153 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.txid(),
3154 if outbound_htlc { "outbound" } else { "inbound" }, log_bytes!($htlc.payment_hash.0),
3155 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
3160 macro_rules! check_htlc_valid_counterparty {
3161 ($counterparty_txid: expr, $htlc_output: expr) => {
3162 if let Some(txid) = $counterparty_txid {
3163 for &(ref pending_htlc, ref pending_source) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
3164 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
3165 if let &Some(ref source) = pending_source {
3166 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
3167 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
3176 macro_rules! scan_commitment {
3177 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
3178 for (ref htlc_output, source_option) in $htlcs {
3179 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
3180 if let Some(ref source) = source_option {
3181 log_claim!($tx_info, $holder_tx, htlc_output, true);
3182 // We have a resolution of an HTLC either from one of our latest
3183 // holder commitment transactions or an unrevoked counterparty commitment
3184 // transaction. This implies we either learned a preimage, the HTLC
3185 // has timed out, or we screwed up. In any case, we should now
3186 // resolve the source HTLC with the original sender.
3187 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
3188 } else if !$holder_tx {
3189 check_htlc_valid_counterparty!(self.current_counterparty_commitment_txid, htlc_output);
3190 if payment_data.is_none() {
3191 check_htlc_valid_counterparty!(self.prev_counterparty_commitment_txid, htlc_output);
3194 if payment_data.is_none() {
3195 log_claim!($tx_info, $holder_tx, htlc_output, false);
3196 let outbound_htlc = $holder_tx == htlc_output.offered;
3197 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3198 txid: tx.txid(), height, transaction: Some(tx.clone()),
3199 event: OnchainEvent::HTLCSpendConfirmation {
3200 commitment_tx_output_idx: input.previous_output.vout,
3201 preimage: if accepted_preimage_claim || offered_preimage_claim {
3202 Some(payment_preimage) } else { None },
3203 // If this is a payment to us (ie !outbound_htlc), wait for
3204 // the CSV delay before dropping the HTLC from claimable
3205 // balance if the claim was an HTLC-Success transaction (ie
3206 // accepted_preimage_claim).
3207 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
3208 Some(self.on_holder_tx_csv) } else { None },
3211 continue 'outer_loop;
3218 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
3219 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3220 "our latest holder commitment tx", true);
3222 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
3223 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
3224 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
3225 "our previous holder commitment tx", true);
3228 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
3229 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, (b.as_ref().clone()).map(|boxed| &**boxed))),
3230 "counterparty commitment tx", false);
3233 // Check that scan_commitment, above, decided there is some source worth relaying an
3234 // HTLC resolution backwards to and figure out whether we learned a preimage from it.
3235 if let Some((source, payment_hash, amount_msat)) = payment_data {
3236 if accepted_preimage_claim {
3237 if !self.pending_monitor_events.iter().any(
3238 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
3239 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3242 transaction: Some(tx.clone()),
3243 event: OnchainEvent::HTLCSpendConfirmation {
3244 commitment_tx_output_idx: input.previous_output.vout,
3245 preimage: Some(payment_preimage),
3246 on_to_local_output_csv: None,
3249 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3251 payment_preimage: Some(payment_preimage),
3253 htlc_value_satoshis: Some(amount_msat / 1000),
3256 } else if offered_preimage_claim {
3257 if !self.pending_monitor_events.iter().any(
3258 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
3259 upd.source == source
3261 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
3263 transaction: Some(tx.clone()),
3265 event: OnchainEvent::HTLCSpendConfirmation {
3266 commitment_tx_output_idx: input.previous_output.vout,
3267 preimage: Some(payment_preimage),
3268 on_to_local_output_csv: None,
3271 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
3273 payment_preimage: Some(payment_preimage),
3275 htlc_value_satoshis: Some(amount_msat / 1000),
3279 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3280 if entry.height != height { return true; }
3282 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
3283 *htlc_source != source
3288 let entry = OnchainEventEntry {
3290 transaction: Some(tx.clone()),
3292 event: OnchainEvent::HTLCUpdate {
3293 source, payment_hash,
3294 htlc_value_satoshis: Some(amount_msat / 1000),
3295 commitment_tx_output_idx: Some(input.previous_output.vout),
3298 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", log_bytes!(payment_hash.0), entry.confirmation_threshold());
3299 self.onchain_events_awaiting_threshold_conf.push(entry);
3305 /// Check if any transaction broadcasted is paying fund back to some address we can assume to own
3306 fn is_paying_spendable_output<L: Deref>(&mut self, tx: &Transaction, height: u32, logger: &L) where L::Target: Logger {
3307 let mut spendable_output = None;
3308 for (i, outp) in tx.output.iter().enumerate() { // There is max one spendable output for any channel tx, including ones generated by us
3309 if i > ::core::u16::MAX as usize {
3310 // While it is possible that an output exists on chain which is greater than the
3311 // 2^16th output in a given transaction, this is only possible if the output is not
3312 // in a lightning transaction and was instead placed there by some third party who
3313 // wishes to give us money for no reason.
3314 // Namely, any lightning transactions which we pre-sign will never have anywhere
3315 // near 2^16 outputs both because such transactions must have ~2^16 outputs who's
3316 // scripts are not longer than one byte in length and because they are inherently
3317 // non-standard due to their size.
3318 // Thus, it is completely safe to ignore such outputs, and while it may result in
3319 // us ignoring non-lightning fund to us, that is only possible if someone fills
3320 // nearly a full block with garbage just to hit this case.
3323 if outp.script_pubkey == self.destination_script {
3324 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3325 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3326 output: outp.clone(),
3330 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
3331 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
3332 spendable_output = Some(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
3333 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3334 per_commitment_point: broadcasted_holder_revokable_script.1,
3335 to_self_delay: self.on_holder_tx_csv,
3336 output: outp.clone(),
3337 revocation_pubkey: broadcasted_holder_revokable_script.2.clone(),
3338 channel_keys_id: self.channel_keys_id,
3339 channel_value_satoshis: self.channel_value_satoshis,
3344 if self.counterparty_payment_script == outp.script_pubkey {
3345 spendable_output = Some(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
3346 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3347 output: outp.clone(),
3348 channel_keys_id: self.channel_keys_id,
3349 channel_value_satoshis: self.channel_value_satoshis,
3353 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
3354 spendable_output = Some(SpendableOutputDescriptor::StaticOutput {
3355 outpoint: OutPoint { txid: tx.txid(), index: i as u16 },
3356 output: outp.clone(),
3361 if let Some(spendable_output) = spendable_output {
3362 let entry = OnchainEventEntry {
3364 transaction: Some(tx.clone()),
3366 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
3368 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
3369 self.onchain_events_awaiting_threshold_conf.push(entry);
3374 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
3376 T::Target: BroadcasterInterface,
3377 F::Target: FeeEstimator,
3380 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3381 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &*self.3);
3384 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
3385 self.0.block_disconnected(header, height, &*self.1, &*self.2, &*self.3);
3389 impl<Signer: Sign, T: Deref, F: Deref, L: Deref> chain::Confirm for (ChannelMonitor<Signer>, T, F, L)
3391 T::Target: BroadcasterInterface,
3392 F::Target: FeeEstimator,
3395 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
3396 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &*self.3);
3399 fn transaction_unconfirmed(&self, txid: &Txid) {
3400 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &*self.3);
3403 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
3404 self.0.best_block_updated(header, height, &*self.1, &*self.2, &*self.3);
3407 fn get_relevant_txids(&self) -> Vec<Txid> {
3408 self.0.get_relevant_txids()
3412 const MAX_ALLOC_SIZE: usize = 64*1024;
3414 impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3415 for (BlockHash, ChannelMonitor<Signer>) {
3416 fn read<R: io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
3417 macro_rules! unwrap_obj {
3421 Err(_) => return Err(DecodeError::InvalidValue),
3426 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
3428 let latest_update_id: u64 = Readable::read(reader)?;
3429 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
3431 let destination_script = Readable::read(reader)?;
3432 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
3434 let revokable_address = Readable::read(reader)?;
3435 let per_commitment_point = Readable::read(reader)?;
3436 let revokable_script = Readable::read(reader)?;
3437 Some((revokable_address, per_commitment_point, revokable_script))
3440 _ => return Err(DecodeError::InvalidValue),
3442 let counterparty_payment_script = Readable::read(reader)?;
3443 let shutdown_script = {
3444 let script = <Script as Readable>::read(reader)?;
3445 if script.is_empty() { None } else { Some(script) }
3448 let channel_keys_id = Readable::read(reader)?;
3449 let holder_revocation_basepoint = Readable::read(reader)?;
3450 // Technically this can fail and serialize fail a round-trip, but only for serialization of
3451 // barely-init'd ChannelMonitors that we can't do anything with.
3452 let outpoint = OutPoint {
3453 txid: Readable::read(reader)?,
3454 index: Readable::read(reader)?,
3456 let funding_info = (outpoint, Readable::read(reader)?);
3457 let current_counterparty_commitment_txid = Readable::read(reader)?;
3458 let prev_counterparty_commitment_txid = Readable::read(reader)?;
3460 let counterparty_commitment_params = Readable::read(reader)?;
3461 let funding_redeemscript = Readable::read(reader)?;
3462 let channel_value_satoshis = Readable::read(reader)?;
3464 let their_cur_per_commitment_points = {
3465 let first_idx = <U48 as Readable>::read(reader)?.0;
3469 let first_point = Readable::read(reader)?;
3470 let second_point_slice: [u8; 33] = Readable::read(reader)?;
3471 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
3472 Some((first_idx, first_point, None))
3474 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
3479 let on_holder_tx_csv: u16 = Readable::read(reader)?;
3481 let commitment_secrets = Readable::read(reader)?;
3483 macro_rules! read_htlc_in_commitment {
3486 let offered: bool = Readable::read(reader)?;
3487 let amount_msat: u64 = Readable::read(reader)?;
3488 let cltv_expiry: u32 = Readable::read(reader)?;
3489 let payment_hash: PaymentHash = Readable::read(reader)?;
3490 let transaction_output_index: Option<u32> = Readable::read(reader)?;
3492 HTLCOutputInCommitment {
3493 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
3499 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
3500 let mut counterparty_claimable_outpoints = HashMap::with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
3501 for _ in 0..counterparty_claimable_outpoints_len {
3502 let txid: Txid = Readable::read(reader)?;
3503 let htlcs_count: u64 = Readable::read(reader)?;
3504 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
3505 for _ in 0..htlcs_count {
3506 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
3508 if let Some(_) = counterparty_claimable_outpoints.insert(txid, htlcs) {
3509 return Err(DecodeError::InvalidValue);
3513 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
3514 let mut counterparty_commitment_txn_on_chain = HashMap::with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
3515 for _ in 0..counterparty_commitment_txn_on_chain_len {
3516 let txid: Txid = Readable::read(reader)?;
3517 let commitment_number = <U48 as Readable>::read(reader)?.0;
3518 if let Some(_) = counterparty_commitment_txn_on_chain.insert(txid, commitment_number) {
3519 return Err(DecodeError::InvalidValue);
3523 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
3524 let mut counterparty_hash_commitment_number = HashMap::with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
3525 for _ in 0..counterparty_hash_commitment_number_len {
3526 let payment_hash: PaymentHash = Readable::read(reader)?;
3527 let commitment_number = <U48 as Readable>::read(reader)?.0;
3528 if let Some(_) = counterparty_hash_commitment_number.insert(payment_hash, commitment_number) {
3529 return Err(DecodeError::InvalidValue);
3533 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
3534 match <u8 as Readable>::read(reader)? {
3537 Some(Readable::read(reader)?)
3539 _ => return Err(DecodeError::InvalidValue),
3541 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
3543 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
3544 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
3546 let payment_preimages_len: u64 = Readable::read(reader)?;
3547 let mut payment_preimages = HashMap::with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
3548 for _ in 0..payment_preimages_len {
3549 let preimage: PaymentPreimage = Readable::read(reader)?;
3550 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3551 if let Some(_) = payment_preimages.insert(hash, preimage) {
3552 return Err(DecodeError::InvalidValue);
3556 let pending_monitor_events_len: u64 = Readable::read(reader)?;
3557 let mut pending_monitor_events = Some(
3558 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
3559 for _ in 0..pending_monitor_events_len {
3560 let ev = match <u8 as Readable>::read(reader)? {
3561 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
3562 1 => MonitorEvent::CommitmentTxConfirmed(funding_info.0),
3563 _ => return Err(DecodeError::InvalidValue)
3565 pending_monitor_events.as_mut().unwrap().push(ev);
3568 let pending_events_len: u64 = Readable::read(reader)?;
3569 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
3570 for _ in 0..pending_events_len {
3571 if let Some(event) = MaybeReadable::read(reader)? {
3572 pending_events.push(event);
3576 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
3578 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
3579 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
3580 for _ in 0..waiting_threshold_conf_len {
3581 if let Some(val) = MaybeReadable::read(reader)? {
3582 onchain_events_awaiting_threshold_conf.push(val);
3586 let outputs_to_watch_len: u64 = Readable::read(reader)?;
3587 let mut outputs_to_watch = HashMap::with_capacity(cmp::min(outputs_to_watch_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<Txid>() + mem::size_of::<u32>() + mem::size_of::<Vec<Script>>())));
3588 for _ in 0..outputs_to_watch_len {
3589 let txid = Readable::read(reader)?;
3590 let outputs_len: u64 = Readable::read(reader)?;
3591 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<Script>())));
3592 for _ in 0..outputs_len {
3593 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
3595 if let Some(_) = outputs_to_watch.insert(txid, outputs) {
3596 return Err(DecodeError::InvalidValue);
3599 let onchain_tx_handler: OnchainTxHandler<Signer> = ReadableArgs::read(reader, keys_manager)?;
3601 let lockdown_from_offchain = Readable::read(reader)?;
3602 let holder_tx_signed = Readable::read(reader)?;
3604 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
3605 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
3606 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
3607 if prev_commitment_tx.to_self_value_sat == u64::max_value() {
3608 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
3609 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
3610 return Err(DecodeError::InvalidValue);
3614 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
3615 if current_holder_commitment_tx.to_self_value_sat == u64::max_value() {
3616 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
3617 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
3618 return Err(DecodeError::InvalidValue);
3621 let mut funding_spend_confirmed = None;
3622 let mut htlcs_resolved_on_chain = Some(Vec::new());
3623 let mut funding_spend_seen = Some(false);
3624 let mut counterparty_node_id = None;
3625 let mut confirmed_commitment_tx_counterparty_output = None;
3626 read_tlv_fields!(reader, {
3627 (1, funding_spend_confirmed, option),
3628 (3, htlcs_resolved_on_chain, vec_type),
3629 (5, pending_monitor_events, vec_type),
3630 (7, funding_spend_seen, option),
3631 (9, counterparty_node_id, option),
3632 (11, confirmed_commitment_tx_counterparty_output, option),
3635 let mut secp_ctx = Secp256k1::new();
3636 secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
3638 Ok((best_block.block_hash(), ChannelMonitor::from_impl(ChannelMonitorImpl {
3640 commitment_transaction_number_obscure_factor,
3643 broadcasted_holder_revokable_script,
3644 counterparty_payment_script,
3648 holder_revocation_basepoint,
3650 current_counterparty_commitment_txid,
3651 prev_counterparty_commitment_txid,
3653 counterparty_commitment_params,
3654 funding_redeemscript,
3655 channel_value_satoshis,
3656 their_cur_per_commitment_points,
3661 counterparty_claimable_outpoints,
3662 counterparty_commitment_txn_on_chain,
3663 counterparty_hash_commitment_number,
3665 prev_holder_signed_commitment_tx,
3666 current_holder_commitment_tx,
3667 current_counterparty_commitment_number,
3668 current_holder_commitment_number,
3671 pending_monitor_events: pending_monitor_events.unwrap(),
3674 onchain_events_awaiting_threshold_conf,
3679 lockdown_from_offchain,
3681 funding_spend_seen: funding_spend_seen.unwrap(),
3682 funding_spend_confirmed,
3683 confirmed_commitment_tx_counterparty_output,
3684 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
3687 counterparty_node_id,
3696 use bitcoin::blockdata::block::BlockHeader;
3697 use bitcoin::blockdata::script::{Script, Builder};
3698 use bitcoin::blockdata::opcodes;
3699 use bitcoin::blockdata::transaction::{Transaction, TxIn, TxOut, EcdsaSighashType};
3700 use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
3701 use bitcoin::util::sighash;
3702 use bitcoin::hashes::Hash;
3703 use bitcoin::hashes::sha256::Hash as Sha256;
3704 use bitcoin::hashes::hex::FromHex;
3705 use bitcoin::hash_types::{BlockHash, Txid};
3706 use bitcoin::network::constants::Network;
3707 use bitcoin::secp256k1::{SecretKey,PublicKey};
3708 use bitcoin::secp256k1::Secp256k1;
3712 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
3714 use super::ChannelMonitorUpdateStep;
3715 use ::{check_added_monitors, check_closed_broadcast, check_closed_event, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err};
3716 use chain::{BestBlock, Confirm};
3717 use chain::channelmonitor::ChannelMonitor;
3718 use chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
3719 use chain::transaction::OutPoint;
3720 use chain::keysinterface::InMemorySigner;
3721 use ln::{PaymentPreimage, PaymentHash};
3723 use ln::chan_utils::{HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
3724 use ln::channelmanager::PaymentSendFailure;
3725 use ln::features::InitFeatures;
3726 use ln::functional_test_utils::*;
3727 use ln::script::ShutdownScript;
3728 use util::errors::APIError;
3729 use util::events::{ClosureReason, MessageSendEventsProvider};
3730 use util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
3731 use util::ser::{ReadableArgs, Writeable};
3732 use sync::{Arc, Mutex};
3734 use bitcoin::{PackedLockTime, Sequence, TxMerkleNode, Witness};
3737 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
3738 // Previously, monitor updates were allowed freely even after a funding-spend transaction
3739 // confirmed. This would allow a race condition where we could receive a payment (including
3740 // the counterparty revoking their broadcasted state!) and accept it without recourse as
3741 // long as the ChannelMonitor receives the block first, the full commitment update dance
3742 // occurs after the block is connected, and before the ChannelManager receives the block.
3743 // Obviously this is an incredibly contrived race given the counterparty would be risking
3744 // their full channel balance for it, but its worth fixing nonetheless as it makes the
3745 // potential ChannelMonitor states simpler to reason about.
3747 // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3748 // updates is handled correctly in such conditions.
3749 let chanmon_cfgs = create_chanmon_cfgs(3);
3750 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3751 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3752 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3753 let channel = create_announced_chan_between_nodes(
3754 &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3755 create_announced_chan_between_nodes(
3756 &nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3758 // Rebalance somewhat
3759 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
3761 // First route two payments for testing at the end
3762 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3763 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
3765 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
3766 assert_eq!(local_txn.len(), 1);
3767 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
3768 assert_eq!(remote_txn.len(), 3); // Commitment and two HTLC-Timeouts
3769 check_spends!(remote_txn[1], remote_txn[0]);
3770 check_spends!(remote_txn[2], remote_txn[0]);
3771 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
3773 // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3774 // channel is now closed, but the ChannelManager doesn't know that yet.
3775 let new_header = BlockHeader {
3776 version: 2, time: 0, bits: 0, nonce: 0,
3777 prev_blockhash: nodes[0].best_block_info().0,
3778 merkle_root: TxMerkleNode::all_zeros() };
3779 let conf_height = nodes[0].best_block_info().1 + 1;
3780 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
3781 &[(0, broadcast_tx)], conf_height);
3783 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
3784 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
3785 &nodes[1].keys_manager.backing).unwrap();
3787 // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3788 // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3789 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
3790 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)),
3791 true, APIError::ChannelUnavailable { ref err },
3792 assert!(err.contains("ChannelMonitor storage failure")));
3793 check_added_monitors!(nodes[1], 2); // After the failure we generate a close-channel monitor update
3794 check_closed_broadcast!(nodes[1], true);
3795 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "ChannelMonitor storage failure".to_string() });
3797 // Build a new ChannelMonitorUpdate which contains both the failing commitment tx update
3798 // and provides the claim preimages for the two pending HTLCs. The first update generates
3799 // an error, but the point of this test is to ensure the later updates are still applied.
3800 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
3801 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().skip(1).next().unwrap().clone();
3802 assert_eq!(replay_update.updates.len(), 1);
3803 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
3804 } else { panic!(); }
3805 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_1 });
3806 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage: payment_preimage_2 });
3808 let broadcaster = TestBroadcaster::new(Arc::clone(&nodes[1].blocks));
3810 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
3812 // Even though we error'd on the first update, we should still have generated an HTLC claim
3814 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3815 assert!(txn_broadcasted.len() >= 2);
3816 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
3817 assert_eq!(tx.input.len(), 1);
3818 tx.input[0].previous_output.txid == broadcast_tx.txid()
3819 }).collect::<Vec<_>>();
3820 assert_eq!(htlc_txn.len(), 2);
3821 check_spends!(htlc_txn[0], broadcast_tx);
3822 check_spends!(htlc_txn[1], broadcast_tx);
3825 fn test_funding_spend_refuses_updates() {
3826 do_test_funding_spend_refuses_updates(true);
3827 do_test_funding_spend_refuses_updates(false);
3831 fn test_prune_preimages() {
3832 let secp_ctx = Secp256k1::new();
3833 let logger = Arc::new(TestLogger::new());
3834 let broadcaster = Arc::new(TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))});
3835 let fee_estimator = TestFeeEstimator { sat_per_kw: Mutex::new(253) };
3837 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3838 let dummy_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
3840 let mut preimages = Vec::new();
3843 let preimage = PaymentPreimage([i; 32]);
3844 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).into_inner());
3845 preimages.push((preimage, hash));
3849 macro_rules! preimages_slice_to_htlc_outputs {
3850 ($preimages_slice: expr) => {
3852 let mut res = Vec::new();
3853 for (idx, preimage) in $preimages_slice.iter().enumerate() {
3854 res.push((HTLCOutputInCommitment {
3858 payment_hash: preimage.1.clone(),
3859 transaction_output_index: Some(idx as u32),
3866 macro_rules! preimages_to_holder_htlcs {
3867 ($preimages_slice: expr) => {
3869 let mut inp = preimages_slice_to_htlc_outputs!($preimages_slice);
3870 let res: Vec<_> = inp.drain(..).map(|e| { (e.0, None, e.1) }).collect();
3876 macro_rules! test_preimages_exist {
3877 ($preimages_slice: expr, $monitor: expr) => {
3878 for preimage in $preimages_slice {
3879 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
3884 let keys = InMemorySigner::new(
3886 SecretKey::from_slice(&[41; 32]).unwrap(),
3887 SecretKey::from_slice(&[41; 32]).unwrap(),
3888 SecretKey::from_slice(&[41; 32]).unwrap(),
3889 SecretKey::from_slice(&[41; 32]).unwrap(),
3890 SecretKey::from_slice(&[41; 32]).unwrap(),
3891 SecretKey::from_slice(&[41; 32]).unwrap(),
3897 let counterparty_pubkeys = ChannelPublicKeys {
3898 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
3899 revocation_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap()),
3900 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
3901 delayed_payment_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap()),
3902 htlc_basepoint: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())
3904 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::max_value() };
3905 let channel_parameters = ChannelTransactionParameters {
3906 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
3907 holder_selected_contest_delay: 66,
3908 is_outbound_from_holder: true,
3909 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
3910 pubkeys: counterparty_pubkeys,
3911 selected_contest_delay: 67,
3913 funding_outpoint: Some(funding_outpoint),
3916 // Prune with one old state and a holder commitment tx holding a few overlaps with the
3918 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
3919 let best_block = BestBlock::from_genesis(Network::Testnet);
3920 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
3921 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &Script::new(),
3922 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, Script::new()),
3923 &channel_parameters,
3924 Script::new(), 46, 0,
3925 HolderCommitmentTransaction::dummy(), best_block, dummy_key);
3927 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..10])).unwrap();
3928 let dummy_txid = dummy_tx.txid();
3929 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
3930 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
3931 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
3932 monitor.provide_latest_counterparty_commitment_tx(dummy_txid, preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
3933 for &(ref preimage, ref hash) in preimages.iter() {
3934 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
3935 monitor.provide_payment_preimage(hash, preimage, &broadcaster, &bounded_fee_estimator, &logger);
3938 // Now provide a secret, pruning preimages 10-15
3939 let mut secret = [0; 32];
3940 secret[0..32].clone_from_slice(&hex::decode("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
3941 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
3942 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
3943 test_preimages_exist!(&preimages[0..10], monitor);
3944 test_preimages_exist!(&preimages[15..20], monitor);
3946 // Now provide a further secret, pruning preimages 15-17
3947 secret[0..32].clone_from_slice(&hex::decode("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
3948 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
3949 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
3950 test_preimages_exist!(&preimages[0..10], monitor);
3951 test_preimages_exist!(&preimages[17..20], monitor);
3953 // Now update holder commitment tx info, pruning only element 18 as we still care about the
3954 // previous commitment tx's preimages too
3955 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..5])).unwrap();
3956 secret[0..32].clone_from_slice(&hex::decode("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
3957 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
3958 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
3959 test_preimages_exist!(&preimages[0..10], monitor);
3960 test_preimages_exist!(&preimages[18..20], monitor);
3962 // But if we do it again, we'll prune 5-10
3963 monitor.provide_latest_holder_commitment_tx(HolderCommitmentTransaction::dummy(), preimages_to_holder_htlcs!(preimages[0..3])).unwrap();
3964 secret[0..32].clone_from_slice(&hex::decode("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
3965 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
3966 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
3967 test_preimages_exist!(&preimages[0..5], monitor);
3971 fn test_claim_txn_weight_computation() {
3972 // We test Claim txn weight, knowing that we want expected weigth and
3973 // not actual case to avoid sigs and time-lock delays hell variances.
3975 let secp_ctx = Secp256k1::new();
3976 let privkey = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
3977 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
3979 macro_rules! sign_input {
3980 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
3981 let htlc = HTLCOutputInCommitment {
3982 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
3984 cltv_expiry: 2 << 16,
3985 payment_hash: PaymentHash([1; 32]),
3986 transaction_output_index: Some($idx as u32),
3988 let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&pubkey, 256, &pubkey) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &pubkey, &pubkey, &pubkey) };
3989 let sighash = hash_to_message!(&$sighash_parts.segwit_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
3990 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
3991 let mut ser_sig = sig.serialize_der().to_vec();
3992 ser_sig.push(EcdsaSighashType::All as u8);
3993 $sum_actual_sigs += ser_sig.len();
3994 let witness = $sighash_parts.witness_mut($idx).unwrap();
3995 witness.push(ser_sig);
3996 if *$weight == WEIGHT_REVOKED_OUTPUT {
3997 witness.push(vec!(1));
3998 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
3999 witness.push(pubkey.clone().serialize().to_vec());
4000 } else if *$weight == weight_received_htlc($opt_anchors) {
4001 witness.push(vec![0]);
4003 witness.push(PaymentPreimage([1; 32]).0.to_vec());
4005 witness.push(redeem_script.into_bytes());
4006 let witness = witness.to_vec();
4007 println!("witness[0] {}", witness[0].len());
4008 println!("witness[1] {}", witness[1].len());
4009 println!("witness[2] {}", witness[2].len());
4013 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
4014 let txid = Txid::from_hex("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
4016 // Justice tx with 1 to_holder, 2 revoked offered HTLCs, 1 revoked received HTLCs
4017 for &opt_anchors in [false, true].iter() {
4018 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4019 let mut sum_actual_sigs = 0;
4021 claim_tx.input.push(TxIn {
4022 previous_output: BitcoinOutPoint {
4026 script_sig: Script::new(),
4027 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4028 witness: Witness::new(),
4031 claim_tx.output.push(TxOut {
4032 script_pubkey: script_pubkey.clone(),
4035 let base_weight = claim_tx.weight();
4036 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(opt_anchors), weight_revoked_offered_htlc(opt_anchors), weight_revoked_received_htlc(opt_anchors)];
4037 let mut inputs_total_weight = 2; // count segwit flags
4039 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4040 for (idx, inp) in inputs_weight.iter().enumerate() {
4041 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4042 inputs_total_weight += inp;
4045 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4048 // Claim tx with 1 offered HTLCs, 3 received HTLCs
4049 for &opt_anchors in [false, true].iter() {
4050 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4051 let mut sum_actual_sigs = 0;
4053 claim_tx.input.push(TxIn {
4054 previous_output: BitcoinOutPoint {
4058 script_sig: Script::new(),
4059 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4060 witness: Witness::new(),
4063 claim_tx.output.push(TxOut {
4064 script_pubkey: script_pubkey.clone(),
4067 let base_weight = claim_tx.weight();
4068 let inputs_weight = vec![weight_offered_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors), weight_received_htlc(opt_anchors)];
4069 let mut inputs_total_weight = 2; // count segwit flags
4071 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4072 for (idx, inp) in inputs_weight.iter().enumerate() {
4073 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4074 inputs_total_weight += inp;
4077 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_sig */ (73 * inputs_weight.len() - sum_actual_sigs));
4080 // Justice tx with 1 revoked HTLC-Success tx output
4081 for &opt_anchors in [false, true].iter() {
4082 let mut claim_tx = Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() };
4083 let mut sum_actual_sigs = 0;
4084 claim_tx.input.push(TxIn {
4085 previous_output: BitcoinOutPoint {
4089 script_sig: Script::new(),
4090 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
4091 witness: Witness::new(),
4093 claim_tx.output.push(TxOut {
4094 script_pubkey: script_pubkey.clone(),
4097 let base_weight = claim_tx.weight();
4098 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
4099 let mut inputs_total_weight = 2; // count segwit flags
4101 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
4102 for (idx, inp) in inputs_weight.iter().enumerate() {
4103 sign_input!(sighash_parts, idx, 0, inp, sum_actual_sigs, opt_anchors);
4104 inputs_total_weight += inp;
4107 assert_eq!(base_weight + inputs_total_weight as usize, claim_tx.weight() + /* max_length_isg */ (73 * inputs_weight.len() - sum_actual_sigs));
4111 // Further testing is done in the ChannelManager integration tests.