1use bitcoin::amount::Amount;
24use bitcoin::block::Header;
25use bitcoin::script::{Script, ScriptBuf};
26use bitcoin::transaction::{OutPoint as BitcoinOutPoint, Transaction, TxOut};
27
28use bitcoin::hash_types::{BlockHash, Txid};
29use bitcoin::hashes::sha256::Hash as Sha256;
30use bitcoin::hashes::Hash;
31
32use bitcoin::ecdsa::Signature as BitcoinSignature;
33use bitcoin::secp256k1::{self, ecdsa::Signature, PublicKey, Secp256k1, SecretKey};
34
35use crate::chain;
36use crate::chain::chaininterface::{
37 BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator,
38};
39use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler};
40use crate::chain::package::{
41 CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput,
42 HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedHTLCOutput, RevokedOutput,
43};
44use crate::chain::transaction::{OutPoint, TransactionData};
45use crate::chain::{BlockLocator, WatchedOutput};
46use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent};
47use crate::events::{ClosureReason, Event, EventHandler, FundingInfo, ReplayEvent};
48use crate::ln::chan_utils::{
49 self, ChannelTransactionParameters, CommitmentTransaction, CounterpartyCommitmentSecrets,
50 HTLCClaim, HTLCOutputInCommitment, HolderCommitmentTransaction,
51};
52use crate::ln::channel::INITIAL_COMMITMENT_NUMBER;
53use crate::ln::channel_keys::{
54 DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint,
55 RevocationKey,
56};
57use crate::ln::channelmanager::{HTLCSource, PaymentClaimDetails, SentHTLCId};
58use crate::ln::funding::FundingContribution;
59use crate::ln::msgs::DecodeError;
60use crate::ln::types::ChannelId;
61use crate::sign::{
62 ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, DelayedPaymentOutputDescriptor,
63 EntropySource, HTLCDescriptor, SignerProvider, SpendableOutputDescriptor,
64 StaticPaymentOutputDescriptor,
65};
66use crate::types::features::ChannelTypeFeatures;
67use crate::types::payment::{PaymentHash, PaymentPreimage};
68use crate::util::byte_utils;
69use crate::util::logger::{Logger, WithContext};
70use crate::util::persist::MonitorName;
71use crate::util::ser::{
72 MaybeReadable, Readable, ReadableArgs, RequiredWrapper, UpgradableRequired, Writeable, Writer,
73 U48,
74};
75
76#[allow(unused_imports)]
77use crate::prelude::*;
78
79use crate::io::{self, Error};
80use crate::sync::Mutex;
81use core::ops::Deref;
82use core::{cmp, mem};
83
84#[derive(Clone, Debug, PartialEq, Eq)]
92#[must_use]
93pub struct ChannelMonitorUpdate {
94 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
95 pub update_id: u64,
109 pub channel_id: Option<ChannelId>,
114}
115
116impl ChannelMonitorUpdate {
117 pub(crate) fn internal_renegotiated_funding_data(
118 &self,
119 ) -> impl Iterator<Item = (OutPoint, ScriptBuf)> + '_ {
120 self.updates.iter().filter_map(|update| match update {
121 ChannelMonitorUpdateStep::RenegotiatedFunding { channel_parameters, .. } => {
122 let funding_outpoint = channel_parameters
123 .funding_outpoint
124 .expect("Renegotiated funding must always have known outpoint");
125 let funding_script = channel_parameters.make_funding_redeemscript().to_p2wsh();
126 Some((funding_outpoint, funding_script))
127 },
128 _ => None,
129 })
130 }
131
132 #[cfg(c_bindings)]
135 pub fn renegotiated_funding_data(&self) -> Vec<(OutPoint, ScriptBuf)> {
136 self.internal_renegotiated_funding_data().collect()
137 }
138
139 #[cfg(not(c_bindings))]
142 pub fn renegotiated_funding_data(&self) -> impl Iterator<Item = (OutPoint, ScriptBuf)> + '_ {
143 self.internal_renegotiated_funding_data()
144 }
145}
146
147const LEGACY_CLOSED_CHANNEL_UPDATE_ID: u64 = u64::MAX;
150
151impl Writeable for ChannelMonitorUpdate {
152 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
153 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
154 self.update_id.write(w)?;
155 (self.updates.len() as u64).write(w)?;
156 for update_step in self.updates.iter() {
157 update_step.write(w)?;
158 }
159 write_tlv_fields!(w, {
160 (3, self.channel_id, option),
162 });
163 Ok(())
164 }
165}
166impl Readable for ChannelMonitorUpdate {
167 #[rustfmt::skip]
168 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
169 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
170 let update_id: u64 = Readable::read(r)?;
171 let len: u64 = Readable::read(r)?;
172 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
173 for _ in 0..len {
174 if let Some(upd) = MaybeReadable::read(r)? {
175 updates.push(upd);
176 }
177 }
178 let mut channel_id = None;
179 read_tlv_fields!(r, {
180 (3, channel_id, option),
182 });
183 Ok(Self { update_id, updates, channel_id })
184 }
185}
186
187#[derive(Clone, PartialEq, Eq)]
189pub enum MonitorEvent {
190 HTLCEvent(HTLCUpdate),
192
193 HolderForceClosedWithInfo {
196 reason: ClosureReason,
198 outpoint: OutPoint,
200 channel_id: ChannelId,
202 },
203
204 HolderForceClosed(OutPoint),
207
208 CommitmentTxConfirmed(()),
211
212 Completed {
217 funding_txo: OutPoint,
219 channel_id: ChannelId,
221 monitor_update_id: u64,
227 },
228}
229impl_writeable_tlv_based_enum_upgradable_legacy!(MonitorEvent,
230 (0, Completed) => {
233 (0, funding_txo, required),
234 (2, monitor_update_id, required),
235 (4, channel_id, required),
236 },
237 (5, HolderForceClosedWithInfo) => {
238 (0, reason, upgradable_required),
239 (2, outpoint, required),
240 (4, channel_id, required),
241 },
242;
243 (1, CommitmentTxConfirmed),
244 (2, HTLCEvent),
245 (4, HolderForceClosed),
246 );
248
249#[derive(Clone, PartialEq, Eq)]
253pub struct HTLCUpdate {
254 pub(crate) payment_hash: PaymentHash,
255 pub(crate) payment_preimage: Option<PaymentPreimage>,
256 pub(crate) source: HTLCSource,
257 pub(crate) htlc_value_satoshis: u64,
258}
259impl_writeable_tlv_based!(HTLCUpdate, {
260 (0, payment_hash, required),
261 (1, htlc_value_satoshis, required),
262 (2, source, required),
263 (4, payment_preimage, option),
264});
265
266pub(crate) const COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE: u32 = 12;
270
271const _: () = assert!(MAX_BLOCKS_FOR_CONF > COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE);
275
276pub(crate) const MAX_BLOCKS_FOR_CONF: u32 = 18;
278
279pub(crate) const CLTV_CLAIM_BUFFER: u32 = MAX_BLOCKS_FOR_CONF * 2;
285pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
298pub const ANTI_REORG_DELAY: u32 = 6;
310pub const ARCHIVAL_DELAY_BLOCKS: u32 = 4032;
314pub const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
331
332#[derive(Clone, PartialEq, Eq)]
334struct HolderSignedTx {
335 txid: Txid,
337 revocation_key: RevocationKey,
338 a_htlc_key: HtlcKey,
339 b_htlc_key: HtlcKey,
340 delayed_payment_key: DelayedPaymentKey,
341 per_commitment_point: PublicKey,
342 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
343 to_self_value_sat: u64,
344 feerate_per_kw: u32,
345}
346
347impl_writeable_tlv_based!(HolderSignedTx, {
349 (0, txid, required),
350 (1, to_self_value_sat, required), (2, revocation_key, required),
352 (4, a_htlc_key, required),
353 (6, b_htlc_key, required),
354 (8, delayed_payment_key, required),
355 (10, per_commitment_point, required),
356 (12, feerate_per_kw, required),
357 (14, htlc_outputs, required_vec)
358});
359
360#[rustfmt::skip]
362fn write_legacy_holder_commitment_data<W: Writer>(
363 writer: &mut W, commitment_tx: &HolderCommitmentTransaction, htlc_data: &CommitmentHTLCData,
364) -> Result<(), io::Error> {
365 let trusted_tx = commitment_tx.trust();
366 let tx_keys = trusted_tx.keys();
367
368 let txid = trusted_tx.txid();
369 let to_self_value_sat = commitment_tx.to_broadcaster_value_sat();
370 let feerate_per_kw = trusted_tx.negotiated_feerate_per_kw();
371 let revocation_key = &tx_keys.revocation_key;
372 let a_htlc_key = &tx_keys.broadcaster_htlc_key;
373 let b_htlc_key = &tx_keys.countersignatory_htlc_key;
374 let delayed_payment_key = &tx_keys.broadcaster_delayed_payment_key;
375 let per_commitment_point = &tx_keys.per_commitment_point;
376
377 let mut nondust_htlcs = commitment_tx.nondust_htlcs().iter()
378 .zip(commitment_tx.counterparty_htlc_sigs.iter());
379 let mut sources = htlc_data.nondust_htlc_sources.iter();
380
381 let nondust_htlcs = core::iter::from_fn(move || {
383 let (htlc, counterparty_htlc_sig) = if let Some(nondust_htlc) = nondust_htlcs.next() {
384 nondust_htlc
385 } else {
386 assert!(sources.next().is_none());
387 return None;
388 };
389
390 let mut source = None;
391 if htlc.offered {
392 source = sources.next();
393 if source.is_none() {
394 panic!("Every offered non-dust HTLC should have a corresponding source");
395 }
396 }
397 Some((htlc, Some(counterparty_htlc_sig), source))
398 });
399
400 let dust_htlcs = htlc_data.dust_htlcs.iter()
402 .map(|(htlc, source)| (htlc, None::<&Signature>, source.as_ref()));
403 let htlc_outputs = crate::util::ser::IterableOwned(nondust_htlcs.chain(dust_htlcs));
404
405 write_tlv_fields!(writer, {
406 (0, txid, required),
407 (1, to_self_value_sat, required),
408 (2, revocation_key, required),
409 (4, a_htlc_key, required),
410 (6, b_htlc_key, required),
411 (8, delayed_payment_key, required),
412 (10, per_commitment_point, required),
413 (12, feerate_per_kw, required),
414 (14, htlc_outputs, required),
415 });
416
417 Ok(())
418}
419
420#[derive(Clone, PartialEq, Eq)]
423struct CounterpartyCommitmentParameters {
424 counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
425 counterparty_htlc_base_key: HtlcBasepoint,
426 on_counterparty_tx_csv: u16,
427}
428
429impl Writeable for CounterpartyCommitmentParameters {
430 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
431 w.write_all(&0u64.to_be_bytes())?;
432 write_tlv_fields!(w, {
433 (0, self.counterparty_delayed_payment_base_key, required),
434 (2, self.counterparty_htlc_base_key, required),
435 (4, self.on_counterparty_tx_csv, required),
436 });
437 Ok(())
438 }
439}
440impl Readable for CounterpartyCommitmentParameters {
441 #[rustfmt::skip]
442 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
443 let counterparty_commitment_transaction = {
444 let per_htlc_len: u64 = Readable::read(r)?;
447 for _ in 0..per_htlc_len {
448 let _txid: Txid = Readable::read(r)?;
449 let htlcs_count: u64 = Readable::read(r)?;
450 for _ in 0..htlcs_count {
451 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
452 }
453 }
454
455 let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
456 let mut counterparty_htlc_base_key = RequiredWrapper(None);
457 let mut on_counterparty_tx_csv: u16 = 0;
458 read_tlv_fields!(r, {
459 (0, counterparty_delayed_payment_base_key, required),
460 (2, counterparty_htlc_base_key, required),
461 (4, on_counterparty_tx_csv, required),
462 });
463 CounterpartyCommitmentParameters {
464 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
465 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
466 on_counterparty_tx_csv,
467 }
468 };
469 Ok(counterparty_commitment_transaction)
470 }
471}
472
473#[derive(Clone, PartialEq, Eq)]
478struct OnchainEventEntry {
479 txid: Txid,
480 height: u32,
481 block_hash: Option<BlockHash>, event: OnchainEvent,
483 transaction: Option<Transaction>, }
485
486impl OnchainEventEntry {
487 #[rustfmt::skip]
488 fn confirmation_threshold(&self) -> u32 {
489 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
490 match self.event {
491 OnchainEvent::MaturingOutput {
492 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
493 } => {
494 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
497 },
498 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
499 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
500 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
503 },
504 _ => {},
505 }
506 conf_threshold
507 }
508
509 fn has_reached_confirmation_threshold(&self, best_block: &BlockLocator) -> bool {
510 best_block.height >= self.confirmation_threshold()
511 }
512}
513
514type CommitmentTxCounterpartyOutputInfo = Option<(u32, Amount)>;
518
519#[derive(Clone, PartialEq, Eq)]
522enum OnchainEvent {
523 HTLCUpdate {
530 source: HTLCSource,
531 payment_hash: PaymentHash,
532 htlc_value_satoshis: u64,
533 commitment_tx_output_idx: Option<u32>,
536 },
537 MaturingOutput { descriptor: SpendableOutputDescriptor },
540 FundingSpendConfirmation {
543 on_local_output_csv: Option<u16>,
546 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
552 },
553 HTLCSpendConfirmation {
565 commitment_tx_output_idx: u32,
566 preimage: Option<PaymentPreimage>,
568 on_to_local_output_csv: Option<u16>,
572 },
573 AlternativeFundingConfirmation {},
580}
581
582impl Writeable for OnchainEventEntry {
583 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
584 write_tlv_fields!(writer, {
585 (0, self.txid, required),
586 (1, self.transaction, option),
587 (2, self.height, required),
588 (3, self.block_hash, option),
589 (4, self.event, required),
590 });
591 Ok(())
592 }
593}
594
595impl MaybeReadable for OnchainEventEntry {
596 #[rustfmt::skip]
597 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
598 let mut txid = Txid::all_zeros();
599 let mut transaction = None;
600 let mut block_hash = None;
601 let mut height = 0;
602 let mut event = UpgradableRequired(None);
603 read_tlv_fields!(reader, {
604 (0, txid, required),
605 (1, transaction, option),
606 (2, height, required),
607 (3, block_hash, option),
608 (4, event, upgradable_required),
609 });
610 Ok(Some(Self { txid, transaction, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
611 }
612}
613
614impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
615 (0, HTLCUpdate) => {
616 (0, source, required),
617 (1, htlc_value_satoshis, required),
618 (2, payment_hash, required),
619 (3, commitment_tx_output_idx, option),
620 },
621 (1, MaturingOutput) => {
622 (0, descriptor, required),
623 },
624 (2, AlternativeFundingConfirmation) => {},
625 (3, FundingSpendConfirmation) => {
626 (0, on_local_output_csv, option),
627 (1, commitment_tx_to_counterparty_output, option),
628 },
629 (5, HTLCSpendConfirmation) => {
630 (0, commitment_tx_output_idx, required),
631 (2, preimage, option),
632 (4, on_to_local_output_csv, option),
633 },
634);
635
636#[derive(Clone, Debug, PartialEq, Eq)]
637pub(crate) enum ChannelMonitorUpdateStep {
638 LatestHolderCommitmentTXInfo {
639 commitment_tx: HolderCommitmentTransaction,
640 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
647 claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
648 nondust_htlc_sources: Vec<HTLCSource>,
649 },
650 LatestHolderCommitment {
651 commitment_txs: Vec<HolderCommitmentTransaction>,
652 htlc_data: CommitmentHTLCData,
653 claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
654 },
655 LatestCounterpartyCommitmentTXInfo {
656 commitment_txid: Txid,
657 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
658 commitment_number: u64,
659 their_per_commitment_point: PublicKey,
660 feerate_per_kw: Option<u32>,
661 to_broadcaster_value_sat: Option<u64>,
662 to_countersignatory_value_sat: Option<u64>,
663 },
664 LatestCounterpartyCommitment {
665 commitment_txs: Vec<CommitmentTransaction>,
666 htlc_data: CommitmentHTLCData,
667 },
668 PaymentPreimage {
669 payment_preimage: PaymentPreimage,
670 payment_info: Option<PaymentClaimDetails>,
673 },
674 CommitmentSecret {
675 idx: u64,
676 secret: [u8; 32],
677 },
678 ChannelForceClosed {
681 should_broadcast: bool,
684 counterparty_failed_htlcs: Vec<(HTLCSource, PaymentHash)>,
688 },
689 ShutdownScript {
690 scriptpubkey: ScriptBuf,
691 },
692 RenegotiatedFunding {
693 channel_parameters: ChannelTransactionParameters,
694 holder_commitment_tx: HolderCommitmentTransaction,
695 counterparty_commitment_tx: CommitmentTransaction,
696 funding_contribution: Option<FundingContribution>,
697 },
698 RenegotiatedFundingLocked {
699 funding_txid: Txid,
700 },
701 ReleasePaymentComplete {
713 htlc: SentHTLCId,
714 },
715}
716
717impl ChannelMonitorUpdateStep {
718 #[rustfmt::skip]
719 fn variant_name(&self) -> &'static str {
720 match self {
721 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
722 ChannelMonitorUpdateStep::LatestHolderCommitment { .. } => "LatestHolderCommitment",
723 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
724 ChannelMonitorUpdateStep::LatestCounterpartyCommitment { .. } => "LatestCounterpartyCommitment",
725 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
726 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
727 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
728 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
729 ChannelMonitorUpdateStep::RenegotiatedFunding { .. } => "RenegotiatedFunding",
730 ChannelMonitorUpdateStep::RenegotiatedFundingLocked { .. } => "RenegotiatedFundingLocked",
731 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => "ReleasePaymentComplete",
732 }
733 }
734}
735
736impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
737 (0, LatestHolderCommitmentTXInfo) => {
738 (0, commitment_tx, required),
739 (1, claimed_htlcs, optional_vec),
740 (2, htlc_outputs, required_vec),
741 (4, nondust_htlc_sources, optional_vec),
742 },
743 (1, LatestCounterpartyCommitmentTXInfo) => {
744 (0, commitment_txid, required),
745 (1, feerate_per_kw, option),
746 (2, commitment_number, required),
747 (3, to_broadcaster_value_sat, option),
748 (4, their_per_commitment_point, required),
749 (5, to_countersignatory_value_sat, option),
750 (6, htlc_outputs, required_vec),
751 },
752 (2, PaymentPreimage) => {
753 (0, payment_preimage, required),
754 (1, payment_info, option),
755 },
756 (3, CommitmentSecret) => {
757 (0, idx, required),
758 (2, secret, required),
759 },
760 (4, ChannelForceClosed) => {
761 (0, should_broadcast, required),
762 (1, counterparty_failed_htlcs, optional_vec),
763 },
764 (5, ShutdownScript) => {
765 (0, scriptpubkey, required),
766 },
767 (6, LatestCounterpartyCommitment) => {
768 (1, commitment_txs, required_vec),
769 (3, htlc_data, required),
770 },
771 (7, ReleasePaymentComplete) => {
772 (1, htlc, required),
773 },
774 (8, LatestHolderCommitment) => {
775 (1, commitment_txs, required_vec),
776 (3, htlc_data, required),
777 (5, claimed_htlcs, required_vec),
778 },
779 (10, RenegotiatedFunding) => {
780 (1, channel_parameters, (required: ReadableArgs, None)),
781 (3, holder_commitment_tx, required),
782 (5, counterparty_commitment_tx, required),
783 (7, funding_contribution, option),
784 },
785 (12, RenegotiatedFundingLocked) => {
786 (1, funding_txid, required),
787 },
788);
789
790#[derive(Clone, Debug, PartialEq, Eq)]
793#[cfg_attr(test, derive(PartialOrd, Ord))]
794pub enum BalanceSource {
795 HolderForceClosed,
797 CounterpartyForceClosed,
799 CoopClose,
801 Htlc,
803}
804
805#[derive(Clone, Debug, PartialEq, Eq)]
807#[cfg_attr(test, derive(PartialOrd, Ord))]
808pub struct HolderCommitmentTransactionBalance {
809 pub amount_satoshis: u64,
812 pub transaction_fee_satoshis: u64,
821}
822
823#[derive(Clone, Debug, PartialEq, Eq)]
828#[cfg_attr(test, derive(PartialOrd, Ord))]
829pub enum Balance {
830 ClaimableOnChannelClose {
833 balance_candidates: Vec<HolderCommitmentTransactionBalance>,
851 confirmed_balance_candidate_index: usize,
856 outbound_payment_htlc_rounded_msat: u64,
865 outbound_forwarded_htlc_rounded_msat: u64,
873 inbound_claiming_htlc_rounded_msat: u64,
883 inbound_htlc_rounded_msat: u64,
892 },
893 ClaimableAwaitingConfirmations {
896 amount_satoshis: u64,
899 confirmation_height: u32,
902 source: BalanceSource,
904 },
905 ContentiousClaimable {
913 amount_satoshis: u64,
916 timeout_height: u32,
919 payment_hash: PaymentHash,
921 payment_preimage: PaymentPreimage,
923 },
924 MaybeTimeoutClaimableHTLC {
928 amount_satoshis: u64,
931 claimable_height: u32,
934 payment_hash: PaymentHash,
936 outbound_payment: bool,
940 },
941 MaybePreimageClaimableHTLC {
945 amount_satoshis: u64,
948 expiry_height: u32,
951 payment_hash: PaymentHash,
953 },
954 CounterpartyRevokedOutputClaimable {
960 amount_satoshis: u64,
965 },
966}
967
968impl Balance {
969 #[rustfmt::skip]
989 pub fn claimable_amount_satoshis(&self) -> u64 {
990 match self {
991 Balance::ClaimableOnChannelClose {
992 balance_candidates, confirmed_balance_candidate_index, ..
993 } => {
994 if *confirmed_balance_candidate_index != 0 {
995 balance_candidates[*confirmed_balance_candidate_index].amount_satoshis
996 } else {
997 balance_candidates.last().map(|balance| balance.amount_satoshis).unwrap_or(0)
998 }
999 },
1000 Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
1001 Balance::ContentiousClaimable { amount_satoshis, .. }|
1002 Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
1003 => *amount_satoshis,
1004 Balance::MaybeTimeoutClaimableHTLC { amount_satoshis, outbound_payment, .. }
1005 => if *outbound_payment { 0 } else { *amount_satoshis },
1006 Balance::MaybePreimageClaimableHTLC { .. } => 0,
1007 }
1008 }
1009}
1010
1011#[derive(Clone, PartialEq, Eq)]
1013struct IrrevocablyResolvedHTLC {
1014 commitment_tx_output_idx: Option<u32>,
1015 resolving_txid: Option<Txid>, resolving_tx: Option<Transaction>,
1020 payment_preimage: Option<PaymentPreimage>,
1022}
1023
1024impl Writeable for IrrevocablyResolvedHTLC {
1029 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1030 let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::MAX);
1031 write_tlv_fields!(writer, {
1032 (0, mapped_commitment_tx_output_idx, required),
1033 (1, self.resolving_txid, option),
1034 (2, self.payment_preimage, option),
1035 (3, self.resolving_tx, option),
1036 });
1037 Ok(())
1038 }
1039}
1040
1041impl Readable for IrrevocablyResolvedHTLC {
1042 #[rustfmt::skip]
1043 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1044 let mut mapped_commitment_tx_output_idx = 0;
1045 let mut resolving_txid = None;
1046 let mut payment_preimage = None;
1047 let mut resolving_tx = None;
1048 read_tlv_fields!(reader, {
1049 (0, mapped_commitment_tx_output_idx, required),
1050 (1, resolving_txid, option),
1051 (2, payment_preimage, option),
1052 (3, resolving_tx, option),
1053 });
1054 Ok(Self {
1055 commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::MAX { None } else { Some(mapped_commitment_tx_output_idx) },
1056 resolving_txid,
1057 payment_preimage,
1058 resolving_tx,
1059 })
1060 }
1061}
1062
1063pub struct ChannelMonitor<Signer: EcdsaChannelSigner> {
1085 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
1086}
1087
1088impl<Signer: EcdsaChannelSigner> Clone for ChannelMonitor<Signer>
1089where
1090 Signer: Clone,
1091{
1092 fn clone(&self) -> Self {
1093 let inner = self.inner.lock().unwrap().clone();
1094 ChannelMonitor::from_impl(inner)
1095 }
1096}
1097
1098#[derive(Clone, Debug, PartialEq, Eq)]
1099pub(crate) struct CommitmentHTLCData {
1100 pub nondust_htlc_sources: Vec<HTLCSource>,
1103 pub dust_htlcs: Vec<(HTLCOutputInCommitment, Option<HTLCSource>)>,
1104}
1105
1106impl CommitmentHTLCData {
1107 fn new() -> Self {
1108 Self { nondust_htlc_sources: Vec::new(), dust_htlcs: Vec::new() }
1109 }
1110}
1111
1112impl_writeable_tlv_based!(CommitmentHTLCData, {
1113 (1, nondust_htlc_sources, required_vec),
1114 (3, dust_htlcs, required_vec),
1115});
1116
1117impl TryFrom<HolderSignedTx> for CommitmentHTLCData {
1118 type Error = ();
1119 #[rustfmt::skip]
1120 fn try_from(value: HolderSignedTx) -> Result<Self, Self::Error> {
1121 let mut missing_nondust_source = false;
1125 let mut nondust_htlc_sources = Vec::with_capacity(value.htlc_outputs.len());
1126 let dust_htlcs = value.htlc_outputs.into_iter().filter_map(|(htlc, _, source)| {
1127 if htlc.transaction_output_index.is_none() {
1130 return Some((htlc, source))
1131 }
1132 if htlc.offered {
1133 if let Some(source) = source {
1134 nondust_htlc_sources.push(source);
1135 } else {
1136 missing_nondust_source = true;
1137 }
1138 }
1139 None
1140 }).collect();
1141 if missing_nondust_source {
1142 return Err(());
1143 }
1144
1145 Ok(Self {
1146 nondust_htlc_sources,
1147 dust_htlcs,
1148 })
1149 }
1150}
1151
1152#[derive(Clone, PartialEq)]
1153struct FundingScope {
1154 channel_parameters: ChannelTransactionParameters,
1155
1156 current_counterparty_commitment_txid: Option<Txid>,
1157 prev_counterparty_commitment_txid: Option<Txid>,
1158
1159 counterparty_claimable_outpoints:
1169 HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
1170
1171 current_holder_commitment_tx: HolderCommitmentTransaction,
1176 prev_holder_commitment_tx: Option<HolderCommitmentTransaction>,
1177
1178 contribution: Option<FundingContribution>,
1180}
1181
1182impl FundingScope {
1183 fn funding_outpoint(&self) -> OutPoint {
1184 let funding_outpoint = self.channel_parameters.funding_outpoint.as_ref();
1185 *funding_outpoint.expect("Funding outpoint must be set for active monitor")
1186 }
1187
1188 fn funding_txid(&self) -> Txid {
1189 self.funding_outpoint().txid
1190 }
1191
1192 fn is_splice(&self) -> bool {
1193 self.channel_parameters.splice_parent_funding_txid.is_some()
1194 }
1195
1196 fn channel_type_features(&self) -> &ChannelTypeFeatures {
1197 &self.channel_parameters.channel_type_features
1198 }
1199
1200 fn contributed_inputs(&self) -> impl Iterator<Item = bitcoin::OutPoint> + '_ {
1201 self.contribution.iter().flat_map(|contribution| contribution.contributed_inputs())
1202 }
1203
1204 fn contributed_outputs(&self) -> impl Iterator<Item = &bitcoin::Script> + '_ {
1205 self.contribution.iter().flat_map(|contribution| contribution.contributed_outputs())
1206 }
1207}
1208
1209impl_writeable_tlv_based!(FundingScope, {
1210 (1, channel_parameters, (required: ReadableArgs, None)),
1211 (3, current_counterparty_commitment_txid, required),
1212 (5, prev_counterparty_commitment_txid, option),
1213 (7, current_holder_commitment_tx, required),
1214 (9, prev_holder_commitment_tx, option),
1215 (11, counterparty_claimable_outpoints, required),
1216 (13, contribution, option),
1217});
1218
1219#[derive(Clone, PartialEq)]
1220pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
1221 funding: FundingScope,
1222 pending_funding: Vec<FundingScope>,
1223
1224 is_manual_broadcast: bool,
1227 funding_seen_onchain: bool,
1236
1237 latest_update_id: u64,
1238 commitment_transaction_number_obscure_factor: u64,
1239
1240 destination_script: ScriptBuf,
1241 broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>,
1242 counterparty_payment_script: ScriptBuf,
1243 shutdown_script: Option<ScriptBuf>,
1244
1245 channel_keys_id: [u8; 32],
1246 holder_revocation_basepoint: RevocationBasepoint,
1247 channel_id: ChannelId,
1248 first_negotiated_funding_txo: OutPoint,
1249
1250 counterparty_commitment_params: CounterpartyCommitmentParameters,
1251
1252 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
1254
1255 on_holder_tx_csv: u16,
1256
1257 commitment_secrets: CounterpartyCommitmentSecrets,
1258 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
1264 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
1269
1270 counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
1271
1272 current_counterparty_commitment_number: u64,
1275 current_holder_commitment_number: u64,
1278
1279 payment_preimages: HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)>,
1293
1294 pending_monitor_events: Vec<MonitorEvent>,
1304
1305 pub(super) pending_events: Vec<Event>,
1306 pub(super) is_processing_pending_events: bool,
1307
1308 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
1312
1313 outputs_to_watch: HashMap<Txid, Vec<(u32, ScriptBuf)>>,
1318
1319 #[cfg(any(test, feature = "_test_utils"))]
1320 pub onchain_tx_handler: OnchainTxHandler<Signer>,
1321 #[cfg(not(any(test, feature = "_test_utils")))]
1322 onchain_tx_handler: OnchainTxHandler<Signer>,
1323
1324 lockdown_from_offchain: bool,
1328
1329 holder_tx_signed: bool,
1337
1338 funding_spend_seen: bool,
1342
1343 holder_pays_commitment_tx_fee: Option<bool>,
1346
1347 funding_spend_confirmed: Option<Txid>,
1350
1351 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
1352 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
1356
1357 htlcs_resolved_to_user: HashSet<SentHTLCId>,
1364
1365 spendable_txids_confirmed: Vec<Txid>,
1371
1372 best_block: BlockLocator,
1378
1379 counterparty_node_id: PublicKey,
1381
1382 initial_counterparty_commitment_info: Option<(PublicKey, u32, u64, u64)>,
1389 initial_counterparty_commitment_tx: Option<CommitmentTransaction>,
1394
1395 balances_empty_height: Option<u32>,
1397
1398 pub(crate) failed_back_htlc_ids: HashSet<SentHTLCId>,
1403
1404 current_holder_htlc_data: CommitmentHTLCData,
1410 prev_holder_htlc_data: Option<CommitmentHTLCData>,
1411
1412 alternative_funding_confirmed: Option<(Txid, u32, Option<BlockHash>)>,
1424
1425 funding_tx_confirmed_in: Option<(u32, BlockHash)>,
1430
1431 written_by_0_1_or_later: bool,
1435}
1436
1437macro_rules! get_confirmed_funding_scope {
1440 ($self: expr) => {
1441 $self
1442 .alternative_funding_confirmed
1443 .map(|(alternative_funding_txid, _, _)| {
1444 $self
1445 .pending_funding
1446 .iter()
1447 .find(|funding| funding.funding_txid() == alternative_funding_txid)
1448 .expect("FundingScope for confirmed alternative funding must exist")
1449 })
1450 .unwrap_or(&$self.funding)
1451 };
1452}
1453
1454#[rustfmt::skip]
1459macro_rules! holder_commitment_htlcs {
1460 ($self: expr, CURRENT) => {{
1461 let funding = get_confirmed_funding_scope!($self);
1462 funding.current_holder_commitment_tx.nondust_htlcs().iter()
1463 .chain($self.current_holder_htlc_data.dust_htlcs.iter().map(|(htlc, _)| htlc))
1464 }};
1465 ($self: expr, CURRENT_WITH_SOURCES) => {{
1466 let funding = get_confirmed_funding_scope!($self);
1467 holder_commitment_htlcs!(
1468 &funding.current_holder_commitment_tx, &$self.current_holder_htlc_data
1469 )
1470 }};
1471 ($self: expr, PREV) => {{
1472 let funding = get_confirmed_funding_scope!($self);
1473 funding.prev_holder_commitment_tx.as_ref().map(|tx| {
1474 let dust_htlcs = $self.prev_holder_htlc_data.as_ref().unwrap().dust_htlcs.iter()
1475 .map(|(htlc, _)| htlc);
1476 tx.nondust_htlcs().iter().chain(dust_htlcs)
1477 })
1478 }};
1479 ($self: expr, PREV_WITH_SOURCES) => {{
1480 let funding = get_confirmed_funding_scope!($self);
1481 funding.prev_holder_commitment_tx.as_ref().map(|tx| {
1482 holder_commitment_htlcs!(tx, $self.prev_holder_htlc_data.as_ref().unwrap())
1483 })
1484 }};
1485 ($commitment_tx: expr, $htlc_data: expr) => {{
1486 let mut sources = $htlc_data.nondust_htlc_sources.iter();
1487 let nondust_htlcs = $commitment_tx.nondust_htlcs().iter().map(move |htlc| {
1488 let mut source = None;
1489 if htlc.offered {
1490 debug_assert!(htlc.transaction_output_index.is_some());
1491 source = sources.next();
1492 if source.is_none() {
1493 panic!("Every offered non-dust HTLC should have a corresponding source");
1494 }
1495 }
1496 (htlc, source)
1497 });
1498 let dust_htlcs = $htlc_data.dust_htlcs.iter().map(|(htlc, source)| (htlc, source.as_ref()));
1499 nondust_htlcs.chain(dust_htlcs)
1500 }};
1501}
1502
1503pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
1505
1506#[cfg(any(feature = "_test_utils", test))]
1510impl<Signer: EcdsaChannelSigner> PartialEq for ChannelMonitor<Signer>
1511where
1512 Signer: PartialEq,
1513{
1514 fn eq(&self, other: &Self) -> bool {
1515 use crate::sync::LockTestExt;
1516 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1520 let a = if ord {
1521 self.inner.unsafe_well_ordered_double_lock_self()
1522 } else {
1523 other.inner.unsafe_well_ordered_double_lock_self()
1524 };
1525 let b = if ord {
1526 other.inner.unsafe_well_ordered_double_lock_self()
1527 } else {
1528 self.inner.unsafe_well_ordered_double_lock_self()
1529 };
1530 a.eq(&b)
1531 }
1532}
1533
1534impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
1535 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1536 self.inner.lock().unwrap().write(writer)
1537 }
1538}
1539
1540const SERIALIZATION_VERSION: u8 = 1;
1542const MIN_SERIALIZATION_VERSION: u8 = 1;
1543
1544pub(crate) fn write_chanmon_internal<Signer: EcdsaChannelSigner, W: Writer>(
1552 channel_monitor: &ChannelMonitorImpl<Signer>, _is_stub: bool, writer: &mut W,
1553) -> Result<(), Error> {
1554 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1555
1556 channel_monitor.latest_update_id.write(writer)?;
1557
1558 U48(channel_monitor.commitment_transaction_number_obscure_factor).write(writer)?;
1560
1561 channel_monitor.destination_script.write(writer)?;
1562 if let Some(ref broadcasted_holder_revokable_script) =
1563 channel_monitor.broadcasted_holder_revokable_script
1564 {
1565 writer.write_all(&[0; 1])?;
1566 broadcasted_holder_revokable_script.0.write(writer)?;
1567 broadcasted_holder_revokable_script.1.write(writer)?;
1568 broadcasted_holder_revokable_script.2.write(writer)?;
1569 } else {
1570 writer.write_all(&[1; 1])?;
1571 }
1572
1573 channel_monitor.counterparty_payment_script.write(writer)?;
1574 match &channel_monitor.shutdown_script {
1575 Some(script) => script.write(writer)?,
1576 None => ScriptBuf::new().write(writer)?,
1577 }
1578
1579 channel_monitor.channel_keys_id.write(writer)?;
1580 channel_monitor.holder_revocation_basepoint.write(writer)?;
1581 let funding_outpoint = channel_monitor.get_funding_txo();
1582 writer.write_all(&funding_outpoint.txid[..])?;
1583 writer.write_all(&funding_outpoint.index.to_be_bytes())?;
1584 let redeem_script = channel_monitor.funding.channel_parameters.make_funding_redeemscript();
1585 let script_pubkey = redeem_script.to_p2wsh();
1586 script_pubkey.write(writer)?;
1587 channel_monitor.funding.current_counterparty_commitment_txid.write(writer)?;
1588 channel_monitor.funding.prev_counterparty_commitment_txid.write(writer)?;
1589
1590 channel_monitor.counterparty_commitment_params.write(writer)?;
1591 redeem_script.write(writer)?;
1592 channel_monitor.funding.channel_parameters.channel_value_satoshis.write(writer)?;
1593
1594 match channel_monitor.their_cur_per_commitment_points {
1595 Some((idx, pubkey, second_option)) => {
1596 writer.write_all(&byte_utils::be48_to_array(idx))?;
1597 writer.write_all(&pubkey.serialize())?;
1598 match second_option {
1599 Some(second_pubkey) => {
1600 writer.write_all(&second_pubkey.serialize())?;
1601 },
1602 None => {
1603 writer.write_all(&[0; 33])?;
1604 },
1605 }
1606 },
1607 None => {
1608 writer.write_all(&byte_utils::be48_to_array(0))?;
1609 },
1610 }
1611
1612 writer.write_all(&channel_monitor.on_holder_tx_csv.to_be_bytes())?;
1613
1614 channel_monitor.commitment_secrets.write(writer)?;
1615
1616 #[rustfmt::skip]
1617 macro_rules! serialize_htlc_in_commitment {
1618 ($htlc_output: expr) => {
1619 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1620 writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
1621 writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
1622 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1623 $htlc_output.transaction_output_index.write(writer)?;
1624 }
1625 }
1626
1627 writer.write_all(
1628 &(channel_monitor.funding.counterparty_claimable_outpoints.len() as u64).to_be_bytes(),
1629 )?;
1630 for (ref txid, ref htlc_infos) in
1631 channel_monitor.funding.counterparty_claimable_outpoints.iter()
1632 {
1633 writer.write_all(&txid[..])?;
1634 writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
1635 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1636 debug_assert!(
1637 htlc_source.is_none()
1638 || Some(**txid) == channel_monitor.funding.current_counterparty_commitment_txid
1639 || Some(**txid) == channel_monitor.funding.prev_counterparty_commitment_txid,
1640 "HTLC Sources for all revoked commitment transactions should be none!"
1641 );
1642 serialize_htlc_in_commitment!(htlc_output);
1643 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1644 }
1645 }
1646
1647 writer.write_all(
1648 &(channel_monitor.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes(),
1649 )?;
1650 for (ref txid, commitment_number) in channel_monitor.counterparty_commitment_txn_on_chain.iter()
1651 {
1652 writer.write_all(&txid[..])?;
1653 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1654 }
1655
1656 writer.write_all(
1657 &(channel_monitor.counterparty_hash_commitment_number.len() as u64).to_be_bytes(),
1658 )?;
1659 for (ref payment_hash, commitment_number) in
1660 channel_monitor.counterparty_hash_commitment_number.iter()
1661 {
1662 writer.write_all(&payment_hash.0[..])?;
1663 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1664 }
1665
1666 if let Some(holder_commitment_tx) = &channel_monitor.funding.prev_holder_commitment_tx {
1667 writer.write_all(&[1; 1])?;
1668 write_legacy_holder_commitment_data(
1669 writer,
1670 holder_commitment_tx,
1671 &channel_monitor.prev_holder_htlc_data.as_ref().unwrap(),
1672 )?;
1673 } else {
1674 writer.write_all(&[0; 1])?;
1675 }
1676
1677 write_legacy_holder_commitment_data(
1678 writer,
1679 &channel_monitor.funding.current_holder_commitment_tx,
1680 &channel_monitor.current_holder_htlc_data,
1681 )?;
1682
1683 writer.write_all(&byte_utils::be48_to_array(
1684 channel_monitor.current_counterparty_commitment_number,
1685 ))?;
1686 writer
1687 .write_all(&byte_utils::be48_to_array(channel_monitor.current_holder_commitment_number))?;
1688
1689 writer.write_all(&(channel_monitor.payment_preimages.len() as u64).to_be_bytes())?;
1690 for (payment_preimage, _) in channel_monitor.payment_preimages.values() {
1691 writer.write_all(&payment_preimage.0[..])?;
1692 }
1693
1694 writer.write_all(
1695 &(channel_monitor
1696 .pending_monitor_events
1697 .iter()
1698 .filter(|ev| match ev {
1699 MonitorEvent::HTLCEvent(_) => true,
1700 MonitorEvent::HolderForceClosed(_) => true,
1701 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1702 _ => false,
1703 })
1704 .count() as u64)
1705 .to_be_bytes(),
1706 )?;
1707 for event in channel_monitor.pending_monitor_events.iter() {
1708 match event {
1709 MonitorEvent::HTLCEvent(upd) => {
1710 0u8.write(writer)?;
1711 upd.write(writer)?;
1712 },
1713 MonitorEvent::HolderForceClosed(_) => 1u8.write(writer)?,
1714 MonitorEvent::HolderForceClosedWithInfo { .. } => 1u8.write(writer)?,
1718 _ => {}, }
1720 }
1721
1722 writer.write_all(&(channel_monitor.pending_events.len() as u64).to_be_bytes())?;
1723 for event in channel_monitor.pending_events.iter() {
1724 event.write(writer)?;
1725 }
1726
1727 channel_monitor.best_block.block_hash.write(writer)?;
1728 writer.write_all(&channel_monitor.best_block.height.to_be_bytes())?;
1729
1730 writer.write_all(
1731 &(channel_monitor.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes(),
1732 )?;
1733 for ref entry in channel_monitor.onchain_events_awaiting_threshold_conf.iter() {
1734 entry.write(writer)?;
1735 }
1736
1737 (channel_monitor.outputs_to_watch.len() as u64).write(writer)?;
1738 for (txid, idx_scripts) in channel_monitor.outputs_to_watch.iter() {
1739 txid.write(writer)?;
1740 (idx_scripts.len() as u64).write(writer)?;
1741 for (idx, script) in idx_scripts.iter() {
1742 idx.write(writer)?;
1743 script.write(writer)?;
1744 }
1745 }
1746
1747 channel_monitor.onchain_tx_handler.write(writer)?;
1748
1749 channel_monitor.lockdown_from_offchain.write(writer)?;
1750 channel_monitor.holder_tx_signed.write(writer)?;
1751
1752 let pending_monitor_events =
1754 match channel_monitor.pending_monitor_events.iter().find(|ev| match ev {
1755 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1756 _ => false,
1757 }) {
1758 Some(MonitorEvent::HolderForceClosedWithInfo { outpoint, .. }) => {
1759 let mut pending_monitor_events = channel_monitor.pending_monitor_events.clone();
1760 pending_monitor_events.push(MonitorEvent::HolderForceClosed(*outpoint));
1761 pending_monitor_events
1762 },
1763 _ => channel_monitor.pending_monitor_events.clone(),
1764 };
1765
1766 let legacy_alternative_funding_confirmed = channel_monitor
1767 .alternative_funding_confirmed
1768 .map(|(txid, conf_height, _)| (txid, conf_height));
1769 let alternative_funding_confirmed_block =
1770 channel_monitor.alternative_funding_confirmed.and_then(|(_, _, conf_hash)| conf_hash);
1771
1772 write_tlv_fields!(writer, {
1773 (1, channel_monitor.funding_spend_confirmed, option),
1774 (3, channel_monitor.htlcs_resolved_on_chain, required_vec),
1775 (5, pending_monitor_events, required_vec),
1776 (7, channel_monitor.funding_spend_seen, required),
1777 (9, channel_monitor.counterparty_node_id, required),
1778 (11, channel_monitor.confirmed_commitment_tx_counterparty_output, option),
1779 (13, channel_monitor.spendable_txids_confirmed, required_vec),
1780 (15, channel_monitor.counterparty_fulfilled_htlcs, required),
1781 (17, channel_monitor.initial_counterparty_commitment_info, option),
1782 (19, channel_monitor.channel_id, required),
1783 (21, channel_monitor.balances_empty_height, option),
1784 (23, channel_monitor.holder_pays_commitment_tx_fee, option),
1785 (25, channel_monitor.payment_preimages, required),
1786 (27, channel_monitor.first_negotiated_funding_txo, required),
1787 (29, channel_monitor.initial_counterparty_commitment_tx, option),
1788 (31, channel_monitor.funding.channel_parameters, required),
1789 (32, channel_monitor.pending_funding, optional_vec),
1790 (33, channel_monitor.htlcs_resolved_to_user, required),
1791 (34, legacy_alternative_funding_confirmed, option),
1792 (35, channel_monitor.is_manual_broadcast, required),
1793 (37, channel_monitor.funding_seen_onchain, required),
1794 (39, channel_monitor.best_block.previous_blocks, required),
1795 (41, channel_monitor.funding.contribution, option),
1796 (43, channel_monitor.funding_tx_confirmed_in, option),
1797 (45, alternative_funding_confirmed_block, option),
1798 });
1799
1800 Ok(())
1801}
1802
1803impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
1804 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1805 write_chanmon_internal(self, false, writer)
1806 }
1807}
1808
1809#[rustfmt::skip]
1810macro_rules! _process_events_body {
1811 ($self_opt: expr, $logger: expr, $event_to_handle: expr, $handle_event: expr) => {
1812 loop {
1813 let mut handling_res = Ok(());
1814 let (pending_events, repeated_events);
1815 if let Some(us) = $self_opt {
1816 let mut inner = us.inner.lock().unwrap();
1817 if inner.is_processing_pending_events {
1818 break handling_res;
1819 }
1820 inner.is_processing_pending_events = true;
1821
1822 pending_events = inner.pending_events.clone();
1823 repeated_events = inner.get_repeated_events();
1824 } else { break handling_res; }
1825
1826 let mut num_handled_events = 0;
1827 for event in pending_events {
1828 log_trace!($logger, "Handling event {:?}...", event);
1829 $event_to_handle = event;
1830 let event_handling_result = $handle_event;
1831 log_trace!($logger, "Done handling event, result: {:?}", event_handling_result);
1832 match event_handling_result {
1833 Ok(()) => num_handled_events += 1,
1834 Err(e) => {
1835 handling_res = Err(e);
1838 break;
1839 }
1840 }
1841 }
1842
1843 if handling_res.is_ok() {
1844 for event in repeated_events {
1845 $event_to_handle = event;
1848 let _ = $handle_event;
1849 }
1850 }
1851
1852 if let Some(us) = $self_opt {
1853 let mut inner = us.inner.lock().unwrap();
1854 inner.pending_events.drain(..num_handled_events);
1855 inner.is_processing_pending_events = false;
1856 if handling_res.is_ok() && !inner.pending_events.is_empty() {
1857 continue;
1860 }
1861 }
1862 break handling_res;
1863 }
1864 }
1865}
1866pub(super) use _process_events_body as process_events_body;
1867
1868pub(crate) struct WithChannelMonitor;
1869
1870impl WithChannelMonitor {
1871 pub(crate) fn from<'a, L: Logger, S: EcdsaChannelSigner>(
1872 logger: &'a L, monitor: &ChannelMonitor<S>, payment_hash: Option<PaymentHash>,
1873 ) -> WithContext<'a, L> {
1874 Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash)
1875 }
1876
1877 pub(crate) fn from_impl<'a, L: Logger, S: EcdsaChannelSigner>(
1878 logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>, payment_hash: Option<PaymentHash>,
1879 ) -> WithContext<'a, L> {
1880 let peer_id = Some(monitor_impl.counterparty_node_id);
1881 let channel_id = Some(monitor_impl.channel_id());
1882 WithContext::from(logger, peer_id, channel_id, payment_hash)
1883 }
1884}
1885
1886impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
1887 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1891 ChannelMonitor { inner: Mutex::new(imp) }
1892 }
1893
1894 #[rustfmt::skip]
1895 pub(crate) fn new(
1896 secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1897 on_counterparty_tx_csv: u16, destination_script: &Script,
1898 channel_parameters: &ChannelTransactionParameters, holder_pays_commitment_tx_fee: bool,
1899 commitment_transaction_number_obscure_factor: u64,
1900 initial_holder_commitment_tx: HolderCommitmentTransaction, best_block: BlockLocator,
1901 counterparty_node_id: PublicKey, channel_id: ChannelId,
1902 is_manual_broadcast: bool,
1903 ) -> ChannelMonitor<Signer> {
1904
1905 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1906 let holder_pubkeys = &channel_parameters.holder_pubkeys;
1907 let counterparty_payment_script = chan_utils::get_countersigner_payment_script(
1908 &channel_parameters.channel_type_features, &holder_pubkeys.payment_point
1909 );
1910
1911 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1912 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1913 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1914 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1915
1916 let channel_keys_id = keys.channel_keys_id();
1917 let holder_revocation_basepoint = holder_pubkeys.revocation_basepoint;
1918
1919 let current_holder_commitment_number =
1920 initial_holder_commitment_tx.trust().commitment_number();
1921
1922 let onchain_tx_handler = OnchainTxHandler::new(
1923 channel_id, counterparty_node_id, channel_parameters.channel_value_satoshis,
1924 channel_keys_id, destination_script.into(), keys, channel_parameters.clone(),
1925 initial_holder_commitment_tx.clone(), secp_ctx,
1926 );
1927
1928 let funding_outpoint = channel_parameters.funding_outpoint
1929 .expect("Funding outpoint must be known during initialization");
1930 let funding_redeem_script = channel_parameters.make_funding_redeemscript();
1931 let funding_script = funding_redeem_script.to_p2wsh();
1932 let mut outputs_to_watch = new_hash_map();
1933 outputs_to_watch.insert(
1934 funding_outpoint.txid, vec![(funding_outpoint.index as u32, funding_script.clone())],
1935 );
1936
1937 Self::from_impl(ChannelMonitorImpl {
1938 funding: FundingScope {
1939 channel_parameters: channel_parameters.clone(),
1940
1941 current_counterparty_commitment_txid: None,
1942 prev_counterparty_commitment_txid: None,
1943 counterparty_claimable_outpoints: new_hash_map(),
1944
1945 current_holder_commitment_tx: initial_holder_commitment_tx,
1946 prev_holder_commitment_tx: None,
1947
1948 contribution: None,
1949 },
1950 pending_funding: vec![],
1951
1952 is_manual_broadcast,
1953 funding_seen_onchain: false,
1954
1955 latest_update_id: 0,
1956 commitment_transaction_number_obscure_factor,
1957
1958 destination_script: destination_script.into(),
1959 broadcasted_holder_revokable_script: None,
1960 counterparty_payment_script,
1961 shutdown_script,
1962
1963 channel_keys_id,
1964 holder_revocation_basepoint,
1965 channel_id,
1966 first_negotiated_funding_txo: funding_outpoint,
1967
1968 counterparty_commitment_params,
1969 their_cur_per_commitment_points: None,
1970
1971 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1972
1973 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1974 counterparty_commitment_txn_on_chain: new_hash_map(),
1975 counterparty_hash_commitment_number: new_hash_map(),
1976 counterparty_fulfilled_htlcs: new_hash_map(),
1977
1978 current_counterparty_commitment_number: 1 << 48,
1979 current_holder_commitment_number,
1980
1981 payment_preimages: new_hash_map(),
1982 pending_monitor_events: Vec::new(),
1983 pending_events: Vec::new(),
1984 is_processing_pending_events: false,
1985
1986 onchain_events_awaiting_threshold_conf: Vec::new(),
1987 outputs_to_watch,
1988
1989 onchain_tx_handler,
1990
1991 holder_pays_commitment_tx_fee: Some(holder_pays_commitment_tx_fee),
1992 lockdown_from_offchain: false,
1993 holder_tx_signed: false,
1994 funding_spend_seen: false,
1995 funding_spend_confirmed: None,
1996 confirmed_commitment_tx_counterparty_output: None,
1997 htlcs_resolved_on_chain: Vec::new(),
1998 htlcs_resolved_to_user: new_hash_set(),
1999 spendable_txids_confirmed: Vec::new(),
2000
2001 best_block,
2002 counterparty_node_id: counterparty_node_id,
2003 initial_counterparty_commitment_info: None,
2004 initial_counterparty_commitment_tx: None,
2005 balances_empty_height: None,
2006
2007 failed_back_htlc_ids: new_hash_set(),
2008
2009 current_holder_htlc_data: CommitmentHTLCData::new(),
2011 prev_holder_htlc_data: None,
2012
2013 funding_tx_confirmed_in: None,
2014 alternative_funding_confirmed: None,
2015
2016 written_by_0_1_or_later: true,
2017 })
2018 }
2019
2020 pub fn persistence_key(&self) -> MonitorName {
2030 let inner = self.inner.lock().unwrap();
2031 let funding_outpoint = inner.first_negotiated_funding_txo;
2032 let channel_id = inner.channel_id;
2033 if ChannelId::v1_from_funding_outpoint(funding_outpoint) == channel_id {
2034 MonitorName::V1Channel(funding_outpoint)
2035 } else {
2036 MonitorName::V2Channel(channel_id)
2037 }
2038 }
2039
2040 #[cfg(test)]
2041 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2042 self.inner.lock().unwrap().provide_secret(idx, secret)
2043 }
2044
2045 pub(crate) fn provide_initial_counterparty_commitment_tx(
2053 &self, commitment_tx: CommitmentTransaction,
2054 ) {
2055 let mut inner = self.inner.lock().unwrap();
2056 inner.provide_initial_counterparty_commitment_tx(commitment_tx);
2057 }
2058
2059 #[cfg(test)]
2064 fn provide_latest_counterparty_commitment_tx(
2065 &self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2066 commitment_number: u64, their_per_commitment_point: PublicKey,
2067 ) {
2068 let mut inner = self.inner.lock().unwrap();
2069 inner.provide_latest_counterparty_commitment_tx(
2070 txid,
2071 htlc_outputs,
2072 commitment_number,
2073 their_per_commitment_point,
2074 )
2075 }
2076
2077 #[cfg(test)]
2078 #[rustfmt::skip]
2079 fn provide_latest_holder_commitment_tx(
2080 &self, holder_commitment_tx: HolderCommitmentTransaction,
2081 htlc_outputs: &[(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)],
2082 ) {
2083 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
2084 holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new(),
2085 ).unwrap()
2086 }
2087
2088 #[rustfmt::skip]
2099 pub(crate) fn provide_payment_preimage_unsafe_legacy<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2100 &self,
2101 payment_hash: &PaymentHash,
2102 payment_preimage: &PaymentPreimage,
2103 broadcaster: &B,
2104 fee_estimator: &LowerBoundedFeeEstimator<F>,
2105 logger: &L,
2106 ) {
2107 let mut inner = self.inner.lock().unwrap();
2108 let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash));
2109 inner.provide_payment_preimage(
2113 payment_hash, payment_preimage, &None, broadcaster, fee_estimator, &logger)
2114 }
2115
2116 pub fn update_monitor<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2121 &self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L,
2122 ) -> Result<(), ()> {
2123 let mut inner = self.inner.lock().unwrap();
2124 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2125 inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
2126 }
2127
2128 pub fn get_latest_update_id(&self) -> u64 {
2133 self.inner.lock().unwrap().get_latest_update_id()
2134 }
2135
2136 pub fn get_funding_txo(&self) -> OutPoint {
2138 self.inner.lock().unwrap().get_funding_txo()
2139 }
2140
2141 pub(crate) fn written_by_0_1_or_later(&self) -> bool {
2142 self.inner.lock().unwrap().written_by_0_1_or_later
2143 }
2144
2145 pub fn get_funding_script(&self) -> ScriptBuf {
2147 self.inner.lock().unwrap().get_funding_script()
2148 }
2149
2150 pub fn channel_id(&self) -> ChannelId {
2152 self.inner.lock().unwrap().channel_id()
2153 }
2154
2155 pub fn channel_type_features(&self) -> ChannelTypeFeatures {
2157 self.inner.lock().unwrap().channel_type_features().clone()
2158 }
2159
2160 #[rustfmt::skip]
2163 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
2164 self.inner.lock().unwrap().get_outputs_to_watch()
2165 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
2166 }
2167
2168 #[rustfmt::skip]
2172 pub fn load_outputs_to_watch<F: chain::Filter, L: Logger>(&self, filter: &F, logger: &L) {
2173 let lock = self.inner.lock().unwrap();
2174 let logger = WithChannelMonitor::from_impl(logger, &*lock, None);
2175 for funding in core::iter::once(&lock.funding).chain(&lock.pending_funding) {
2176 let funding_outpoint = funding.funding_outpoint();
2177 log_trace!(&logger, "Registering funding outpoint {} with the filter to monitor confirmations", &funding_outpoint);
2178 let script_pubkey = funding.channel_parameters.make_funding_redeemscript().to_p2wsh();
2179 filter.register_tx(&funding_outpoint.txid, &script_pubkey);
2180 }
2181 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
2182 for (index, script_pubkey) in outputs.iter() {
2183 assert!(*index <= u16::MAX as u32);
2184 let outpoint = OutPoint { txid: *txid, index: *index as u16 };
2185 log_trace!(logger, "Registering outpoint {} with the filter to monitor spend", outpoint);
2186 filter.register_output(WatchedOutput {
2187 block_hash: None,
2188 outpoint,
2189 script_pubkey: script_pubkey.clone(),
2190 });
2191 }
2192 }
2193 }
2194
2195 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
2198 self.inner.lock().unwrap().get_and_clear_pending_monitor_events_filtered(|_| true)
2199 }
2200
2201 pub(super) fn get_and_clear_pending_non_htlc_fail_events(&self) -> Vec<MonitorEvent> {
2204 self.inner.lock().unwrap().get_and_clear_pending_monitor_events_filtered(
2205 |ev| !matches!(ev, MonitorEvent::HTLCEvent(upd) if upd.payment_preimage.is_none()),
2206 )
2207 }
2208
2209 pub fn process_pending_events<H: Deref, L: Logger>(
2225 &self, handler: &H, logger: &L,
2226 ) -> Result<(), ReplayEvent>
2227 where
2228 H::Target: EventHandler,
2229 {
2230 let mut ev;
2231 process_events_body!(Some(self), logger, ev, handler.handle_event(ev))
2232 }
2233
2234 pub async fn process_pending_events_async<
2238 Future: core::future::Future<Output = Result<(), ReplayEvent>>,
2239 H: Fn(Event) -> Future,
2240 L: Logger,
2241 >(
2242 &self, handler: &H, logger: &L,
2243 ) -> Result<(), ReplayEvent> {
2244 let mut ev;
2245 process_events_body!(Some(self), logger, ev, { handler(ev).await })
2246 }
2247
2248 #[cfg(test)]
2249 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
2250 let mut ret = Vec::new();
2251 let mut lck = self.inner.lock().unwrap();
2252 mem::swap(&mut ret, &mut lck.pending_events);
2253 ret.append(&mut lck.get_repeated_events());
2254 ret
2255 }
2256
2257 pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
2270 self.inner.lock().unwrap().initial_counterparty_commitment_tx()
2271 }
2272
2273 pub fn counterparty_commitment_txs_from_update(
2294 &self, update: &ChannelMonitorUpdate,
2295 ) -> Vec<CommitmentTransaction> {
2296 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
2297 }
2298
2299 #[rustfmt::skip]
2321 pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
2322 self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
2323 }
2324
2325 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2326 self.inner.lock().unwrap().get_min_seen_secret()
2327 }
2328
2329 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2330 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
2331 }
2332
2333 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2334 self.inner.lock().unwrap().get_cur_holder_commitment_number()
2335 }
2336
2337 pub(crate) fn no_further_updates_allowed(&self) -> bool {
2344 self.inner.lock().unwrap().no_further_updates_allowed()
2345 }
2346
2347 pub fn get_counterparty_node_id(&self) -> PublicKey {
2349 self.inner.lock().unwrap().counterparty_node_id
2350 }
2351
2352 pub fn broadcast_latest_holder_commitment_txn<
2372 B: BroadcasterInterface,
2373 F: FeeEstimator,
2374 L: Logger,
2375 >(
2376 &self, broadcaster: &B, fee_estimator: &F, logger: &L,
2377 ) {
2378 let mut inner = self.inner.lock().unwrap();
2379 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2380 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2381
2382 inner.queue_latest_holder_commitment_txn_for_broadcast(
2383 broadcaster,
2384 &fee_estimator,
2385 &logger,
2386 false,
2387 );
2388 }
2389
2390 #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
2394 pub fn unsafe_get_latest_holder_commitment_txn<L: Logger>(
2395 &self, logger: &L,
2396 ) -> Vec<Transaction> {
2397 let mut inner = self.inner.lock().unwrap();
2398 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2399 inner.unsafe_get_latest_holder_commitment_txn(&logger)
2400 }
2401
2402 #[rustfmt::skip]
2414 pub fn block_connected<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2415 &self,
2416 header: &Header,
2417 txdata: &TransactionData,
2418 height: u32,
2419 broadcaster: B,
2420 fee_estimator: F,
2421 logger: &L,
2422 ) -> Vec<TransactionOutputs> {
2423 let mut inner = self.inner.lock().unwrap();
2424 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2425 inner.block_connected(
2426 header, txdata, height, broadcaster, fee_estimator, &logger)
2427 }
2428
2429 pub fn blocks_disconnected<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2432 &self, fork_point: BlockLocator, broadcaster: B, fee_estimator: F, logger: &L,
2433 ) {
2434 let mut inner = self.inner.lock().unwrap();
2435 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2436 inner.blocks_disconnected(fork_point, broadcaster, fee_estimator, &logger)
2437 }
2438
2439 #[rustfmt::skip]
2447 pub fn transactions_confirmed<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2448 &self,
2449 header: &Header,
2450 txdata: &TransactionData,
2451 height: u32,
2452 broadcaster: B,
2453 fee_estimator: F,
2454 logger: &L,
2455 ) -> Vec<TransactionOutputs> {
2456 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2457 let mut inner = self.inner.lock().unwrap();
2458 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2459 inner.transactions_confirmed(
2460 header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
2461 }
2462
2463 #[rustfmt::skip]
2470 pub fn transaction_unconfirmed<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2471 &self,
2472 txid: &Txid,
2473 broadcaster: B,
2474 fee_estimator: F,
2475 logger: &L,
2476 ) {
2477 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2478 let mut inner = self.inner.lock().unwrap();
2479 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2480 inner.transaction_unconfirmed(
2481 txid, broadcaster, &bounded_fee_estimator, &logger
2482 );
2483 }
2484
2485 #[rustfmt::skip]
2493 pub fn best_block_updated<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2494 &self,
2495 header: &Header,
2496 height: u32,
2497 broadcaster: B,
2498 fee_estimator: F,
2499 logger: &L,
2500 ) -> Vec<TransactionOutputs> {
2501 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2502 let mut inner = self.inner.lock().unwrap();
2503 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2504 inner.best_block_updated(
2505 header, height, broadcaster, &bounded_fee_estimator, &logger
2506 )
2507 }
2508
2509 #[rustfmt::skip]
2521 pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
2522 let inner = self.inner.lock().unwrap();
2523 let funding_confirmed = inner.funding_tx_confirmed_in.map(|(conf_height, conf_hash)| {
2524 (inner.funding.funding_txid(), conf_height, Some(conf_hash))
2525 });
2526 let alternative_funding_confirmed = inner.alternative_funding_confirmed
2527 .and_then(|(alternative_funding_txid, conf_height, conf_hash)| {
2528 conf_hash.map(|conf_hash| (alternative_funding_txid, conf_height, Some(conf_hash)))
2529 });
2530 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
2531 .iter()
2532 .map(|entry| (entry.txid, entry.height, entry.block_hash))
2533 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
2534 .chain(funding_confirmed)
2535 .chain(alternative_funding_confirmed)
2536 .collect();
2537 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
2538 txids.dedup_by_key(|(txid, _, _)| *txid);
2539 txids
2540 }
2541
2542 pub fn current_best_block(&self) -> BlockLocator {
2545 self.inner.lock().unwrap().best_block.clone()
2546 }
2547
2548 #[rustfmt::skip]
2554 pub fn rebroadcast_pending_claims<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2555 &self, broadcaster: B, fee_estimator: F, logger: &L,
2556 ) {
2557 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2558 let mut lock = self.inner.lock().unwrap();
2559 let inner = &mut *lock;
2560 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2561 let current_height = inner.best_block.height;
2562 let conf_target = inner.closure_conf_target();
2563 inner.onchain_tx_handler.rebroadcast_pending_claims(
2564 current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, conf_target,
2565 &inner.destination_script, &fee_estimator, &logger,
2566 );
2567 }
2568
2569 pub fn has_pending_claims(&self) -> bool {
2571 self.inner.lock().unwrap().onchain_tx_handler.has_pending_claims()
2572 }
2573
2574 #[rustfmt::skip]
2577 pub fn signer_unblocked<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
2578 &self, broadcaster: B, fee_estimator: F, logger: &L,
2579 ) {
2580 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2581 let mut lock = self.inner.lock().unwrap();
2582 let inner = &mut *lock;
2583 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2584 let current_height = inner.best_block.height;
2585 let conf_target = inner.closure_conf_target();
2586 inner.onchain_tx_handler.rebroadcast_pending_claims(
2587 current_height, FeerateStrategy::RetryPrevious, &broadcaster, conf_target,
2588 &inner.destination_script, &fee_estimator, &logger,
2589 );
2590 }
2591
2592 #[rustfmt::skip]
2611 pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
2612 let inner = self.inner.lock().unwrap();
2613 let current_height = inner.best_block.height;
2614 let funding = get_confirmed_funding_scope!(inner);
2615 let mut spendable_outputs = inner.get_spendable_outputs(&funding, tx);
2616 spendable_outputs.retain(|descriptor| {
2617 let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
2618 if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
2619 conf_threshold = cmp::min(conf_threshold,
2620 current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
2621 }
2622 conf_threshold >= confirmation_height
2623 });
2624 spendable_outputs
2625 }
2626
2627 #[rustfmt::skip]
2642 pub fn check_and_update_full_resolution_status<L: Logger>(&self, logger: &L) -> (bool, bool) {
2643 let mut is_all_funds_claimed = self.get_claimable_balances().is_empty();
2644 let current_height = self.current_best_block().height;
2645 let mut inner = self.inner.lock().unwrap();
2646
2647 if inner.is_closed_without_updates()
2648 && is_all_funds_claimed
2649 && !inner.funding_spend_seen
2650 {
2651 return (inner.pending_monitor_events.is_empty(), false);
2657 }
2658
2659 if is_all_funds_claimed && !inner.funding_spend_seen {
2660 debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2661 is_all_funds_claimed = false;
2662 }
2663
2664 let preimages_not_needed_elsewhere = inner.pending_monitor_events.is_empty();
2668
2669 match (inner.balances_empty_height, is_all_funds_claimed, preimages_not_needed_elsewhere) {
2670 (Some(balances_empty_height), true, true) => {
2671 (current_height >= balances_empty_height + ARCHIVAL_DELAY_BLOCKS, false)
2673 },
2674 (Some(_), false, _)|(Some(_), _, false) => {
2675 debug_assert!(false,
2680 "Thought we were done claiming funds, but claimable_balances now has entries");
2681 log_error!(logger,
2682 "WARNING: LDK thought it was done claiming all the available funds in the ChannelMonitor for channel {}, but later decided it had more to claim. This is potentially an important bug in LDK, please report it at https://github.com/lightningdevkit/rust-lightning/issues/new",
2683 inner.get_funding_txo());
2684 inner.balances_empty_height = None;
2685 (false, true)
2686 },
2687 (None, true, true) => {
2688 log_debug!(logger,
2691 "ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
2692 inner.get_funding_txo(), ARCHIVAL_DELAY_BLOCKS);
2693 inner.balances_empty_height = Some(current_height);
2694 (false, true)
2695 },
2696 (None, false, _)|(None, _, false) => {
2697 (false, false)
2699 },
2700 }
2701 }
2702
2703 #[cfg(test)]
2704 pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
2705 self.inner.lock().unwrap().counterparty_payment_script.clone()
2706 }
2707
2708 #[cfg(test)]
2709 pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
2710 self.inner.lock().unwrap().counterparty_payment_script = script;
2711 }
2712
2713 #[cfg(any(test, feature = "_test_utils"))]
2714 pub fn do_mut_signer_call<F: FnMut(&mut Signer) -> ()>(&self, mut f: F) {
2715 let mut inner = self.inner.lock().unwrap();
2716 f(&mut inner.onchain_tx_handler.signer);
2717 }
2718}
2719
2720impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2721 #[rustfmt::skip]
2724 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, source: Option<&HTLCSource>,
2725 holder_commitment: bool, counterparty_revoked_commitment: bool,
2726 confirmed_txid: Option<Txid>
2727 ) -> Option<Balance> {
2728 let htlc_commitment_tx_output_idx = htlc.transaction_output_index?;
2729
2730 let mut htlc_spend_txid_opt = None;
2731 let mut htlc_spend_tx_opt = None;
2732 let mut holder_timeout_spend_pending = None;
2733 let mut htlc_spend_pending = None;
2734 let mut holder_delayed_output_pending = None;
2735 for event in self.onchain_events_awaiting_threshold_conf.iter() {
2736 match event.event {
2737 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
2738 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
2739 debug_assert!(htlc_spend_txid_opt.is_none());
2740 htlc_spend_txid_opt = Some(&event.txid);
2741 debug_assert!(htlc_spend_tx_opt.is_none());
2742 htlc_spend_tx_opt = event.transaction.as_ref();
2743 debug_assert!(holder_timeout_spend_pending.is_none());
2744 debug_assert_eq!(htlc_value_satoshis, htlc.amount_msat / 1000);
2745 holder_timeout_spend_pending = Some(event.confirmation_threshold());
2746 },
2747 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
2748 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
2749 debug_assert!(htlc_spend_txid_opt.is_none());
2750 htlc_spend_txid_opt = Some(&event.txid);
2751 debug_assert!(htlc_spend_tx_opt.is_none());
2752 htlc_spend_tx_opt = event.transaction.as_ref();
2753 debug_assert!(htlc_spend_pending.is_none());
2754 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
2755 },
2756 OnchainEvent::MaturingOutput {
2757 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
2758 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
2759 .any(|(input_idx, inp)|
2760 Some(inp.previous_output.txid) == confirmed_txid &&
2761 inp.previous_output.vout == htlc_commitment_tx_output_idx &&
2762 descriptor.outpoint.index as usize == input_idx
2768 ))
2769 .unwrap_or(false)
2770 => {
2771 debug_assert!(holder_delayed_output_pending.is_none());
2772 holder_delayed_output_pending = Some(event.confirmation_threshold());
2773 },
2774 _ => {},
2775 }
2776 }
2777 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
2778 .any(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
2779 debug_assert!(htlc_spend_txid_opt.is_none());
2780 htlc_spend_txid_opt = v.resolving_txid.as_ref();
2781 debug_assert!(htlc_spend_tx_opt.is_none());
2782 htlc_spend_tx_opt = v.resolving_tx.as_ref();
2783 true
2784 } else { false });
2785 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved as u8 <= 1);
2786
2787 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
2788 let htlc_output_to_spend =
2789 if let Some(txid) = htlc_spend_txid_opt {
2790 if let Some(ref tx) = htlc_spend_tx_opt {
2795 let htlc_input_idx_opt = tx.input.iter().enumerate()
2796 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2797 .map(|(idx, _)| idx as u32);
2798 debug_assert!(htlc_input_idx_opt.is_some());
2799 BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2800 } else {
2801 let funding = get_confirmed_funding_scope!(self);
2802 debug_assert!(!funding.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2803 debug_assert!(!funding.channel_type_features().supports_anchor_zero_fee_commitments());
2804 BitcoinOutPoint::new(*txid, 0)
2805 }
2806 } else {
2807 htlc_commitment_outpoint
2808 };
2809 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2810
2811 if let Some(conf_thresh) = holder_delayed_output_pending {
2812 debug_assert!(holder_commitment);
2813 return Some(Balance::ClaimableAwaitingConfirmations {
2814 amount_satoshis: htlc.amount_msat / 1000,
2815 confirmation_height: conf_thresh,
2816 source: BalanceSource::Htlc,
2817 });
2818 } else if htlc_resolved && !htlc_output_spend_pending {
2819 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2825 } else if counterparty_revoked_commitment {
2826 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2827 if let OnchainEvent::MaturingOutput {
2828 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2829 } = &event.event {
2830 event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2831 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2832 tx.compute_txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2833 } else {
2834 Some(inp.previous_output.txid) == confirmed_txid &&
2835 inp.previous_output.vout == htlc_commitment_tx_output_idx
2836 }
2837 })).unwrap_or(false)
2838 } else {
2839 false
2840 }
2841 });
2842 if htlc_output_claim_pending {
2843 } else {
2848 debug_assert!(holder_timeout_spend_pending.is_none(),
2849 "HTLCUpdate OnchainEvents should never appear for preimage claims");
2850 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2851 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2852 return Some(Balance::CounterpartyRevokedOutputClaimable {
2853 amount_satoshis: htlc.amount_msat / 1000,
2854 });
2855 }
2856 } else if htlc.offered == holder_commitment {
2857 if let Some(conf_thresh) = holder_timeout_spend_pending {
2861 return Some(Balance::ClaimableAwaitingConfirmations {
2862 amount_satoshis: htlc.amount_msat / 1000,
2863 confirmation_height: conf_thresh,
2864 source: BalanceSource::Htlc,
2865 });
2866 } else {
2867 let outbound_payment = match source {
2868 None => panic!("Outbound HTLCs should have a source"),
2869 Some(&HTLCSource::PreviousHopData(_)) => false,
2870 Some(&HTLCSource::TrampolineForward { .. }) => false,
2871 Some(&HTLCSource::OutboundRoute { .. }) => true,
2872 };
2873 return Some(Balance::MaybeTimeoutClaimableHTLC {
2874 amount_satoshis: htlc.amount_msat / 1000,
2875 claimable_height: htlc.cltv_expiry,
2876 payment_hash: htlc.payment_hash,
2877 outbound_payment,
2878 });
2879 }
2880 } else if let Some((payment_preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
2881 debug_assert!(holder_timeout_spend_pending.is_none());
2887 if let Some((conf_thresh, true)) = htlc_spend_pending {
2888 return Some(Balance::ClaimableAwaitingConfirmations {
2889 amount_satoshis: htlc.amount_msat / 1000,
2890 confirmation_height: conf_thresh,
2891 source: BalanceSource::Htlc,
2892 });
2893 } else {
2894 return Some(Balance::ContentiousClaimable {
2895 amount_satoshis: htlc.amount_msat / 1000,
2896 timeout_height: htlc.cltv_expiry,
2897 payment_hash: htlc.payment_hash,
2898 payment_preimage: *payment_preimage,
2899 });
2900 }
2901 } else if !htlc_resolved {
2902 return Some(Balance::MaybePreimageClaimableHTLC {
2903 amount_satoshis: htlc.amount_msat / 1000,
2904 expiry_height: htlc.cltv_expiry,
2905 payment_hash: htlc.payment_hash,
2906 });
2907 }
2908 None
2909 }
2910}
2911
2912impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
2913 #[rustfmt::skip]
2928 pub fn get_claimable_balances(&self) -> Vec<Balance> {
2929 let mut res = Vec::new();
2930 let us = self.inner.lock().unwrap();
2931
2932 let mut confirmed_txid = us.funding_spend_confirmed;
2933 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
2934 let mut pending_commitment_tx_conf_thresh = None;
2935 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2936 if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
2937 event.event
2938 {
2939 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2940 Some((event.txid, event.confirmation_threshold()))
2941 } else { None }
2942 });
2943 if let Some((txid, conf_thresh)) = funding_spend_pending {
2944 debug_assert!(us.funding_spend_confirmed.is_none(),
2945 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2946 confirmed_txid = Some(txid);
2947 pending_commitment_tx_conf_thresh = Some(conf_thresh);
2948 }
2949
2950 macro_rules! walk_htlcs {
2951 ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2952 for (htlc, source) in $htlc_iter {
2953 if htlc.transaction_output_index.is_some() {
2954
2955 if let Some(bal) = us.get_htlc_balance(
2956 htlc, source, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid
2957 ) {
2958 res.push(bal);
2959 }
2960 }
2961 }
2962 }
2963 }
2964
2965 if let Some(txid) = confirmed_txid {
2966 let funding_spent = get_confirmed_funding_scope!(us);
2967 let mut found_commitment_tx = false;
2968 if let Some(counterparty_tx_htlcs) = funding_spent.counterparty_claimable_outpoints.get(&txid) {
2969 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2971 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2972 if let OnchainEvent::MaturingOutput {
2973 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2974 } = &event.event {
2975 Some(descriptor.output.value)
2976 } else { None }
2977 }) {
2978 res.push(Balance::ClaimableAwaitingConfirmations {
2979 amount_satoshis: value.to_sat(),
2980 confirmation_height: conf_thresh,
2981 source: BalanceSource::CounterpartyForceClosed,
2982 });
2983 } else {
2984 }
2988 }
2989 if Some(txid) == funding_spent.current_counterparty_commitment_txid || Some(txid) == funding_spent.prev_counterparty_commitment_txid {
2990 walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2991 } else {
2992 walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2993 let mut spent_counterparty_output = false;
2998 for event in us.onchain_events_awaiting_threshold_conf.iter() {
2999 if let OnchainEvent::MaturingOutput {
3000 descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
3001 } = &event.event {
3002 res.push(Balance::ClaimableAwaitingConfirmations {
3003 amount_satoshis: output.value.to_sat(),
3004 confirmation_height: event.confirmation_threshold(),
3005 source: BalanceSource::CounterpartyForceClosed,
3006 });
3007 if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
3008 if event.transaction.as_ref().map(|tx|
3009 tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
3010 ).unwrap_or(false) {
3011 spent_counterparty_output = true;
3012 }
3013 }
3014 }
3015 }
3016
3017 if spent_counterparty_output {
3018 } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
3019 let output_spendable = us.onchain_tx_handler
3020 .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
3021 if output_spendable {
3022 res.push(Balance::CounterpartyRevokedOutputClaimable {
3023 amount_satoshis: amt.to_sat(),
3024 });
3025 }
3026 } else {
3027 }
3030 }
3031 found_commitment_tx = true;
3032 } else if txid == funding_spent.current_holder_commitment_tx.trust().txid() {
3033 walk_htlcs!(true, false, holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES));
3034 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
3035 res.push(Balance::ClaimableAwaitingConfirmations {
3036 amount_satoshis: funding_spent.current_holder_commitment_tx.to_broadcaster_value_sat(),
3037 confirmation_height: conf_thresh,
3038 source: BalanceSource::HolderForceClosed,
3039 });
3040 }
3041 found_commitment_tx = true;
3042 } else if let Some(prev_holder_commitment_tx) = &funding_spent.prev_holder_commitment_tx {
3043 if txid == prev_holder_commitment_tx.trust().txid() {
3044 walk_htlcs!(true, false, holder_commitment_htlcs!(us, PREV_WITH_SOURCES).unwrap());
3045 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
3046 res.push(Balance::ClaimableAwaitingConfirmations {
3047 amount_satoshis: prev_holder_commitment_tx.to_broadcaster_value_sat(),
3048 confirmation_height: conf_thresh,
3049 source: BalanceSource::HolderForceClosed,
3050 });
3051 }
3052 found_commitment_tx = true;
3053 }
3054 }
3055 if !found_commitment_tx {
3056 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
3057 res.push(Balance::ClaimableAwaitingConfirmations {
3061 amount_satoshis: funding_spent.current_holder_commitment_tx.to_broadcaster_value_sat(),
3062 confirmation_height: conf_thresh,
3063 source: BalanceSource::CoopClose,
3064 });
3065 }
3066 }
3067 } else {
3068 let mut claimable_inbound_htlc_value_sat = 0;
3069 let mut outbound_payment_htlc_rounded_msat = 0;
3070 let mut outbound_forwarded_htlc_rounded_msat = 0;
3071 let mut inbound_claiming_htlc_rounded_msat = 0;
3072 let mut inbound_htlc_rounded_msat = 0;
3073 for (htlc, source) in holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES) {
3076 let rounded_value_msat = if htlc.transaction_output_index.is_none() {
3077 htlc.amount_msat
3078 } else { htlc.amount_msat % 1000 };
3079 if htlc.offered {
3080 let outbound_payment = match source {
3081 None => panic!("Outbound HTLCs should have a source"),
3082 Some(HTLCSource::PreviousHopData(_)) => false,
3083 Some(HTLCSource::TrampolineForward { .. }) => false,
3084 Some(HTLCSource::OutboundRoute { .. }) => true,
3085 };
3086 if outbound_payment {
3087 outbound_payment_htlc_rounded_msat += rounded_value_msat;
3088 } else {
3089 outbound_forwarded_htlc_rounded_msat += rounded_value_msat;
3090 }
3091 if htlc.transaction_output_index.is_some() {
3092 res.push(Balance::MaybeTimeoutClaimableHTLC {
3093 amount_satoshis: htlc.amount_msat / 1000,
3094 claimable_height: htlc.cltv_expiry,
3095 payment_hash: htlc.payment_hash,
3096 outbound_payment,
3097 });
3098 }
3099 } else if us.payment_preimages.contains_key(&htlc.payment_hash) {
3100 inbound_claiming_htlc_rounded_msat += rounded_value_msat;
3101 if htlc.transaction_output_index.is_some() {
3102 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
3103 }
3104 } else {
3105 inbound_htlc_rounded_msat += rounded_value_msat;
3106 if htlc.transaction_output_index.is_some() {
3107 res.push(Balance::MaybePreimageClaimableHTLC {
3110 amount_satoshis: htlc.amount_msat / 1000,
3111 expiry_height: htlc.cltv_expiry,
3112 payment_hash: htlc.payment_hash,
3113 });
3114 }
3115 }
3116 }
3117 let balance_candidates = core::iter::once(&us.funding)
3118 .chain(us.pending_funding.iter())
3119 .map(|funding| {
3120 let to_self_value_sat = funding.current_holder_commitment_tx.to_broadcaster_value_sat();
3121 let transaction_fee_satoshis = if us.holder_pays_commitment_tx_fee.unwrap_or(true) {
3124 let transaction = &funding.current_holder_commitment_tx.trust().built_transaction().transaction;
3125 let output_value_sat: u64 = transaction.output.iter().map(|txout| txout.value.to_sat()).sum();
3126 funding.channel_parameters.channel_value_satoshis - output_value_sat
3127 } else {
3128 0
3129 };
3130 HolderCommitmentTransactionBalance {
3131 amount_satoshis: to_self_value_sat + claimable_inbound_htlc_value_sat,
3132 transaction_fee_satoshis,
3133 }
3134 })
3135 .collect::<Vec<_>>();
3136 let confirmed_balance_candidate_index = core::iter::once(&us.funding)
3137 .chain(us.pending_funding.iter())
3138 .enumerate()
3139 .find(|(_, funding)| {
3140 us.alternative_funding_confirmed
3141 .map(|(funding_txid_confirmed, _, _)| funding.funding_txid() == funding_txid_confirmed)
3142 .unwrap_or(true)
3145 })
3146 .map(|(idx, _)| idx)
3147 .expect("We must have one FundingScope that is confirmed");
3148
3149 if !us.is_closed_without_updates()
3156 || balance_candidates.iter().any(|bal| bal.amount_satoshis != 0)
3157 {
3158 res.push(Balance::ClaimableOnChannelClose {
3159 balance_candidates,
3160 confirmed_balance_candidate_index,
3161 outbound_payment_htlc_rounded_msat,
3162 outbound_forwarded_htlc_rounded_msat,
3163 inbound_claiming_htlc_rounded_msat,
3164 inbound_htlc_rounded_msat,
3165 });
3166 }
3167 }
3168
3169 res
3170 }
3171
3172 pub(crate) fn get_all_current_outbound_htlcs(
3176 &self,
3177 ) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
3178 let mut res = new_hash_map();
3179 let us = self.inner.lock().unwrap();
3182 let mut walk_counterparty_commitment = |txid| {
3183 if let Some(latest_outpoints) = us.funding.counterparty_claimable_outpoints.get(txid) {
3184 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
3185 if let &Some(ref source) = source_option {
3186 let htlc_id = SentHTLCId::from_source(source);
3187 if !us.htlcs_resolved_to_user.contains(&htlc_id) {
3188 let preimage_opt =
3189 us.counterparty_fulfilled_htlcs.get(&htlc_id).cloned();
3190 res.insert((**source).clone(), (htlc.clone(), preimage_opt));
3191 }
3192 }
3193 }
3194 }
3195 };
3196 if let Some(ref txid) = us.funding.current_counterparty_commitment_txid {
3197 walk_counterparty_commitment(txid);
3198 }
3199 if let Some(ref txid) = us.funding.prev_counterparty_commitment_txid {
3200 walk_counterparty_commitment(txid);
3201 }
3202 res
3203 }
3204
3205 pub(crate) fn get_onchain_failed_outbound_htlcs(&self) -> HashMap<HTLCSource, PaymentHash> {
3209 let mut res = new_hash_map();
3210 let us = self.inner.lock().unwrap();
3211
3212 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
3216 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
3217 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
3218 if event.height + ANTI_REORG_DELAY - 1 <= us.best_block.height {
3219 Some(event.txid)
3220 } else {
3221 None
3222 }
3223 } else {
3224 None
3225 }
3226 })
3227 });
3228
3229 let confirmed_txid = if let Some(txid) = confirmed_txid {
3230 txid
3231 } else {
3232 return res;
3233 };
3234
3235 macro_rules! walk_htlcs {
3236 ($htlc_iter: expr) => {
3237 let mut walk_candidate_htlcs = |htlcs| {
3238 for &(ref candidate_htlc, ref candidate_source) in htlcs {
3239 let candidate_htlc: &HTLCOutputInCommitment = &candidate_htlc;
3240 let candidate_source: &Option<Box<HTLCSource>> = &candidate_source;
3241
3242 let source: &HTLCSource = if let Some(source) = candidate_source {
3243 source
3244 } else {
3245 continue;
3246 };
3247 let htlc_id = SentHTLCId::from_source(source);
3248 if us.htlcs_resolved_to_user.contains(&htlc_id) {
3249 continue;
3250 }
3251
3252 let confirmed = $htlc_iter.find(|(_, conf_src)| Some(source) == *conf_src);
3253 if let Some((confirmed_htlc, _)) = confirmed {
3254 let filter = |v: &&IrrevocablyResolvedHTLC| {
3255 v.commitment_tx_output_idx
3256 == confirmed_htlc.transaction_output_index
3257 };
3258
3259 if confirmed_htlc.transaction_output_index.is_none() {
3262 res.insert(source.clone(), confirmed_htlc.payment_hash);
3265 } else if let Some(state) =
3266 us.htlcs_resolved_on_chain.iter().filter(filter).next()
3267 {
3268 if state.payment_preimage.is_none() {
3269 res.insert(source.clone(), confirmed_htlc.payment_hash);
3270 }
3271 }
3272 } else {
3273 res.insert(source.clone(), candidate_htlc.payment_hash);
3277 }
3278 }
3279 };
3280
3281 if let Some(ref txid) = us.funding.current_counterparty_commitment_txid {
3284 let htlcs = us.funding.counterparty_claimable_outpoints.get(txid);
3285 walk_candidate_htlcs(htlcs.expect("Missing tx info for latest tx"));
3286 }
3287 if let Some(ref txid) = us.funding.prev_counterparty_commitment_txid {
3288 let htlcs = us.funding.counterparty_claimable_outpoints.get(txid);
3289 walk_candidate_htlcs(htlcs.expect("Missing tx info for previous tx"));
3290 }
3291 };
3292 }
3293
3294 let funding = get_confirmed_funding_scope!(us);
3295
3296 if Some(confirmed_txid) == funding.current_counterparty_commitment_txid
3297 || Some(confirmed_txid) == funding.prev_counterparty_commitment_txid
3298 {
3299 let htlcs = funding.counterparty_claimable_outpoints.get(&confirmed_txid).unwrap();
3300 walk_htlcs!(htlcs.iter().filter_map(|(a, b)| {
3301 if let &Some(ref source) = b {
3302 Some((a, Some(&**source)))
3303 } else {
3304 None
3305 }
3306 }));
3307 } else if confirmed_txid == funding.current_holder_commitment_tx.trust().txid() {
3308 walk_htlcs!(holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES));
3309 } else if let Some(prev_commitment_tx) = &funding.prev_holder_commitment_tx {
3310 if confirmed_txid == prev_commitment_tx.trust().txid() {
3311 walk_htlcs!(holder_commitment_htlcs!(us, PREV_WITH_SOURCES).unwrap());
3312 } else {
3313 let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
3314 walk_htlcs!(htlcs_confirmed.iter());
3315 }
3316 } else {
3317 let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
3318 walk_htlcs!(htlcs_confirmed.iter());
3319 }
3320
3321 res
3322 }
3323
3324 pub(crate) fn get_stored_preimages(
3325 &self,
3326 ) -> HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)> {
3327 self.inner.lock().unwrap().payment_preimages.clone()
3328 }
3329}
3330
3331macro_rules! fail_unbroadcast_htlcs {
3347 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
3348 $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
3349 debug_assert_eq!($commitment_tx_confirmed.compute_txid(), $commitment_txid_confirmed);
3350
3351 macro_rules! check_htlc_fails {
3352 ($txid: expr, $commitment_tx: expr, $per_commitment_outpoints: expr) => {
3353 if let Some(ref latest_outpoints) = $per_commitment_outpoints {
3354 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
3355 if let &Some(ref source) = source_option {
3356 let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
3366
3367 let mut matched_htlc = false;
3368 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
3369 if broadcast_htlc.transaction_output_index.is_some() &&
3370 (Some(&**source) == *broadcast_source ||
3371 (broadcast_source.is_none() &&
3372 broadcast_htlc.payment_hash == htlc.payment_hash &&
3373 broadcast_htlc.amount_msat == htlc.amount_msat)) {
3374 matched_htlc = true;
3375 break;
3376 }
3377 }
3378 if matched_htlc { continue; }
3379 if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
3380 continue;
3381 }
3382 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3383 if entry.height != $commitment_tx_conf_height { return true; }
3384 match entry.event {
3385 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
3386 *update_source != **source
3387 },
3388 _ => true,
3389 }
3390 });
3391 let entry = OnchainEventEntry {
3392 txid: $commitment_txid_confirmed,
3393 transaction: Some($commitment_tx_confirmed.clone()),
3394 height: $commitment_tx_conf_height,
3395 block_hash: Some(*$commitment_tx_conf_hash),
3396 event: OnchainEvent::HTLCUpdate {
3397 source: (**source).clone(),
3398 payment_hash: htlc.payment_hash.clone(),
3399 htlc_value_satoshis: htlc.amount_msat / 1000,
3400 commitment_tx_output_idx: None,
3401 },
3402 };
3403 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
3404 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
3405 $commitment_txid_confirmed, entry.confirmation_threshold());
3406 $self.onchain_events_awaiting_threshold_conf.push(entry);
3407 }
3408 }
3409 }
3410 }
3411 }
3412 if let Some(ref txid) = $self.funding.current_counterparty_commitment_txid {
3413 check_htlc_fails!(txid, "current", $self.funding.counterparty_claimable_outpoints.get(txid));
3414 }
3415 if let Some(ref txid) = $self.funding.prev_counterparty_commitment_txid {
3416 check_htlc_fails!(txid, "previous", $self.funding.counterparty_claimable_outpoints.get(txid));
3417 }
3418 } }
3419}
3420
3421#[cfg(any(test, feature = "_test_utils"))]
3426pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
3427 use bitcoin::opcodes;
3428 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
3429 ret[131] = opcodes::all::OP_DROP.to_u8();
3430 ret[132] = opcodes::all::OP_DROP.to_u8();
3431 ret[133] = opcodes::all::OP_DROP.to_u8();
3432 ret[134] = opcodes::all::OP_DROP.to_u8();
3433 ret[135] = opcodes::OP_TRUE.to_u8();
3434 Vec::from(&ret[..])
3435}
3436
3437#[cfg(any(test, feature = "_test_utils"))]
3438#[rustfmt::skip]
3439pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
3440 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
3441}
3442
3443impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
3444 #[rustfmt::skip]
3447 fn closure_conf_target(&self) -> ConfirmationTarget {
3448 if holder_commitment_htlcs!(self, CURRENT).next().is_some() {
3452 return ConfirmationTarget::UrgentOnChainSweep;
3453 }
3454 if holder_commitment_htlcs!(self, PREV).map(|mut htlcs| htlcs.next().is_some()).unwrap_or(false) {
3455 return ConfirmationTarget::UrgentOnChainSweep;
3456 }
3457 if let Some(txid) = self.funding.current_counterparty_commitment_txid {
3458 if !self.funding.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
3459 return ConfirmationTarget::UrgentOnChainSweep;
3460 }
3461 }
3462 if let Some(txid) = self.funding.prev_counterparty_commitment_txid {
3463 if !self.funding.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
3464 return ConfirmationTarget::UrgentOnChainSweep;
3465 }
3466 }
3467 ConfirmationTarget::OutputSpendingFee
3468 }
3469
3470 #[rustfmt::skip]
3474 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
3475 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
3476 return Err("Previous secret did not match new one");
3477 }
3478
3479 let mut removed_fulfilled_htlcs = false;
3482 let prune_htlc_sources = |funding: &mut FundingScope| {
3483 if let Some(txid) = funding.prev_counterparty_commitment_txid.take() {
3484 if funding.current_counterparty_commitment_txid.unwrap() != txid {
3485 let cur_claimables = funding.counterparty_claimable_outpoints.get(
3486 &funding.current_counterparty_commitment_txid.unwrap()).unwrap();
3487 if !removed_fulfilled_htlcs {
3490 for (_, ref source_opt) in funding.counterparty_claimable_outpoints.get(&txid).unwrap() {
3491 if let Some(source) = source_opt {
3492 if !cur_claimables.iter()
3493 .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
3494 {
3495 self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
3496 }
3497 }
3498 }
3499 removed_fulfilled_htlcs = true;
3500 }
3501 for &mut (_, ref mut source_opt) in funding.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
3502 *source_opt = None;
3503 }
3504 } else {
3505 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
3506 }
3507 }
3508 };
3509 core::iter::once(&mut self.funding).chain(&mut self.pending_funding).for_each(prune_htlc_sources);
3510
3511 if !self.payment_preimages.is_empty() {
3512 let min_idx = self.get_min_seen_secret();
3513 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
3514
3515 self.payment_preimages.retain(|&k, _| {
3516 for htlc in holder_commitment_htlcs!(self, CURRENT) {
3517 if k == htlc.payment_hash {
3518 return true
3519 }
3520 }
3521 if let Some(htlcs) = holder_commitment_htlcs!(self, PREV) {
3522 for htlc in htlcs {
3523 if k == htlc.payment_hash {
3524 return true
3525 }
3526 }
3527 }
3528 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
3529 if *cn < min_idx {
3530 return true
3531 }
3532 true
3533 } else { false };
3534 if contains {
3535 counterparty_hash_commitment_number.remove(&k);
3536 }
3537 false
3538 });
3539 }
3540
3541 Ok(())
3542 }
3543
3544 #[rustfmt::skip]
3545 fn provide_initial_counterparty_commitment_tx(
3546 &mut self, commitment_tx: CommitmentTransaction,
3547 ) {
3548 self.initial_counterparty_commitment_info = Some((commitment_tx.per_commitment_point(),
3550 commitment_tx.negotiated_feerate_per_kw(), commitment_tx.to_broadcaster_value_sat(), commitment_tx.to_countersignatory_value_sat()));
3551
3552 #[cfg(debug_assertions)] {
3553 let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
3554 debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), commitment_tx.trust().txid());
3555 }
3556
3557 self.provide_latest_counterparty_commitment_tx(commitment_tx.trust().txid(), Vec::new(), commitment_tx.commitment_number(),
3558 commitment_tx.per_commitment_point());
3559 self.initial_counterparty_commitment_tx = Some(commitment_tx);
3561 }
3562
3563 #[rustfmt::skip]
3564 fn provide_latest_counterparty_commitment_tx(
3565 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
3566 commitment_number: u64, their_per_commitment_point: PublicKey,
3567 ) {
3568 for &(ref htlc, _) in &htlc_outputs {
3573 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
3574 }
3575
3576 self.funding.prev_counterparty_commitment_txid = self.funding.current_counterparty_commitment_txid.take();
3577 self.funding.current_counterparty_commitment_txid = Some(txid);
3578 self.funding.counterparty_claimable_outpoints.insert(txid, htlc_outputs);
3579 self.current_counterparty_commitment_number = commitment_number;
3580
3581 match self.their_cur_per_commitment_points {
3583 Some(old_points) => {
3584 if old_points.0 == commitment_number + 1 {
3585 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
3586 } else if old_points.0 == commitment_number + 2 {
3587 if let Some(old_second_point) = old_points.2 {
3588 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
3589 } else {
3590 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3591 }
3592 } else {
3593 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3594 }
3595 },
3596 None => {
3597 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3598 }
3599 }
3600 }
3601
3602 fn update_counterparty_commitment_data(
3603 &mut self, commitment_txs: &[CommitmentTransaction], htlc_data: &CommitmentHTLCData,
3604 ) -> Result<(), &'static str> {
3605 self.verify_matching_commitment_transactions(commitment_txs.iter())?;
3606
3607 let htlcs_for_commitment = |commitment: &CommitmentTransaction| {
3608 debug_assert!(htlc_data.nondust_htlc_sources.len() <= commitment.nondust_htlcs().len());
3609 let mut nondust_htlcs = commitment.nondust_htlcs().iter();
3610 let mut sources = htlc_data.nondust_htlc_sources.iter();
3611 let nondust_htlcs = core::iter::from_fn(move || {
3612 let htlc = nondust_htlcs.next()?.clone();
3613 let source = (!htlc.offered).then(|| {
3614 let source = sources
3615 .next()
3616 .expect("Every inbound non-dust HTLC should have a corresponding source")
3617 .clone();
3618 Box::new(source)
3619 });
3620 Some((htlc, source))
3621 });
3622
3623 let dust_htlcs = htlc_data.dust_htlcs.iter().map(|(htlc, source)| {
3624 (htlc.clone(), source.as_ref().map(|source| Box::new(source.clone())))
3625 });
3626
3627 nondust_htlcs.chain(dust_htlcs).collect::<Vec<_>>()
3628 };
3629
3630 let current_funding_commitment_tx = commitment_txs.first().unwrap();
3631 self.provide_latest_counterparty_commitment_tx(
3632 current_funding_commitment_tx.trust().txid(),
3633 htlcs_for_commitment(current_funding_commitment_tx),
3634 current_funding_commitment_tx.commitment_number(),
3635 current_funding_commitment_tx.per_commitment_point(),
3636 );
3637
3638 for (pending_funding, commitment_tx) in
3639 self.pending_funding.iter_mut().zip(commitment_txs.iter().skip(1))
3640 {
3641 let commitment_txid = commitment_tx.trust().txid();
3642 pending_funding.prev_counterparty_commitment_txid =
3643 pending_funding.current_counterparty_commitment_txid.take();
3644 pending_funding.current_counterparty_commitment_txid = Some(commitment_txid);
3645 pending_funding
3646 .counterparty_claimable_outpoints
3647 .insert(commitment_txid, htlcs_for_commitment(commitment_tx));
3648 }
3649
3650 Ok(())
3651 }
3652
3653 #[rustfmt::skip]
3659 fn provide_latest_holder_commitment_tx(
3660 &mut self, holder_commitment_tx: HolderCommitmentTransaction,
3661 htlc_outputs: &[(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)],
3662 claimed_htlcs: &[(SentHTLCId, PaymentPreimage)], mut nondust_htlc_sources: Vec<HTLCSource>,
3663 ) -> Result<(), &'static str> {
3664 let dust_htlcs = if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
3665 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().nondust_htlcs().len());
3669 for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().nondust_htlcs().iter()) {
3670 debug_assert_eq!(a, b);
3671 }
3672 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
3673 for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
3674 debug_assert_eq!(a, b);
3675 }
3676
3677 debug_assert!(nondust_htlc_sources.is_empty());
3679 nondust_htlc_sources.reserve_exact(holder_commitment_tx.nondust_htlcs().len());
3680 htlc_outputs.iter().filter_map(|(htlc, _, source)| {
3681 if htlc.transaction_output_index.is_none() {
3684 return Some((htlc.clone(), source.clone()));
3685 }
3686 if htlc.offered {
3687 nondust_htlc_sources.push(source.clone().expect("Outbound HTLCs should have a source"));
3688 }
3689 None
3690 }).collect()
3691 } else {
3692 {
3696 let mut prev = -1;
3697 for htlc in holder_commitment_tx.trust().nondust_htlcs().iter() {
3698 assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
3699 prev = htlc.transaction_output_index.unwrap() as i32;
3700 }
3701 }
3702
3703 debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
3704 debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
3705 debug_assert_eq!(holder_commitment_tx.trust().nondust_htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
3706
3707 let mut sources = nondust_htlc_sources.iter();
3708 for htlc in holder_commitment_tx.trust().nondust_htlcs().iter() {
3709 if htlc.offered {
3710 let source = sources.next().expect("Non-dust HTLC sources didn't match commitment tx");
3711 assert!(source.possibly_matches_output(htlc));
3712 }
3713 }
3714 assert!(sources.next().is_none(), "All HTLC sources should have been exhausted");
3715
3716 htlc_outputs.iter().map(|(htlc, _, source)| (htlc.clone(), source.clone())).collect()
3718 };
3719
3720 let htlc_data = CommitmentHTLCData { nondust_htlc_sources, dust_htlcs };
3721 self.update_holder_commitment_data(vec![holder_commitment_tx], htlc_data, claimed_htlcs)
3722 }
3723
3724 fn verify_matching_commitment_transactions<
3725 'a,
3726 I: ExactSizeIterator<Item = &'a CommitmentTransaction>,
3727 >(
3728 &self, commitment_txs: I,
3729 ) -> Result<(), &'static str> {
3730 if self.pending_funding.len() + 1 != commitment_txs.len() {
3731 return Err("Commitment transaction count mismatch");
3732 }
3733
3734 let mut other_commitment_tx = None::<&CommitmentTransaction>;
3735 for (funding, commitment_tx) in
3736 core::iter::once(&self.funding).chain(self.pending_funding.iter()).zip(commitment_txs)
3737 {
3738 let trusted_tx = &commitment_tx.trust().built_transaction().transaction;
3739 if trusted_tx.input.len() != 1 {
3740 return Err("Commitment transactions must only spend one input");
3741 }
3742 let funding_outpoint_spent = trusted_tx.input[0].previous_output;
3743 if funding_outpoint_spent != funding.funding_outpoint().into_bitcoin_outpoint() {
3744 return Err("Commitment transaction spends invalid funding outpoint");
3745 }
3746
3747 if let Some(other_commitment_tx) = other_commitment_tx {
3748 if commitment_tx.commitment_number() != other_commitment_tx.commitment_number() {
3749 return Err("Commitment number mismatch");
3750 }
3751 if commitment_tx.per_commitment_point()
3752 != other_commitment_tx.per_commitment_point()
3753 {
3754 return Err("Per-commitment-point mismatch");
3755 }
3756 if commitment_tx.negotiated_feerate_per_kw()
3757 != other_commitment_tx.negotiated_feerate_per_kw()
3758 {
3759 return Err("Commitment fee rate mismatch");
3760 }
3761 let nondust_htlcs = commitment_tx.nondust_htlcs();
3762 let other_nondust_htlcs = other_commitment_tx.nondust_htlcs();
3763 if nondust_htlcs.len() != other_nondust_htlcs.len() {
3764 return Err("Non-dust HTLC count mismatch");
3765 }
3766 for (nondust_htlc, other_nondust_htlc) in
3767 nondust_htlcs.iter().zip(other_nondust_htlcs.iter())
3768 {
3769 if !nondust_htlc.is_data_equal(other_nondust_htlc) {
3770 return Err("Non-dust HTLC mismatch");
3771 }
3772 }
3773 }
3774
3775 other_commitment_tx = Some(commitment_tx);
3776 }
3777
3778 Ok(())
3779 }
3780
3781 fn update_holder_commitment_data(
3782 &mut self, commitment_txs: Vec<HolderCommitmentTransaction>,
3783 mut htlc_data: CommitmentHTLCData, claimed_htlcs: &[(SentHTLCId, PaymentPreimage)],
3784 ) -> Result<(), &'static str> {
3785 self.verify_matching_commitment_transactions(
3786 commitment_txs.iter().map(|holder_commitment_tx| holder_commitment_tx.deref()),
3787 )?;
3788
3789 let current_funding_commitment_tx = commitment_txs.first().unwrap();
3790 self.current_holder_commitment_number = current_funding_commitment_tx.commitment_number();
3791 self.onchain_tx_handler.provide_latest_holder_tx(current_funding_commitment_tx.clone());
3792 for (funding, mut commitment_tx) in core::iter::once(&mut self.funding)
3793 .chain(self.pending_funding.iter_mut())
3794 .zip(commitment_txs.into_iter())
3795 {
3796 mem::swap(&mut commitment_tx, &mut funding.current_holder_commitment_tx);
3797 funding.prev_holder_commitment_tx = Some(commitment_tx);
3798 }
3799
3800 mem::swap(&mut htlc_data, &mut self.current_holder_htlc_data);
3801 self.prev_holder_htlc_data = Some(htlc_data);
3802
3803 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
3804 #[cfg(debug_assertions)]
3805 {
3806 let cur_counterparty_htlcs = self
3807 .funding
3808 .counterparty_claimable_outpoints
3809 .get(&self.funding.current_counterparty_commitment_txid.unwrap())
3810 .unwrap();
3811 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
3812 if let Some(source) = source_opt {
3813 SentHTLCId::from_source(source) == *claimed_htlc_id
3814 } else {
3815 false
3816 }
3817 }));
3818 }
3819 self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
3820 }
3821
3822 Ok(())
3823 }
3824
3825 #[rustfmt::skip]
3830 fn provide_payment_preimage<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
3831 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage,
3832 payment_info: &Option<PaymentClaimDetails>, broadcaster: &B,
3833 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithContext<L>
3834 ) {
3835 self.payment_preimages.entry(payment_hash.clone())
3836 .and_modify(|(_, payment_infos)| {
3837 if let Some(payment_info) = payment_info {
3838 if !payment_infos.contains(&payment_info) {
3839 payment_infos.push(payment_info.clone());
3840 }
3841 }
3842 })
3843 .or_insert_with(|| {
3844 (payment_preimage.clone(), payment_info.clone().into_iter().collect())
3845 });
3846
3847 let confirmed_spend_info = self.funding_spend_confirmed
3848 .map(|txid| (txid, None))
3849 .or_else(|| {
3850 self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3851 OnchainEvent::FundingSpendConfirmation { .. } => Some((event.txid, Some(event.height))),
3852 _ => None,
3853 })
3854 });
3855 let (confirmed_spend_txid, confirmed_spend_height) =
3856 if let Some((txid, height)) = confirmed_spend_info {
3857 (txid, height)
3858 } else {
3859 return;
3860 };
3861 let funding_spent = get_confirmed_funding_scope!(self);
3862
3863 macro_rules! claim_htlcs {
3866 ($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3867 let htlc_claim_reqs = self.get_counterparty_output_claims_for_preimage(*payment_preimage, funding_spent, $commitment_number, $txid, $htlcs, confirmed_spend_height);
3868 let conf_target = self.closure_conf_target();
3869 self.onchain_tx_handler.update_claims_view_from_requests(
3870 htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster,
3871 conf_target, &self.destination_script, fee_estimator, logger,
3872 );
3873 }
3874 }
3875 if let Some(txid) = funding_spent.current_counterparty_commitment_txid {
3876 if txid == confirmed_spend_txid {
3877 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3878 claim_htlcs!(*commitment_number, txid, funding_spent.counterparty_claimable_outpoints.get(&txid));
3879 } else {
3880 debug_assert!(false);
3881 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3882 }
3883 return;
3884 }
3885 }
3886 if let Some(txid) = funding_spent.prev_counterparty_commitment_txid {
3887 if txid == confirmed_spend_txid {
3888 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3889 claim_htlcs!(*commitment_number, txid, funding_spent.counterparty_claimable_outpoints.get(&txid));
3890 } else {
3891 debug_assert!(false);
3892 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3893 }
3894 return;
3895 }
3896 }
3897
3898 if self.broadcasted_holder_revokable_script.is_some() {
3904 let holder_commitment_tx = if funding_spent.current_holder_commitment_tx.trust().txid() == confirmed_spend_txid {
3905 Some(&funding_spent.current_holder_commitment_tx)
3906 } else if let Some(prev_holder_commitment_tx) = &funding_spent.prev_holder_commitment_tx {
3907 if prev_holder_commitment_tx.trust().txid() == confirmed_spend_txid {
3908 Some(prev_holder_commitment_tx)
3909 } else {
3910 None
3911 }
3912 } else {
3913 None
3914 };
3915 if let Some(holder_commitment_tx) = holder_commitment_tx {
3916 let (claim_reqs, _) = self.get_broadcasted_holder_claims(
3920 funding_spent, holder_commitment_tx, self.best_block.height,
3921 );
3922 let conf_target = self.closure_conf_target();
3923 self.onchain_tx_handler.update_claims_view_from_requests(
3924 claim_reqs, self.best_block.height, self.best_block.height, broadcaster,
3925 conf_target, &self.destination_script, fee_estimator, logger,
3926 );
3927 }
3928 }
3929 }
3930
3931 #[rustfmt::skip]
3932 fn generate_claimable_outpoints_and_watch_outputs(
3933 &mut self, generate_monitor_event_with_reason: Option<ClosureReason>,
3934 require_funding_seen: bool,
3935 ) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3936 let funding = get_confirmed_funding_scope!(self);
3937 let holder_commitment_tx = &funding.current_holder_commitment_tx;
3938 let funding_outp = HolderFundingOutput::build(
3939 holder_commitment_tx.clone(),
3940 funding.channel_parameters.clone(),
3941 );
3942 let funding_outpoint = funding.funding_outpoint();
3943 let commitment_package = PackageTemplate::build_package(
3944 funding_outpoint.txid.clone(), funding_outpoint.index as u32,
3945 PackageSolvingData::HolderFundingOutput(funding_outp),
3946 self.best_block.height,
3947 );
3948 let mut claimable_outpoints = vec![commitment_package];
3949 if let Some(reason) = generate_monitor_event_with_reason {
3950 let event = MonitorEvent::HolderForceClosedWithInfo {
3951 reason,
3952 outpoint: funding_outpoint,
3953 channel_id: self.channel_id,
3954 };
3955 self.pending_monitor_events.push(event);
3956 }
3957
3958 self.holder_tx_signed = true;
3962
3963 if require_funding_seen && self.is_manual_broadcast && !self.funding_seen_onchain {
3966 return (Vec::new(), Vec::new());
3967 }
3968
3969 let mut watch_outputs = Vec::new();
3970 let zero_fee_htlcs =
3978 self.channel_type_features().supports_anchors_zero_fee_htlc_tx();
3979 let zero_fee_commitments =
3980 self.channel_type_features().supports_anchor_zero_fee_commitments();
3981 if !zero_fee_htlcs && !zero_fee_commitments {
3982 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3986 funding, holder_commitment_tx, self.best_block.height,
3987 );
3988 let new_outputs = self.get_broadcasted_holder_watch_outputs(holder_commitment_tx);
3989 if !new_outputs.is_empty() {
3990 watch_outputs.push((holder_commitment_tx.trust().txid(), new_outputs));
3991 }
3992 claimable_outpoints.append(&mut new_outpoints);
3993 }
3994 (claimable_outpoints, watch_outputs)
3995 }
3996
3997 #[rustfmt::skip]
3998 pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
4007 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithContext<L>,
4008 require_funding_seen: bool,
4009 ) {
4010 let reason = ClosureReason::HolderForceClosed {
4011 broadcasted_latest_txn: Some(true),
4012 message: "ChannelMonitor-initiated commitment transaction broadcast".to_owned(),
4013 };
4014 let (claimable_outpoints, _) =
4015 self.generate_claimable_outpoints_and_watch_outputs(Some(reason), require_funding_seen);
4016 if require_funding_seen && self.is_manual_broadcast && !self.funding_seen_onchain {
4019 log_info!(logger, "Not broadcasting holder commitment for manual-broadcast channel before funding appears on-chain");
4020 return;
4021 }
4022 let conf_target = self.closure_conf_target();
4023 self.onchain_tx_handler.update_claims_view_from_requests(
4024 claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
4025 conf_target, &self.destination_script, fee_estimator, logger,
4026 );
4027 }
4028
4029 fn renegotiated_funding<L: Logger>(
4030 &mut self, logger: &WithContext<L>, channel_parameters: &ChannelTransactionParameters,
4031 alternative_holder_commitment_tx: &HolderCommitmentTransaction,
4032 alternative_counterparty_commitment_tx: &CommitmentTransaction,
4033 funding_contribution: &Option<FundingContribution>,
4034 ) -> Result<(), ()> {
4035 let alternative_counterparty_commitment_txid =
4036 alternative_counterparty_commitment_tx.trust().txid();
4037
4038 let current_counterparty_commitment_htlcs =
4046 if let Some(txid) = &self.funding.current_counterparty_commitment_txid {
4047 self.funding.counterparty_claimable_outpoints.get(txid).unwrap()
4048 } else {
4049 debug_assert!(false);
4050 log_error!(
4051 logger,
4052 "Received funding renegotiation while initial funding negotiation is still pending"
4053 );
4054 return Err(());
4055 };
4056 let mut htlcs_with_sources = current_counterparty_commitment_htlcs.clone();
4057 let alternative_htlcs = alternative_counterparty_commitment_tx.nondust_htlcs();
4058
4059 let expected_non_dust_htlc_count = htlcs_with_sources
4060 .iter()
4061 .position(|(htlc, _)| htlc.transaction_output_index.is_none())
4064 .unwrap_or(htlcs_with_sources.len());
4065 if alternative_htlcs.len() != expected_non_dust_htlc_count {
4066 log_error!(
4067 logger,
4068 "Received alternative counterparty commitment with HTLC count mismatch"
4069 );
4070 return Err(());
4071 }
4072
4073 for (alternative_htlc, (htlc, _)) in
4074 alternative_htlcs.iter().zip(htlcs_with_sources.iter_mut())
4075 {
4076 debug_assert!(htlc.transaction_output_index.is_some());
4077 debug_assert!(alternative_htlc.transaction_output_index.is_some());
4078 if !alternative_htlc.is_data_equal(htlc) {
4079 log_error!(
4080 logger,
4081 "Received alternative counterparty commitment with non-dust HTLC mismatch"
4082 );
4083 return Err(());
4084 }
4085 htlc.transaction_output_index = alternative_htlc.transaction_output_index;
4086 }
4087
4088 let mut counterparty_claimable_outpoints = new_hash_map();
4089 counterparty_claimable_outpoints
4090 .insert(alternative_counterparty_commitment_txid, htlcs_with_sources);
4091
4092 let alternative_funding = FundingScope {
4094 channel_parameters: channel_parameters.clone(),
4095 current_counterparty_commitment_txid: Some(alternative_counterparty_commitment_txid),
4096 prev_counterparty_commitment_txid: None,
4097 counterparty_claimable_outpoints,
4098 current_holder_commitment_tx: alternative_holder_commitment_tx.clone(),
4099 prev_holder_commitment_tx: None,
4100 contribution: funding_contribution.clone(),
4101 };
4102 let alternative_funding_outpoint = alternative_funding.funding_outpoint();
4103
4104 if self
4105 .pending_funding
4106 .iter()
4107 .any(|funding| funding.funding_txid() == alternative_funding_outpoint.txid)
4108 {
4109 log_error!(
4110 logger,
4111 "Renegotiated funding transaction with a duplicate funding txid {}",
4112 alternative_funding_outpoint.txid
4113 );
4114 return Err(());
4115 }
4116
4117 if let Some(parent_funding_txid) = channel_parameters.splice_parent_funding_txid.as_ref() {
4118 let has_different_parent = self.pending_funding.iter().any(|funding| {
4124 funding.channel_parameters.splice_parent_funding_txid.as_ref()
4125 != Some(parent_funding_txid)
4126 });
4127 if has_different_parent {
4128 log_error!(
4129 logger,
4130 "Negotiated splice while channel is pending channel_ready/splice_locked"
4131 );
4132 return Err(());
4133 }
4134 if *parent_funding_txid != self.funding.funding_txid() {
4135 log_error!(
4136 logger,
4137 "Negotiated splice that does not spend currently locked funding transaction"
4138 );
4139 return Err(());
4140 }
4141 } else if self.funding.is_splice() {
4142 return Err(());
4145 }
4146
4147 let script_pubkey = channel_parameters.make_funding_redeemscript().to_p2wsh();
4148 self.outputs_to_watch.insert(
4149 alternative_funding_outpoint.txid,
4150 vec![(alternative_funding_outpoint.index as u32, script_pubkey)],
4151 );
4152 self.pending_funding.push(alternative_funding);
4153
4154 Ok(())
4155 }
4156
4157 fn queue_discard_funding_event(
4158 &mut self, discarded_funding: impl Iterator<Item = FundingScope>,
4159 ) {
4160 for funding in discarded_funding {
4161 if let Some(contribution) = funding.contribution {
4162 if let Some((inputs, outputs)) = contribution.into_unique_contributions(
4163 self.funding.contributed_inputs(),
4164 self.funding.contributed_outputs(),
4165 ) {
4166 let outputs = outputs.into_iter().map(|output| output.script_pubkey).collect();
4167 self.pending_events.push(Event::DiscardFunding {
4168 channel_id: self.channel_id,
4169 funding_info: FundingInfo::Contribution { inputs, outputs },
4170 });
4171 }
4172 } else {
4173 self.pending_events.push(Event::DiscardFunding {
4174 channel_id: self.channel_id,
4175 funding_info: FundingInfo::OutPoint { outpoint: funding.funding_outpoint() },
4176 });
4177 }
4178 }
4179 }
4180
4181 fn promote_funding(&mut self, new_funding_txid: Txid) -> Result<(), ()> {
4182 let prev_funding_txid = self.funding.funding_txid();
4183
4184 let new_funding = self
4185 .pending_funding
4186 .iter_mut()
4187 .find(|funding| funding.funding_txid() == new_funding_txid);
4188 if new_funding.is_none() {
4189 return Err(());
4190 }
4191 let mut new_funding = new_funding.unwrap();
4192
4193 mem::swap(&mut self.funding, &mut new_funding);
4194 self.onchain_tx_handler.update_after_renegotiated_funding_locked(
4195 self.funding.channel_parameters.clone(),
4196 self.funding.current_holder_commitment_tx.clone(),
4197 self.funding.prev_holder_commitment_tx.clone(),
4198 );
4199
4200 if self.funding.prev_holder_commitment_tx.is_none() {
4205 self.prev_holder_htlc_data.take();
4206 }
4207
4208 let no_further_updates_allowed = self.no_further_updates_allowed();
4209
4210 for funding in &self.pending_funding {
4212 self.outputs_to_watch.remove(&funding.funding_txid());
4213 }
4214 let mut discarded_funding = Vec::new();
4215 mem::swap(&mut self.pending_funding, &mut discarded_funding);
4216 self.funding_tx_confirmed_in = None;
4217 let discarded_funding = discarded_funding
4218 .into_iter()
4219 .filter(|funding| {
4222 no_further_updates_allowed && funding.funding_txid() != prev_funding_txid
4223 });
4224 self.queue_discard_funding_event(discarded_funding);
4225
4226 if let Some((alternative_funding_txid, conf_height, conf_hash)) =
4227 self.alternative_funding_confirmed.take()
4228 {
4229 debug_assert_eq!(alternative_funding_txid, new_funding_txid);
4233 if alternative_funding_txid == new_funding_txid {
4234 self.funding_tx_confirmed_in = conf_hash.map(|conf_hash| (conf_height, conf_hash));
4235 }
4236 }
4237
4238 Ok(())
4239 }
4240
4241 #[rustfmt::skip]
4242 fn update_monitor<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
4243 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithContext<L>
4244 ) -> Result<(), ()> {
4245 if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4246 log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
4247 log_funding_info!(self), updates.updates.len());
4248 } else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4249 log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
4250 log_funding_info!(self), updates.updates.len());
4251 } else {
4252 log_info!(logger, "Applying update, bringing update_id from {} to {} with {} change(s).",
4253 self.latest_update_id, updates.update_id, updates.updates.len());
4254 }
4255
4256 if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
4265 assert_eq!(updates.updates.len(), 1);
4266 match updates.updates[0] {
4267 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
4268 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
4269 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
4272 debug_assert!(self.lockdown_from_offchain),
4273 _ => {
4274 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
4275 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
4276 },
4277 }
4278 }
4279 if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4280 if self.latest_update_id + 1 != updates.update_id {
4281 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
4282 }
4283 }
4284 let mut ret = Ok(());
4285 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4286 for update in updates.updates.iter() {
4287 match update {
4288 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
4289 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
4290 if self.lockdown_from_offchain { panic!(); }
4291 if let Err(e) = self.provide_latest_holder_commitment_tx(
4292 commitment_tx.clone(), htlc_outputs, &claimed_htlcs,
4293 nondust_htlc_sources.clone()
4294 ) {
4295 log_error!(logger, "Failed updating latest holder commitment transaction info: {}", e);
4296 ret = Err(());
4297 }
4298 }
4299 ChannelMonitorUpdateStep::LatestHolderCommitment {
4300 commitment_txs, htlc_data, claimed_htlcs,
4301 } => {
4302 log_trace!(logger, "Updating ChannelMonitor with {} latest holder commitment(s)", commitment_txs.len());
4303 assert!(!self.lockdown_from_offchain);
4304 if let Err(e) = self.update_holder_commitment_data(
4305 commitment_txs.clone(), htlc_data.clone(), claimed_htlcs,
4306 ) {
4307 log_error!(logger, "Failed updating latest holder commitment state: {}", e);
4308 ret = Err(());
4309 }
4310 },
4311 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
4315 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
4316 if self.pending_funding.is_empty() {
4317 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point)
4318 } else {
4319 log_error!(logger, "Received unexpected non-splice counterparty commitment monitor update");
4320 ret = Err(());
4321 }
4322 },
4323 ChannelMonitorUpdateStep::LatestCounterpartyCommitment {
4324 commitment_txs, htlc_data,
4325 } => {
4326 log_trace!(logger, "Updating ChannelMonitor with {} latest counterparty commitments", commitment_txs.len());
4327 if let Err(e) = self.update_counterparty_commitment_data(commitment_txs, htlc_data) {
4328 log_error!(logger, "Failed updating latest counterparty commitment state: {}", e);
4329 ret = Err(());
4330 }
4331 },
4332 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
4333 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
4334 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
4335 },
4336 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
4337 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
4338 if let Err(e) = self.provide_secret(*idx, *secret) {
4339 debug_assert!(false, "Latest counterparty commitment secret was invalid");
4340 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
4341 log_error!(logger, " {}", e);
4342 ret = Err(());
4343 }
4344 },
4345 ChannelMonitorUpdateStep::RenegotiatedFunding {
4346 channel_parameters, holder_commitment_tx, counterparty_commitment_tx,
4347 funding_contribution,
4348 } => {
4349 log_trace!(logger, "Updating ChannelMonitor with alternative holder and counterparty commitment transactions for funding txid {}",
4350 channel_parameters.funding_outpoint.unwrap().txid);
4351 if let Err(_) = self.renegotiated_funding(
4352 logger, channel_parameters, holder_commitment_tx, counterparty_commitment_tx,
4353 funding_contribution,
4354 ) {
4355 ret = Err(());
4356 }
4357 },
4358 ChannelMonitorUpdateStep::RenegotiatedFundingLocked { funding_txid } => {
4359 log_trace!(logger, "Updating ChannelMonitor with locked renegotiated funding txid {}", funding_txid);
4360 if let Err(_) = self.promote_funding(*funding_txid) {
4361 log_error!(logger, "Unknown funding with txid {} became locked", funding_txid);
4362 ret = Err(());
4363 }
4364 },
4365 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast, counterparty_failed_htlcs } => {
4366 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
4367 self.lockdown_from_offchain = true;
4368 self.fail_counterparty_failed_htlcs(counterparty_failed_htlcs, logger);
4369 if *should_broadcast {
4370 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
4374 self.onchain_events_awaiting_threshold_conf.iter().any(
4375 |event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
4376 if detected_funding_spend {
4377 log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
4378 continue;
4379 }
4380 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger, true);
4381 } else if !self.holder_tx_signed {
4382 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
4383 log_error!(logger, " in channel monitor!");
4384 log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
4385 } else {
4386 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
4390 }
4391 },
4392 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
4393 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
4394 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
4395 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
4396 }
4397 },
4398 ChannelMonitorUpdateStep::ReleasePaymentComplete { htlc } => {
4399 log_trace!(logger, "HTLC {htlc:?} permanently and fully resolved");
4400 self.htlcs_resolved_to_user.insert(*htlc);
4401 },
4402 }
4403 }
4404
4405 #[cfg(debug_assertions)] {
4406 self.counterparty_commitment_txs_from_update(updates);
4407 }
4408
4409 self.latest_update_id = updates.update_id;
4410
4411 for update in updates.updates.iter() {
4416 match update {
4417 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
4418 htlc_outputs, ..
4419 } => {
4420 self.fail_htlcs_from_update_after_funding_spend(
4423 htlc_outputs.iter().filter_map(|(htlc, source)| {
4424 source.as_ref().map(|s| (&**s, htlc.payment_hash, htlc.amount_msat))
4425 }),
4426 logger,
4427 );
4428 },
4429 ChannelMonitorUpdateStep::LatestCounterpartyCommitment {
4430 commitment_txs, htlc_data,
4431 } => {
4432 debug_assert_eq!(
4436 commitment_txs[0].nondust_htlcs().iter()
4437 .filter(|htlc| !htlc.offered).count(),
4438 htlc_data.nondust_htlc_sources.len(),
4439 );
4440 let nondust = commitment_txs[0]
4441 .nondust_htlcs()
4442 .iter()
4443 .filter(|htlc| !htlc.offered)
4444 .zip(htlc_data.nondust_htlc_sources.iter())
4445 .map(|(htlc, source)| (source, htlc.payment_hash, htlc.amount_msat));
4446 let dust = htlc_data.dust_htlcs.iter().filter_map(|(htlc, source)| {
4449 source.as_ref().map(|s| (s, htlc.payment_hash, htlc.amount_msat))
4450 });
4451 self.fail_htlcs_from_update_after_funding_spend(
4452 nondust.chain(dust),
4453 logger,
4454 );
4455 },
4456 _ => {},
4457 }
4458 }
4459
4460 let mut is_pre_close_update = false;
4464 for update in updates.updates.iter() {
4465 match update {
4466 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
4467 |ChannelMonitorUpdateStep::LatestHolderCommitment { .. }
4468 |ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
4469 |ChannelMonitorUpdateStep::LatestCounterpartyCommitment { .. }
4470 |ChannelMonitorUpdateStep::ShutdownScript { .. }
4471 |ChannelMonitorUpdateStep::CommitmentSecret { .. }
4472 |ChannelMonitorUpdateStep::RenegotiatedFunding { .. }
4473 |ChannelMonitorUpdateStep::RenegotiatedFundingLocked { .. } =>
4474 is_pre_close_update = true,
4475 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
4481 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
4482 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
4483 }
4484 }
4485
4486 if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
4487 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
4488 Err(())
4489 } else { ret }
4490 }
4491
4492 fn is_closed_without_updates(&self) -> bool {
4495 let mut commitment_not_advanced =
4496 self.current_counterparty_commitment_number == INITIAL_COMMITMENT_NUMBER;
4497 commitment_not_advanced &=
4498 self.current_holder_commitment_number == INITIAL_COMMITMENT_NUMBER;
4499 (self.holder_tx_signed || self.lockdown_from_offchain) && commitment_not_advanced
4500 }
4501
4502 fn no_further_updates_allowed(&self) -> bool {
4503 self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
4504 }
4505
4506 fn fail_counterparty_failed_htlcs<L: Logger>(
4515 &mut self, htlcs: &[(HTLCSource, PaymentHash)], logger: &WithContext<L>,
4516 ) {
4517 let in_counterparty_commitment = |source: &HTLCSource| {
4518 [
4519 self.funding.current_counterparty_commitment_txid,
4520 self.funding.prev_counterparty_commitment_txid,
4521 ]
4522 .into_iter()
4523 .flatten()
4524 .filter_map(|txid| self.funding.counterparty_claimable_outpoints.get(&txid))
4525 .flatten()
4526 .any(|(_, source_opt)| source_opt.as_deref() == Some(source))
4527 };
4528 for (source, payment_hash) in htlcs {
4529 let logger = WithContext::from(logger, None, None, Some(*payment_hash));
4530 if in_counterparty_commitment(source) {
4531 log_trace!(
4532 logger,
4533 "Not failing HTLC as it is still in a counterparty commitment transaction"
4534 );
4535 continue;
4536 }
4537 debug_assert!(!holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES)
4541 .any(|(_, s)| s == Some(source)));
4542 let duplicate_event =
4543 self.pending_monitor_events.iter().any(
4544 |event| match event {
4545 MonitorEvent::HTLCEvent(upd) => upd.source == *source,
4546 _ => false,
4547 },
4548 );
4549 if duplicate_event {
4550 continue;
4551 }
4552 let newly_failed = self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source));
4555 debug_assert!(newly_failed);
4556 log_trace!(logger, "Failing HTLC the counterparty failed before the channel closed");
4557 let htlc_value_msat = match source {
4559 HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } => Some(*first_hop_htlc_msat),
4560 _ => source.inbound_htlc_amount_msat(),
4561 };
4562 let htlc_value_satoshis = htlc_value_msat.unwrap_or(0) / 1000;
4563 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4564 source: source.clone(),
4565 payment_preimage: None,
4566 payment_hash: *payment_hash,
4567 htlc_value_satoshis,
4568 }));
4569 }
4570 }
4571
4572 fn fail_htlcs_from_update_after_funding_spend<'a, L: Logger>(
4584 &mut self, htlcs: impl Iterator<Item = (&'a HTLCSource, PaymentHash, u64)>,
4585 logger: &WithContext<L>,
4586 ) {
4587 let pending_spend_entry = self
4588 .onchain_events_awaiting_threshold_conf
4589 .iter()
4590 .find(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }))
4591 .map(|entry| (entry.txid, entry.transaction.clone(), entry.height, entry.block_hash));
4592 if self.funding_spend_confirmed.is_none() && pending_spend_entry.is_none() {
4593 return;
4594 }
4595
4596 let is_source_known = |source: &HTLCSource| {
4602 if let Some(ref txid) = self.funding.prev_counterparty_commitment_txid {
4603 if let Some(htlc_list) = self.funding.counterparty_claimable_outpoints.get(txid) {
4604 if htlc_list.iter().any(|(_, s)| s.as_ref().map(|s| s.as_ref()) == Some(source))
4605 {
4606 return true;
4607 }
4608 }
4609 }
4610 if holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES).any(|(_, s)| s == Some(source))
4619 {
4620 return true;
4621 }
4622 if let Some(mut iter) = holder_commitment_htlcs!(self, PREV_WITH_SOURCES) {
4623 if iter.any(|(_, s)| s == Some(source)) {
4624 return true;
4625 }
4626 }
4627 false
4628 };
4629 for (source, payment_hash, amount_msat) in htlcs {
4630 if is_source_known(source) {
4631 continue;
4632 }
4633 if self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
4634 continue;
4635 }
4636 let htlc_value_satoshis = amount_msat / 1000;
4637 let logger = WithContext::from(logger, None, None, Some(payment_hash));
4638 self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source));
4642 if let Some(confirmed_txid) = self.funding_spend_confirmed {
4643 log_trace!(
4645 logger,
4646 "Failing HTLC from late counterparty commitment update immediately \
4647 (funding spend already confirmed)"
4648 );
4649 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4650 payment_hash,
4651 payment_preimage: None,
4652 source: source.clone(),
4653 htlc_value_satoshis,
4654 }));
4655 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4656 commitment_tx_output_idx: None,
4657 resolving_txid: Some(confirmed_txid),
4658 resolving_tx: None,
4659 payment_preimage: None,
4660 });
4661 } else {
4662 let (txid, transaction, height, block_hash) = pending_spend_entry.clone().unwrap();
4664 let entry = OnchainEventEntry {
4665 txid,
4666 transaction,
4667 height,
4668 block_hash,
4669 event: OnchainEvent::HTLCUpdate {
4670 source: source.clone(),
4671 payment_hash,
4672 htlc_value_satoshis,
4673 commitment_tx_output_idx: None,
4674 },
4675 };
4676 log_trace!(
4677 logger,
4678 "Failing HTLC from late counterparty commitment update, \
4679 waiting for confirmation (at height {})",
4680 entry.confirmation_threshold()
4681 );
4682 self.onchain_events_awaiting_threshold_conf.push(entry);
4683 }
4684 }
4685 }
4686
4687 fn get_latest_update_id(&self) -> u64 {
4688 self.latest_update_id
4689 }
4690
4691 #[rustfmt::skip]
4694 fn get_funding_txo(&self) -> OutPoint {
4695 self.funding.channel_parameters.funding_outpoint
4696 .expect("Funding outpoint must be set for active monitor")
4697 }
4698
4699 fn get_funding_script(&self) -> ScriptBuf {
4702 self.funding.channel_parameters.make_funding_redeemscript().to_p2wsh()
4703 }
4704
4705 pub fn channel_id(&self) -> ChannelId {
4706 self.channel_id
4707 }
4708
4709 fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
4710 for txid in self.counterparty_commitment_txn_on_chain.keys() {
4714 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
4715 }
4716 &self.outputs_to_watch
4717 }
4718
4719 fn get_and_clear_pending_monitor_events_filtered<F: FnMut(&MonitorEvent) -> bool>(
4723 &mut self, mut predicate: F,
4724 ) -> Vec<MonitorEvent> {
4725 let mut released = Vec::new();
4726 let mut retained = Vec::new();
4727 for entry in self.pending_monitor_events.drain(..) {
4729 if predicate(&entry) {
4730 released.push(entry);
4731 } else {
4732 retained.push(entry);
4733 }
4734 }
4735 self.pending_monitor_events = retained;
4736 released
4737 }
4738
4739 #[rustfmt::skip]
4743 pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
4744 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
4745 let mut ret = Vec::with_capacity(pending_claim_events.len());
4746 for (claim_id, claim_event) in pending_claim_events {
4747 match claim_event {
4748 ClaimEvent::BumpCommitment {
4749 package_target_feerate_sat_per_1000_weight, commitment_tx,
4750 commitment_tx_fee_satoshis, pending_nondust_htlcs, anchor_output_idx,
4751 channel_parameters,
4752 } => {
4753 let channel_id = self.channel_id;
4754 let counterparty_node_id = self.counterparty_node_id;
4755 let commitment_txid = commitment_tx.compute_txid();
4756 ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
4757 channel_id,
4758 counterparty_node_id,
4759 claim_id,
4760 package_target_feerate_sat_per_1000_weight,
4761 anchor_descriptor: AnchorDescriptor {
4762 channel_derivation_parameters: ChannelDerivationParameters {
4763 keys_id: self.channel_keys_id,
4764 value_satoshis: channel_parameters.channel_value_satoshis,
4765 transaction_parameters: channel_parameters,
4766 },
4767 outpoint: BitcoinOutPoint {
4768 txid: commitment_txid,
4769 vout: anchor_output_idx,
4770 },
4771 value: commitment_tx.output[anchor_output_idx as usize].value,
4772 },
4773 pending_htlcs: pending_nondust_htlcs,
4774 commitment_tx,
4775 commitment_tx_fee_satoshis,
4776 }));
4777 },
4778 ClaimEvent::BumpHTLC {
4779 target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
4780 } => {
4781 let channel_id = self.channel_id;
4782 let counterparty_node_id = self.counterparty_node_id;
4783 ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
4784 channel_id,
4785 counterparty_node_id,
4786 claim_id,
4787 target_feerate_sat_per_1000_weight,
4788 htlc_descriptors: htlcs,
4789 tx_lock_time,
4790 }));
4791 }
4792 }
4793 }
4794 ret
4795 }
4796
4797 fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
4798 self.initial_counterparty_commitment_tx.clone().or_else(|| {
4799 self.initial_counterparty_commitment_info.map(
4802 |(
4803 their_per_commitment_point,
4804 feerate_per_kw,
4805 to_broadcaster_value,
4806 to_countersignatory_value,
4807 )| {
4808 let nondust_htlcs = vec![];
4809 debug_assert!(self.pending_funding.is_empty());
4813 let channel_parameters = &self.funding.channel_parameters;
4814
4815 let commitment_tx = self.build_counterparty_commitment_tx(
4816 channel_parameters,
4817 INITIAL_COMMITMENT_NUMBER,
4818 &their_per_commitment_point,
4819 to_broadcaster_value,
4820 to_countersignatory_value,
4821 feerate_per_kw,
4822 nondust_htlcs,
4823 );
4824 self.initial_counterparty_commitment_tx = Some(commitment_tx.clone());
4826 commitment_tx
4827 },
4828 )
4829 })
4830 }
4831
4832 #[rustfmt::skip]
4833 fn build_counterparty_commitment_tx(
4834 &self, channel_parameters: &ChannelTransactionParameters, commitment_number: u64,
4835 their_per_commitment_point: &PublicKey, to_broadcaster_value: u64,
4836 to_countersignatory_value: u64, feerate_per_kw: u32,
4837 nondust_htlcs: Vec<HTLCOutputInCommitment>
4838 ) -> CommitmentTransaction {
4839 let channel_parameters = &channel_parameters.as_counterparty_broadcastable();
4840 CommitmentTransaction::new(commitment_number, their_per_commitment_point,
4841 to_broadcaster_value, to_countersignatory_value, feerate_per_kw, nondust_htlcs, channel_parameters, &self.onchain_tx_handler.secp_ctx)
4842 }
4843
4844 #[rustfmt::skip]
4845 fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
4846 update.updates.iter().filter_map(|update| {
4847 match update {
4851 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
4852 ref htlc_outputs, commitment_number, their_per_commitment_point,
4853 feerate_per_kw: Some(feerate_per_kw),
4854 to_broadcaster_value_sat: Some(to_broadcaster_value),
4855 to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
4856
4857 let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
4858 htlc.transaction_output_index.map(|_| htlc).cloned()
4859 }).collect::<Vec<_>>();
4860
4861 debug_assert!(self.pending_funding.is_empty());
4865 let channel_parameters = &self.funding.channel_parameters;
4866 let commitment_tx = self.build_counterparty_commitment_tx(
4867 channel_parameters,
4868 commitment_number,
4869 &their_per_commitment_point,
4870 to_broadcaster_value,
4871 to_countersignatory_value,
4872 feerate_per_kw,
4873 nondust_htlcs,
4874 );
4875
4876 debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
4877
4878 Some(vec![commitment_tx])
4879 },
4880 &ChannelMonitorUpdateStep::LatestCounterpartyCommitment { ref commitment_txs, .. } => {
4881 Some(commitment_txs.clone())
4882 },
4883 &ChannelMonitorUpdateStep::RenegotiatedFunding { ref counterparty_commitment_tx, .. } => {
4884 Some(vec![counterparty_commitment_tx.clone()])
4885 },
4886 _ => None,
4887 }
4888 }).flatten().collect()
4889 }
4890
4891 #[rustfmt::skip]
4892 fn sign_to_local_justice_tx(
4893 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
4894 ) -> Result<Transaction, ()> {
4895 let secret = self.get_secret(commitment_number).ok_or(())?;
4896 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
4897 let their_per_commitment_point = PublicKey::from_secret_key(
4898 &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4899
4900 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
4901 &self.holder_revocation_basepoint, &their_per_commitment_point);
4902 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
4903 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
4904 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
4905 self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
4906
4907 let commitment_txid = &justice_tx.input[input_idx].previous_output.txid;
4908 let channel_parameters = core::iter::once(&self.funding)
4914 .chain(&self.pending_funding)
4915 .find(|funding| funding.counterparty_claimable_outpoints.contains_key(commitment_txid))
4916 .map(|funding| &funding.channel_parameters)
4917 .ok_or(())?;
4918 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
4919 &channel_parameters, &justice_tx, input_idx, value, &per_commitment_key,
4920 &self.onchain_tx_handler.secp_ctx,
4921 )?;
4922 justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
4923 justice_tx.input[input_idx].witness.push(&[1u8]);
4924 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
4925 Ok(justice_tx)
4926 }
4927
4928 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
4930 self.commitment_secrets.get_secret(idx)
4931 }
4932
4933 fn get_min_seen_secret(&self) -> u64 {
4934 self.commitment_secrets.get_min_seen_secret()
4935 }
4936
4937 fn get_cur_counterparty_commitment_number(&self) -> u64 {
4938 self.current_counterparty_commitment_number
4939 }
4940
4941 fn get_cur_holder_commitment_number(&self) -> u64 {
4942 self.current_holder_commitment_number
4943 }
4944
4945 #[rustfmt::skip]
4953 fn check_spend_counterparty_transaction<L: Logger>(&mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
4954 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
4955 {
4956 let mut claimable_outpoints = Vec::new();
4959 let mut to_counterparty_output_info = None;
4960
4961 let funding_spent = get_confirmed_funding_scope!(self);
4962 let per_commitment_option = funding_spent.counterparty_claimable_outpoints.get(&commitment_txid);
4963
4964 macro_rules! ignore_error {
4965 ( $thing : expr ) => {
4966 match $thing {
4967 Ok(a) => a,
4968 Err(_) => return (claimable_outpoints, to_counterparty_output_info)
4969 }
4970 };
4971 }
4972
4973 let funding_txid_spent = commitment_tx.input[0].previous_output.txid;
4974 let commitment_number = 0xffffffffffff - ((((commitment_tx.input[0].sequence.0 as u64 & 0xffffff) << 3*8) | (commitment_tx.lock_time.to_consensus_u32() as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
4975 if commitment_number >= self.get_min_seen_secret() {
4976 assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
4977
4978 let secret = self.get_secret(commitment_number).unwrap();
4979 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
4980 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4981 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point,);
4982 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key));
4983
4984 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
4985 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
4986
4987 for (idx, outp) in commitment_tx.output.iter().enumerate() {
4989 if outp.script_pubkey == revokeable_p2wsh {
4990 let revk_outp = RevokedOutput::build(
4991 per_commitment_point, per_commitment_key, outp.value,
4992 funding_spent.channel_parameters.clone(), height,
4993 );
4994 let justice_package = PackageTemplate::build_package(
4995 commitment_txid, idx as u32,
4996 PackageSolvingData::RevokedOutput(revk_outp),
4997 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
4998 );
4999 claimable_outpoints.push(justice_package);
5000 to_counterparty_output_info =
5001 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
5002 }
5003 }
5004
5005 if let Some(per_commitment_claimable_data) = per_commitment_option {
5007 for (htlc, _) in per_commitment_claimable_data {
5008 if let Some(transaction_output_index) = htlc.transaction_output_index {
5009 if transaction_output_index as usize >= commitment_tx.output.len() ||
5010 commitment_tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
5011 return (claimable_outpoints, to_counterparty_output_info);
5013 }
5014 let revk_htlc_outp = RevokedHTLCOutput::build(
5015 per_commitment_point, per_commitment_key, htlc.clone(),
5016 funding_spent.channel_parameters.clone(), height,
5017 );
5018 let counterparty_spendable_height = if htlc.offered {
5019 htlc.cltv_expiry
5020 } else {
5021 height
5022 };
5023 let justice_package = PackageTemplate::build_package(
5024 commitment_txid,
5025 transaction_output_index,
5026 PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
5027 counterparty_spendable_height,
5028 );
5029 claimable_outpoints.push(justice_package);
5030 }
5031 }
5032 }
5033
5034 if !claimable_outpoints.is_empty() || per_commitment_option.is_some() { log_error!(logger, "Got broadcast of revoked counterparty commitment transaction, going to generate general spend tx with {} inputs", claimable_outpoints.len());
5038 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
5039
5040 if let Some(per_commitment_claimable_data) = per_commitment_option {
5041 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, commitment_tx, height,
5042 block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
5043 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
5044 ), logger);
5045 } else {
5046 debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
5051 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, commitment_tx, height,
5052 block_hash, [].iter().map(|reference| *reference), logger);
5053 }
5054 }
5055 } else if let Some(per_commitment_claimable_data) = per_commitment_option {
5056 assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
5057
5058 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
5069
5070 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
5071 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, commitment_tx, height, block_hash,
5072 per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
5073 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
5074 ), logger);
5075 let (htlc_claim_reqs, counterparty_output_info) =
5076 self.get_counterparty_output_claim_info(funding_spent, commitment_number, commitment_txid, commitment_tx, per_commitment_claimable_data, Some(height));
5077 to_counterparty_output_info = counterparty_output_info;
5078 for req in htlc_claim_reqs {
5079 claimable_outpoints.push(req);
5080 }
5081 }
5082
5083 (claimable_outpoints, to_counterparty_output_info)
5084 }
5085
5086 fn get_point_for_commitment_number(&self, commitment_number: u64) -> Option<PublicKey> {
5087 let per_commitment_points = &self.their_cur_per_commitment_points?;
5088
5089 if per_commitment_points.0 == commitment_number {
5092 Some(per_commitment_points.1)
5093 } else if let Some(point) = per_commitment_points.2.as_ref() {
5094 if per_commitment_points.0 == commitment_number + 1 {
5098 Some(*point)
5099 } else {
5100 None
5101 }
5102 } else {
5103 None
5104 }
5105 }
5106
5107 fn get_counterparty_output_claims_for_preimage(
5108 &self, preimage: PaymentPreimage, funding_spent: &FundingScope, commitment_number: u64,
5109 commitment_txid: Txid,
5110 per_commitment_option: Option<&Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
5111 confirmation_height: Option<u32>,
5112 ) -> Vec<PackageTemplate> {
5113 let per_commitment_claimable_data = match per_commitment_option {
5114 Some(outputs) => outputs,
5115 None => return Vec::new(),
5116 };
5117 let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
5118 Some(point) => point,
5119 None => return Vec::new(),
5120 };
5121
5122 let matching_payment_hash = PaymentHash::from(preimage);
5123 per_commitment_claimable_data
5124 .iter()
5125 .filter_map(|(htlc, _)| {
5126 if let Some(transaction_output_index) = htlc.transaction_output_index {
5127 if htlc.offered && htlc.payment_hash == matching_payment_hash {
5128 let htlc_data = PackageSolvingData::CounterpartyOfferedHTLCOutput(
5129 CounterpartyOfferedHTLCOutput::build(
5130 per_commitment_point,
5131 preimage,
5132 htlc.clone(),
5133 funding_spent.channel_parameters.clone(),
5134 confirmation_height,
5135 ),
5136 );
5137 Some(PackageTemplate::build_package(
5138 commitment_txid,
5139 transaction_output_index,
5140 htlc_data,
5141 htlc.cltv_expiry,
5142 ))
5143 } else {
5144 None
5145 }
5146 } else {
5147 None
5148 }
5149 })
5150 .collect()
5151 }
5152
5153 fn get_counterparty_output_claim_info(
5155 &self, funding_spent: &FundingScope, commitment_number: u64, commitment_txid: Txid,
5156 tx: &Transaction,
5157 per_commitment_claimable_data: &[(HTLCOutputInCommitment, Option<Box<HTLCSource>>)],
5158 confirmation_height: Option<u32>,
5159 ) -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
5160 let mut claimable_outpoints = Vec::new();
5161 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
5162
5163 let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
5164 Some(point) => point,
5165 None => return (claimable_outpoints, to_counterparty_output_info),
5166 };
5167
5168 let revocation_pubkey = RevocationKey::from_basepoint(
5169 &self.onchain_tx_handler.secp_ctx,
5170 &self.holder_revocation_basepoint,
5171 &per_commitment_point,
5172 );
5173 let delayed_key = DelayedPaymentKey::from_basepoint(
5174 &self.onchain_tx_handler.secp_ctx,
5175 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
5176 &per_commitment_point,
5177 );
5178 let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(
5179 &revocation_pubkey,
5180 self.counterparty_commitment_params.on_counterparty_tx_csv,
5181 &delayed_key,
5182 )
5183 .to_p2wsh();
5184 for (idx, outp) in tx.output.iter().enumerate() {
5185 if outp.script_pubkey == revokeable_p2wsh {
5186 to_counterparty_output_info =
5187 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
5188 }
5189 }
5190
5191 for &(ref htlc, _) in per_commitment_claimable_data.iter() {
5192 if let Some(transaction_output_index) = htlc.transaction_output_index {
5193 if transaction_output_index as usize >= tx.output.len()
5194 || tx.output[transaction_output_index as usize].value
5195 != htlc.to_bitcoin_amount()
5196 {
5197 return (claimable_outpoints, to_counterparty_output_info);
5199 }
5200 let preimage = if htlc.offered {
5201 if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) {
5202 Some(*p)
5203 } else {
5204 None
5205 }
5206 } else {
5207 None
5208 };
5209 if preimage.is_some() || !htlc.offered {
5210 let counterparty_htlc_outp = if htlc.offered {
5211 PackageSolvingData::CounterpartyOfferedHTLCOutput(
5212 CounterpartyOfferedHTLCOutput::build(
5213 per_commitment_point,
5214 preimage.unwrap(),
5215 htlc.clone(),
5216 funding_spent.channel_parameters.clone(),
5217 confirmation_height,
5218 ),
5219 )
5220 } else {
5221 PackageSolvingData::CounterpartyReceivedHTLCOutput(
5222 CounterpartyReceivedHTLCOutput::build(
5223 per_commitment_point,
5224 htlc.clone(),
5225 funding_spent.channel_parameters.clone(),
5226 confirmation_height,
5227 ),
5228 )
5229 };
5230 let counterparty_package = PackageTemplate::build_package(
5231 commitment_txid,
5232 transaction_output_index,
5233 counterparty_htlc_outp,
5234 htlc.cltv_expiry,
5235 );
5236 claimable_outpoints.push(counterparty_package);
5237 }
5238 }
5239 }
5240
5241 (claimable_outpoints, to_counterparty_output_info)
5242 }
5243
5244 #[rustfmt::skip]
5246 fn check_spend_counterparty_htlc<L: Logger>(
5247 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
5248 ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) {
5249 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
5250 let per_commitment_key = match SecretKey::from_slice(&secret) {
5251 Ok(key) => key,
5252 Err(_) => return (Vec::new(), None)
5253 };
5254 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
5255
5256 let funding_spent = get_confirmed_funding_scope!(self);
5257 debug_assert!(funding_spent.counterparty_claimable_outpoints.contains_key(commitment_txid));
5258
5259 let htlc_txid = tx.compute_txid();
5260 let mut claimable_outpoints = vec![];
5261 let mut outputs_to_watch = None;
5262 for (idx, input) in tx.input.iter().enumerate() {
5273 if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
5274 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
5275 let revk_outp = RevokedOutput::build(
5276 per_commitment_point, per_commitment_key, tx.output[idx].value,
5277 self.funding.channel_parameters.clone(), height,
5278 );
5279 let justice_package = PackageTemplate::build_package(
5280 htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
5281 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
5282 );
5283 claimable_outpoints.push(justice_package);
5284 if outputs_to_watch.is_none() {
5285 outputs_to_watch = Some((htlc_txid, vec![]));
5286 }
5287 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
5288 }
5289 }
5290 (claimable_outpoints, outputs_to_watch)
5291 }
5292
5293 #[rustfmt::skip]
5294 fn get_broadcasted_holder_htlc_descriptors(
5295 &self, funding: &FundingScope, holder_tx: &HolderCommitmentTransaction,
5296 ) -> Vec<HTLCDescriptor> {
5297 let tx = holder_tx.trust();
5298 let mut htlcs = Vec::with_capacity(holder_tx.nondust_htlcs().len());
5299 debug_assert_eq!(holder_tx.nondust_htlcs().len(), holder_tx.counterparty_htlc_sigs.len());
5300 for (htlc, counterparty_sig) in holder_tx.nondust_htlcs().iter().zip(holder_tx.counterparty_htlc_sigs.iter()) {
5301 assert!(htlc.transaction_output_index.is_some(), "Expected transaction output index for non-dust HTLC");
5302
5303 let preimage = if htlc.offered {
5304 None
5305 } else if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
5306 Some(*preimage)
5307 } else {
5308 continue;
5310 };
5311
5312 htlcs.push(HTLCDescriptor {
5313 channel_derivation_parameters: ChannelDerivationParameters {
5314 value_satoshis: funding.channel_parameters.channel_value_satoshis,
5315 keys_id: self.channel_keys_id,
5316 transaction_parameters: funding.channel_parameters.clone(),
5317 },
5318 commitment_txid: tx.txid(),
5319 per_commitment_number: tx.commitment_number(),
5320 per_commitment_point: tx.per_commitment_point(),
5321 feerate_per_kw: tx.negotiated_feerate_per_kw(),
5322 htlc: htlc.clone(),
5323 preimage,
5324 counterparty_sig: *counterparty_sig,
5325 });
5326 }
5327
5328 htlcs
5329 }
5330
5331 #[rustfmt::skip]
5335 fn get_broadcasted_holder_claims(
5336 &self, funding: &FundingScope, holder_tx: &HolderCommitmentTransaction, conf_height: u32,
5337 ) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
5338 let tx = holder_tx.trust();
5339 let keys = tx.keys();
5340 let redeem_script = chan_utils::get_revokeable_redeemscript(
5341 &keys.revocation_key, self.on_holder_tx_csv, &keys.broadcaster_delayed_payment_key,
5342 );
5343 let broadcasted_holder_revokable_script = Some((
5344 redeem_script.to_p2wsh(), holder_tx.per_commitment_point(), keys.revocation_key.clone(),
5345 ));
5346
5347 let claim_requests = self.get_broadcasted_holder_htlc_descriptors(funding, holder_tx).into_iter()
5348 .map(|htlc_descriptor| {
5349 let counterparty_spendable_height = if htlc_descriptor.htlc.offered {
5350 conf_height
5351 } else {
5352 htlc_descriptor.htlc.cltv_expiry
5353 };
5354 let transaction_output_index = htlc_descriptor.htlc.transaction_output_index
5355 .expect("Expected transaction output index for non-dust HTLC");
5356 PackageTemplate::build_package(
5357 tx.txid(), transaction_output_index,
5358 PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build(htlc_descriptor, conf_height)),
5359 counterparty_spendable_height,
5360 )
5361 })
5362 .collect();
5363
5364 (claim_requests, broadcasted_holder_revokable_script)
5365 }
5366
5367 #[rustfmt::skip]
5369 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderCommitmentTransaction) -> Vec<(u32, TxOut)> {
5370 let mut watch_outputs = Vec::with_capacity(holder_tx.nondust_htlcs().len());
5371 let tx = holder_tx.trust();
5372 for htlc in holder_tx.nondust_htlcs() {
5373 if let Some(transaction_output_index) = htlc.transaction_output_index {
5374 watch_outputs.push((
5375 transaction_output_index,
5376 tx.built_transaction().transaction.output[transaction_output_index as usize].clone(),
5377 ));
5378 } else {
5379 debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5380 }
5381 }
5382 watch_outputs
5383 }
5384
5385 fn check_spend_holder_transaction<L: Logger>(
5390 &mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32,
5391 block_hash: &BlockHash, logger: &L,
5392 ) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> {
5393 let funding_spent = get_confirmed_funding_scope!(self);
5394
5395 let holder_commitment_tx = Some((&funding_spent.current_holder_commitment_tx, true))
5397 .filter(|(current_holder_commitment_tx, _)| {
5398 current_holder_commitment_tx.trust().txid() == commitment_txid
5399 })
5400 .or_else(|| {
5401 funding_spent
5402 .prev_holder_commitment_tx
5403 .as_ref()
5404 .map(|prev_holder_commitment_tx| (prev_holder_commitment_tx, false))
5405 .filter(|(prev_holder_commitment_tx, _)| {
5406 prev_holder_commitment_tx.trust().txid() == commitment_txid
5407 })
5408 });
5409
5410 if let Some((holder_commitment_tx, current)) = holder_commitment_tx {
5411 let funding_txid_spent = commitment_tx.input[0].previous_output.txid;
5412 assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
5413
5414 let current_msg = if current { "latest holder" } else { "previous holder" };
5415 log_info!(logger, "Got broadcast of {current_msg} commitment tx {commitment_txid}, searching for available HTLCs to claim");
5416
5417 let (claim_requests, broadcasted_holder_revokable_script) =
5418 self.get_broadcasted_holder_claims(funding_spent, holder_commitment_tx, height);
5419 self.broadcasted_holder_revokable_script = broadcasted_holder_revokable_script;
5420 let watch_outputs = self.get_broadcasted_holder_watch_outputs(holder_commitment_tx);
5421
5422 if current {
5423 fail_unbroadcast_htlcs!(
5424 self,
5425 current_msg,
5426 commitment_txid,
5427 commitment_tx,
5428 height,
5429 block_hash,
5430 holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES),
5431 logger
5432 );
5433 } else {
5434 fail_unbroadcast_htlcs!(
5435 self,
5436 current_msg,
5437 commitment_txid,
5438 commitment_tx,
5439 height,
5440 block_hash,
5441 holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(),
5442 logger
5443 );
5444 }
5445
5446 Some((claim_requests, (commitment_txid, watch_outputs)))
5447 } else {
5448 None
5449 }
5450 }
5451
5452 #[rustfmt::skip]
5455 pub fn cancel_prev_commitment_claims<L: Logger>(
5456 &mut self, logger: &L, confirmed_commitment_txid: &Txid
5457 ) {
5458 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
5459 if counterparty_commitment_txid == confirmed_commitment_txid {
5461 continue;
5462 }
5463 for funding in core::iter::once(&self.funding).chain(self.pending_funding.iter()) {
5466 let mut found_claim = false;
5467 for (htlc, _) in funding.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
5468 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
5469 if let Some(vout) = htlc.transaction_output_index {
5470 outpoint.vout = vout;
5471 if self.onchain_tx_handler.abandon_claim(&outpoint) {
5472 found_claim = true;
5473 }
5474 }
5475 }
5476 if found_claim {
5477 log_trace!(logger, "Canceled claims for previously confirmed counterparty commitment with txid {counterparty_commitment_txid}");
5478 }
5479 }
5480 }
5481 for funding in core::iter::once(&self.funding).chain(self.pending_funding.iter()) {
5485 if funding.current_holder_commitment_tx.trust().txid() != *confirmed_commitment_txid {
5486 let mut found_claim = false;
5487 let txid = funding.current_holder_commitment_tx.trust().txid();
5488 let mut outpoint = BitcoinOutPoint { txid, vout: 0 };
5489 for htlc in funding.current_holder_commitment_tx.nondust_htlcs() {
5490 if let Some(vout) = htlc.transaction_output_index {
5491 outpoint.vout = vout;
5492 if self.onchain_tx_handler.abandon_claim(&outpoint) {
5493 found_claim = true;
5494 }
5495 } else {
5496 debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5497 }
5498 }
5499 if found_claim {
5500 log_trace!(logger, "Canceled claims for previously broadcast holder commitment with txid {txid}");
5501 }
5502 }
5503 if let Some(prev_holder_commitment_tx) = &funding.prev_holder_commitment_tx {
5504 let txid = prev_holder_commitment_tx.trust().txid();
5505 if txid != *confirmed_commitment_txid {
5506 let mut found_claim = false;
5507 let mut outpoint = BitcoinOutPoint { txid, vout: 0 };
5508 for htlc in prev_holder_commitment_tx.nondust_htlcs() {
5509 if let Some(vout) = htlc.transaction_output_index {
5510 outpoint.vout = vout;
5511 if self.onchain_tx_handler.abandon_claim(&outpoint) {
5512 found_claim = true;
5513 }
5514 } else {
5515 debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5516 }
5517 }
5518 if found_claim {
5519 log_trace!(logger, "Canceled claims for previously broadcast holder commitment with txid {txid}");
5520 }
5521 }
5522 }
5523 }
5524 }
5525
5526 #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
5527 #[rustfmt::skip]
5529 fn unsafe_get_latest_holder_commitment_txn<L: Logger>(
5530 &mut self, logger: &WithContext<L>
5531 ) -> Vec<Transaction> {
5532 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
5533 let commitment_tx = {
5534 let sig = self.onchain_tx_handler.signer.unsafe_sign_holder_commitment(
5535 &self.funding.channel_parameters, &self.funding.current_holder_commitment_tx,
5536 &self.onchain_tx_handler.secp_ctx,
5537 ).expect("sign holder commitment");
5538 let redeem_script = self.funding.channel_parameters.make_funding_redeemscript();
5539 self.funding.current_holder_commitment_tx.add_holder_sig(&redeem_script, sig)
5540 };
5541 let mut holder_transactions = vec![commitment_tx];
5542
5543 if self.channel_type_features().supports_anchors_zero_fee_htlc_tx()
5544 || self.channel_type_features().supports_anchor_zero_fee_commitments()
5545 {
5546 return holder_transactions;
5559 }
5560
5561 self.get_broadcasted_holder_htlc_descriptors(&self.funding, &self.funding.current_holder_commitment_tx)
5562 .into_iter()
5563 .for_each(|htlc_descriptor| {
5564 let txid = self.funding.current_holder_commitment_tx.trust().txid();
5565 let vout = htlc_descriptor.htlc.transaction_output_index
5566 .expect("Expected transaction output index for non-dust HTLC");
5567 let htlc_output = HolderHTLCOutput::build(htlc_descriptor, 0);
5568 if let Some(htlc_tx) = htlc_output.get_maybe_signed_htlc_tx(
5569 &mut self.onchain_tx_handler, &::bitcoin::OutPoint { txid, vout },
5570 ) {
5571 if htlc_tx.is_fully_signed() {
5572 holder_transactions.push(htlc_tx.0);
5573 }
5574 }
5575 });
5576
5577 holder_transactions
5578 }
5579
5580 #[rustfmt::skip]
5581 fn block_connected<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
5582 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
5583 fee_estimator: F, logger: &WithContext<L>,
5584 ) -> Vec<TransactionOutputs> {
5585 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
5586 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
5587 }
5588
5589 #[rustfmt::skip]
5590 fn best_block_updated<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
5591 &mut self,
5592 header: &Header,
5593 height: u32,
5594 broadcaster: B,
5595 fee_estimator: &LowerBoundedFeeEstimator<F>,
5596 logger: &WithContext<L>,
5597 ) -> Vec<TransactionOutputs> {
5598 let block_hash = header.block_hash();
5599
5600 if height > self.best_block.height {
5601 self.best_block.update_for_new_tip(block_hash, height);
5602 log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
5603 self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
5604 } else if block_hash != self.best_block.block_hash {
5605 self.best_block = BlockLocator::new(block_hash, height);
5606 log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
5607 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
5608
5609 let conf_target = self.closure_conf_target();
5610 self.onchain_tx_handler.blocks_disconnected(
5611 height, &broadcaster, conf_target, &self.destination_script, fee_estimator, logger,
5612 );
5613 Vec::new()
5614 } else { Vec::new() }
5615 }
5616
5617 #[rustfmt::skip]
5618 fn transactions_confirmed<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
5619 &mut self,
5620 header: &Header,
5621 txdata: &TransactionData,
5622 height: u32,
5623 broadcaster: B,
5624 fee_estimator: &LowerBoundedFeeEstimator<F>,
5625 logger: &WithContext<L>,
5626 ) -> Vec<TransactionOutputs> {
5627 let funding_seen_before = self.funding_seen_onchain;
5628 let txn_matched = self.filter_block(txdata);
5629 let block_hash = header.block_hash();
5630
5631 if !self.funding_seen_onchain || self.funding_tx_confirmed_in.is_none() {
5632 for tx in txn_matched.iter() {
5633 let txid = tx.compute_txid();
5634 if self.funding.funding_txid() == txid {
5635 self.funding_seen_onchain = true;
5636 if self.funding_tx_confirmed_in.is_none() {
5637 self.funding_tx_confirmed_in = Some((height, block_hash));
5638 }
5639 } else if self.pending_funding.iter().any(|f| f.funding_txid() == txid) {
5640 self.funding_seen_onchain = true;
5642 }
5643 }
5644 }
5645
5646 for tx in &txn_matched {
5647 let mut output_val = Amount::ZERO;
5648 for out in tx.output.iter() {
5649 if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
5650 output_val += out.value;
5651 if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
5652 }
5653 }
5654
5655 let mut should_broadcast_commitment = false;
5661
5662 let mut watch_outputs = Vec::new();
5663 let mut claimable_outpoints = Vec::new();
5664
5665 if self.is_manual_broadcast && !funding_seen_before && self.funding_seen_onchain && self.holder_tx_signed
5666 {
5667 should_broadcast_commitment = true;
5668 }
5669 'tx_iter: for tx in &txn_matched {
5670 let txid = tx.compute_txid();
5671 log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
5672 if let Some((alternative_funding_txid, _, conf_hash)) = self.alternative_funding_confirmed {
5674 if alternative_funding_txid == txid {
5675 if conf_hash.is_none() {
5676 self.alternative_funding_confirmed = Some((txid, height, Some(block_hash)));
5677 }
5678 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
5679 continue 'tx_iter;
5680 }
5681 }
5682 if Some(txid) == self.funding_spend_confirmed {
5683 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
5684 continue 'tx_iter;
5685 }
5686 for ev in self.onchain_events_awaiting_threshold_conf.iter() {
5687 if ev.txid == txid {
5688 if let Some(conf_hash) = ev.block_hash {
5689 assert_eq!(header.block_hash(), conf_hash,
5690 "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
5691 This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
5692 }
5693 log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
5694 continue 'tx_iter;
5695 }
5696 }
5697 for htlc in self.htlcs_resolved_on_chain.iter() {
5698 if Some(txid) == htlc.resolving_txid {
5699 log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
5700 continue 'tx_iter;
5701 }
5702 }
5703 for spendable_txid in self.spendable_txids_confirmed.iter() {
5704 if txid == *spendable_txid {
5705 log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
5706 continue 'tx_iter;
5707 }
5708 }
5709
5710 if let Some(alternative_funding) = self
5715 .pending_funding
5716 .iter()
5717 .find(|funding| funding.funding_txid() == txid)
5718 {
5719 assert!(self.alternative_funding_confirmed.is_none());
5720 assert!(
5721 !self.onchain_events_awaiting_threshold_conf.iter()
5722 .any(|e| matches!(e.event, OnchainEvent::AlternativeFundingConfirmation {}))
5723 );
5724 assert!(self.funding_spend_confirmed.is_none());
5725 assert!(
5726 !self.onchain_events_awaiting_threshold_conf.iter()
5727 .any(|e| matches!(e.event, OnchainEvent::FundingSpendConfirmation { .. }))
5728 );
5729
5730 let (desc, msg) = if alternative_funding.is_splice() {
5731 debug_assert!(tx.input.iter().any(|input| {
5732 let funding_outpoint = self.funding.funding_outpoint().into_bitcoin_outpoint();
5733 input.previous_output == funding_outpoint
5734 }));
5735 ("Splice", "splice_locked")
5736 } else {
5737 ("Dual-funded RBF", "channel_ready")
5738 };
5739 let action = if self.holder_tx_signed || self.funding_spend_seen {
5740 ", broadcasting holder commitment transaction".to_string()
5741 } else if !self.no_further_updates_allowed() {
5742 format!(", waiting for `{msg}` exchange")
5743 } else {
5744 "".to_string()
5745 };
5746 log_info!(logger, "{desc} confirmed with txid {txid}{action}");
5747
5748 self.alternative_funding_confirmed = Some((txid, height, Some(block_hash)));
5749
5750 if self.no_further_updates_allowed() {
5751 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
5755 txid,
5756 transaction: Some((*tx).clone()),
5757 height,
5758 block_hash: Some(block_hash),
5759 event: OnchainEvent::AlternativeFundingConfirmation {},
5760 });
5761 }
5762
5763 if self.holder_tx_signed || self.funding_spend_seen {
5764 let new_holder_commitment_txid =
5767 alternative_funding.current_holder_commitment_tx.trust().txid();
5768 self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5769
5770 should_broadcast_commitment = true;
5774 }
5775
5776 continue 'tx_iter;
5777 }
5778
5779 if tx.input.len() == 1 {
5780 if let Some(funding_txid_spent) = core::iter::once(&self.funding)
5785 .chain(self.pending_funding.iter())
5786 .find(|funding| {
5787 let funding_outpoint = funding.funding_outpoint().into_bitcoin_outpoint();
5788 funding_outpoint == tx.input[0].previous_output
5789 })
5790 .map(|funding| funding.funding_txid())
5791 {
5792 assert_eq!(
5793 funding_txid_spent,
5794 self.alternative_funding_confirmed
5795 .map(|(txid, _, _)| txid)
5796 .unwrap_or_else(|| self.funding.funding_txid())
5797 );
5798 log_info!(logger, "Channel closed by funding output spend in txid {txid}");
5799 if !self.funding_spend_seen {
5800 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(()));
5801 }
5802 self.funding_spend_seen = true;
5803
5804 let mut balance_spendable_csv = None;
5805 let mut commitment_tx_to_counterparty_output = None;
5806
5807 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
5809 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(txid, &tx, height, &block_hash, &logger) {
5810 if !new_outputs.1.is_empty() {
5811 watch_outputs.push(new_outputs);
5812 }
5813
5814 claimable_outpoints.append(&mut new_outpoints);
5815 balance_spendable_csv = Some(self.on_holder_tx_csv);
5816 } else {
5817 let mut new_watch_outputs = Vec::new();
5818 for (idx, outp) in tx.output.iter().enumerate() {
5819 new_watch_outputs.push((idx as u32, outp.clone()));
5820 }
5821 watch_outputs.push((txid, new_watch_outputs));
5822
5823 let (mut new_outpoints, counterparty_output_idx_sats) =
5824 self.check_spend_counterparty_transaction(txid, &tx, height, &block_hash, &logger);
5825 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
5826
5827 claimable_outpoints.append(&mut new_outpoints);
5828 }
5829
5830 if should_broadcast_commitment {
5833 log_info!(logger, "Canceling our queued holder commitment broadcast as we've found a conflict confirm instead");
5834 should_broadcast_commitment = false;
5835 }
5836 }
5837
5838 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
5839 txid,
5840 transaction: Some((*tx).clone()),
5841 height,
5842 block_hash: Some(block_hash),
5843 event: OnchainEvent::FundingSpendConfirmation {
5844 on_local_output_csv: balance_spendable_csv,
5845 commitment_tx_to_counterparty_output,
5846 },
5847 });
5848
5849 self.cancel_prev_commitment_claims(&logger, &txid);
5853 }
5854 }
5855 for tx_input in &tx.input {
5859 let commitment_txid = tx_input.previous_output.txid;
5860 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
5861 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
5862 &tx, commitment_number, &commitment_txid, height, &logger
5863 );
5864 claimable_outpoints.append(&mut new_outpoints);
5865 if let Some(new_outputs) = new_outputs_option {
5866 watch_outputs.push(new_outputs);
5867 }
5868 break;
5873 }
5874 }
5875 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
5876
5877 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
5882 }
5883
5884 if height > self.best_block.height {
5885 self.best_block.update_for_new_tip(block_hash, height);
5886 }
5887
5888 if should_broadcast_commitment {
5889 let (mut claimables, mut outputs) =
5890 self.generate_claimable_outpoints_and_watch_outputs(None, false);
5891 claimable_outpoints.append(&mut claimables);
5892 watch_outputs.append(&mut outputs);
5893 }
5894
5895 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
5896 }
5897
5898 #[rustfmt::skip]
5907 fn block_confirmed<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
5908 &mut self,
5909 conf_height: u32,
5910 conf_hash: BlockHash,
5911 txn_matched: Vec<&Transaction>,
5912 mut watch_outputs: Vec<TransactionOutputs>,
5913 mut claimable_outpoints: Vec<PackageTemplate>,
5914 broadcaster: &B,
5915 fee_estimator: &LowerBoundedFeeEstimator<F>,
5916 logger: &WithContext<L>,
5917 ) -> Vec<TransactionOutputs> {
5918 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
5919 debug_assert!(self.best_block.height >= conf_height);
5920
5921 if claimable_outpoints.is_empty() {
5923 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
5924 if let Some(payment_hash) = should_broadcast {
5925 let reason = ClosureReason::HTLCsTimedOut { payment_hash: Some(payment_hash) };
5926 let (mut new_outpoints, mut new_outputs) =
5927 self.generate_claimable_outpoints_and_watch_outputs(Some(reason), false);
5928 if !self.is_manual_broadcast || self.funding_seen_onchain {
5929 claimable_outpoints.append(&mut new_outpoints);
5930 watch_outputs.append(&mut new_outputs);
5931 } else {
5932 log_info!(logger, "Not broadcasting holder commitment for manual-broadcast channel before funding appears on-chain");
5933 }
5934 }
5935 }
5936
5937 let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
5939 self.onchain_events_awaiting_threshold_conf.drain(..).partition(
5940 |entry| entry.has_reached_confirmation_threshold(&self.best_block));
5941 self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
5942
5943 #[cfg(debug_assertions)]
5945 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
5946 .iter()
5947 .filter_map(|entry| match &entry.event {
5948 OnchainEvent::HTLCUpdate { source, .. } => Some(source.clone()),
5949 _ => None,
5950 })
5951 .collect();
5952 #[cfg(debug_assertions)]
5953 let mut matured_htlcs = Vec::new();
5954
5955 for entry in onchain_events_reaching_threshold_conf {
5957 match entry.event {
5958 OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
5959 #[cfg(debug_assertions)]
5961 {
5962 debug_assert!(
5963 !unmatured_htlcs.contains(&source),
5964 "An unmature HTLC transaction conflicts with a maturing one; failed to \
5965 call either transaction_unconfirmed for the conflicting transaction \
5966 or blocks_disconnected for a block before it.");
5967 debug_assert!(
5968 !matured_htlcs.contains(&source),
5969 "A matured HTLC transaction conflicts with a maturing one; failed to \
5970 call either transaction_unconfirmed for the conflicting transaction \
5971 or blocks_disconnected for a block before it.");
5972 matured_htlcs.push(source.clone());
5973 }
5974
5975 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
5976 &payment_hash, entry.txid);
5977 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
5978 payment_hash,
5979 payment_preimage: None,
5980 source,
5981 htlc_value_satoshis,
5982 }));
5983 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
5984 commitment_tx_output_idx,
5985 resolving_txid: Some(entry.txid),
5986 resolving_tx: entry.transaction,
5987 payment_preimage: None,
5988 });
5989 },
5990 OnchainEvent::MaturingOutput { descriptor } => {
5991 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
5992 self.pending_events.push(Event::SpendableOutputs {
5993 outputs: vec![descriptor],
5994 channel_id: Some(self.channel_id()),
5995 counterparty_node_id: Some(self.counterparty_node_id),
5996 });
5997 self.spendable_txids_confirmed.push(entry.txid);
5998 },
5999 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
6000 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
6001 commitment_tx_output_idx: Some(commitment_tx_output_idx),
6002 resolving_txid: Some(entry.txid),
6003 resolving_tx: entry.transaction,
6004 payment_preimage: preimage,
6005 });
6006 },
6007 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
6008 self.funding_spend_confirmed = Some(entry.txid);
6009 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
6010 if self.alternative_funding_confirmed.is_none() {
6011 for funding in &self.pending_funding {
6014 self.outputs_to_watch.remove(&funding.funding_txid());
6015 }
6016 let mut discarded_funding = Vec::new();
6017 mem::swap(&mut self.pending_funding, &mut discarded_funding);
6018 self.queue_discard_funding_event(discarded_funding.into_iter());
6019 }
6020 },
6021 OnchainEvent::AlternativeFundingConfirmation {} => {
6022 debug_assert!(self.no_further_updates_allowed());
6025 debug_assert_ne!(self.funding.funding_txid(), entry.txid);
6026 if let Err(_) = self.promote_funding(entry.txid) {
6027 debug_assert!(false);
6028 log_error!(logger, "Missing scope for alternative funding confirmation with txid {}", entry.txid);
6029 }
6030 },
6031 }
6032 }
6033
6034 if self.no_further_updates_allowed() {
6035 let current_counterparty_htlcs = if let Some(txid) = self.funding.current_counterparty_commitment_txid {
6042 if let Some(htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&txid) {
6043 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
6044 } else { None }
6045 } else { None }.into_iter().flatten();
6046
6047 let prev_counterparty_htlcs = if let Some(txid) = self.funding.prev_counterparty_commitment_txid {
6048 if let Some(htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&txid) {
6049 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
6050 } else { None }
6051 } else { None }.into_iter().flatten();
6052
6053 let htlcs = holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES)
6054 .chain(current_counterparty_htlcs)
6055 .chain(prev_counterparty_htlcs);
6056
6057 let height = self.best_block.height;
6058 for (htlc, source_opt) in htlcs {
6059 let source = match source_opt {
6061 Some(source) => source,
6062 None => continue,
6063 };
6064 let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
6065 Some(cltv_expiry) => cltv_expiry,
6066 None => continue,
6067 };
6068 let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
6069 if inbound_htlc_expiry > max_expiry_height {
6070 continue;
6071 }
6072 let duplicate_event = self.pending_monitor_events.iter().any(
6073 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
6074 upd.source == *source
6075 } else { false });
6076 if duplicate_event {
6077 continue;
6078 }
6079 if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
6080 continue;
6081 }
6082 if !duplicate_event {
6083 log_error!(logger, "Failing back HTLC {} upstream to preserve the \
6084 channel as the forward HTLC hasn't resolved and our backward HTLC \
6085 expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
6086 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
6087 source: source.clone(),
6088 payment_preimage: None,
6089 payment_hash: htlc.payment_hash,
6090 htlc_value_satoshis: htlc.amount_msat / 1000,
6091 }));
6092 }
6093 }
6094 }
6095
6096 let conf_target = self.closure_conf_target();
6097 self.onchain_tx_handler.update_claims_view_from_requests(
6098 claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target,
6099 &self.destination_script, fee_estimator, logger,
6100 );
6101 self.onchain_tx_handler.update_claims_view_from_matched_txn(
6102 &txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, conf_target,
6103 &self.destination_script, fee_estimator, logger,
6104 );
6105
6106 watch_outputs.retain(|&(ref txid, ref txouts)| {
6109 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
6110 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
6111 });
6112 #[cfg(test)]
6113 {
6114 for tx in &txn_matched {
6118 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
6119 for idx_and_script in outputs.iter() {
6120 assert!((idx_and_script.0 as usize) < tx.output.len());
6121 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
6122 }
6123 }
6124 }
6125 }
6126 watch_outputs
6127 }
6128
6129 #[rustfmt::skip]
6130 fn blocks_disconnected<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
6131 &mut self, fork_point: BlockLocator, broadcaster: B, fee_estimator: F, logger: &WithContext<L>
6132 ) {
6133 let new_height = fork_point.height;
6134 log_trace!(logger, "Block(s) disconnected to height {}", new_height);
6135 assert!(self.best_block.height > fork_point.height,
6136 "Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height");
6137
6138 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= new_height);
6142
6143 if let Some((conf_height, _)) = self.funding_tx_confirmed_in.as_ref() {
6145 if *conf_height > new_height {
6146 self.funding_tx_confirmed_in.take();
6147 }
6148 }
6149
6150 let mut should_broadcast_commitment = false;
6152 if let Some((_, conf_height, _)) = self.alternative_funding_confirmed.as_ref() {
6153 if *conf_height > new_height {
6154 self.alternative_funding_confirmed.take();
6155 if self.holder_tx_signed || self.funding_spend_seen {
6156 let new_holder_commitment_txid =
6159 self.funding.current_holder_commitment_tx.trust().txid();
6160 self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
6161
6162 should_broadcast_commitment = true;
6163 }
6164 }
6165 }
6166
6167 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
6168 let conf_target = self.closure_conf_target();
6169 self.onchain_tx_handler.blocks_disconnected(
6170 new_height, &broadcaster, conf_target, &self.destination_script, &bounded_fee_estimator, logger
6171 );
6172
6173 if should_broadcast_commitment {
6176 self.queue_latest_holder_commitment_txn_for_broadcast(&broadcaster, &bounded_fee_estimator, logger, true);
6177 }
6178
6179 self.best_block = fork_point;
6180 }
6181
6182 #[rustfmt::skip]
6183 fn transaction_unconfirmed<B: BroadcasterInterface, F: FeeEstimator, L: Logger>(
6184 &mut self,
6185 txid: &Txid,
6186 broadcaster: B,
6187 fee_estimator: &LowerBoundedFeeEstimator<F>,
6188 logger: &WithContext<L>,
6189 ) {
6190 let mut removed_height = None;
6191 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
6192 if entry.txid == *txid {
6193 removed_height = Some(entry.height);
6194 break;
6195 }
6196 }
6197
6198 if let Some(removed_height) = removed_height {
6199 log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
6200 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
6201 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
6202 false
6203 } else { true });
6204 }
6205
6206 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
6207
6208 if self.funding_tx_confirmed_in.is_some() && self.funding.funding_txid() == *txid {
6209 log_info!(logger, "Funding transaction {} was unconfirmed", txid);
6210 self.funding_tx_confirmed_in.take();
6211 }
6212
6213 let mut should_broadcast_commitment = false;
6215 if let Some((alternative_funding_txid, _, _)) = self.alternative_funding_confirmed.as_ref() {
6216 if alternative_funding_txid == txid {
6217 self.alternative_funding_confirmed.take();
6218 if self.holder_tx_signed || self.funding_spend_seen {
6219 let new_holder_commitment_txid =
6222 self.funding.current_holder_commitment_tx.trust().txid();
6223 self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
6224
6225 should_broadcast_commitment = true;
6226 }
6227 }
6228 }
6229
6230 let conf_target = self.closure_conf_target();
6231 self.onchain_tx_handler.transaction_unconfirmed(
6232 txid, &broadcaster, conf_target, &self.destination_script, fee_estimator, logger
6233 );
6234
6235 if should_broadcast_commitment {
6238 self.queue_latest_holder_commitment_txn_for_broadcast(&broadcaster, fee_estimator, logger, true);
6239 }
6240 }
6241
6242 #[rustfmt::skip]
6245 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
6246 let mut matched_txn = new_hash_set();
6247 let funding_outputs: Vec<_> = self
6248 .pending_funding
6249 .iter()
6250 .chain(Some(&self.funding))
6251 .map(|f| (
6252 f.funding_outpoint().index,
6253 f.channel_parameters.make_funding_redeemscript().to_p2wsh(),
6254 ))
6255 .collect();
6256 txdata.iter().filter(|&&(_, tx)| {
6257 let mut matches = self.spends_watched_output(tx);
6258 for input in tx.input.iter() {
6259 if matches { break; }
6260 if matched_txn.contains(&input.previous_output.txid) {
6261 matches = true;
6262 }
6263 }
6264 for (output_idx, spk) in funding_outputs.iter() {
6265 if matches { break; }
6266 if let Some(output) = tx.output.get(*output_idx as usize) {
6267 if *spk == output.script_pubkey {
6268 matches = true;
6269 }
6270 }
6271 }
6272 if matches {
6273 matched_txn.insert(tx.compute_txid());
6274 }
6275 matches
6276 }).map(|(_, tx)| *tx).collect()
6277 }
6278
6279 #[rustfmt::skip]
6281 fn spends_watched_output(&self, tx: &Transaction) -> bool {
6282 for input in tx.input.iter() {
6283 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
6284 for (idx, _script_pubkey) in outputs.iter() {
6285 if *idx == input.previous_output.vout {
6286 #[cfg(test)]
6287 {
6288 if _script_pubkey.is_p2wsh() {
6292 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
6293 return true;
6297 }
6298
6299 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
6300 } else if _script_pubkey.is_p2wpkh() {
6301 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
6302 } else if _script_pubkey == &chan_utils::shared_anchor_script_pubkey() {
6303 assert!(input.witness.is_empty());
6304 } else { panic!(); }
6305 }
6306 return true;
6307 }
6308 }
6309 }
6310 }
6311
6312 false
6313 }
6314
6315 #[rustfmt::skip]
6316 fn should_broadcast_holder_commitment_txn<L: Logger>(
6317 &self, logger: &WithContext<L>
6318 ) -> Option<PaymentHash> {
6319 if self.funding_spend_confirmed.is_some() ||
6322 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
6323 OnchainEvent::FundingSpendConfirmation { .. } => true,
6324 _ => false,
6325 }).is_some()
6326 {
6327 return None;
6328 }
6329 let height = self.best_block.height;
6340 macro_rules! scan_commitment {
6341 ($htlcs: expr, $holder_tx: expr) => {
6342 for ref htlc in $htlcs {
6343 let htlc_outbound = $holder_tx == htlc.offered;
6355 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
6356 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
6357 log_info!(logger, "Force-closing channel due to {} HTLC timeout - HTLC with payment hash {} expires at {}", if htlc_outbound { "outbound" } else { "inbound"}, htlc.payment_hash, htlc.cltv_expiry);
6358 return Some(htlc.payment_hash);
6359 }
6360 }
6361 }
6362 }
6363
6364 scan_commitment!(holder_commitment_htlcs!(self, CURRENT), true);
6365
6366 if let Some(ref txid) = self.funding.current_counterparty_commitment_txid {
6367 if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(txid) {
6368 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
6369 }
6370 }
6371 if let Some(ref txid) = self.funding.prev_counterparty_commitment_txid {
6372 if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(txid) {
6373 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
6374 }
6375 }
6376
6377 None
6378 }
6379
6380 #[rustfmt::skip]
6383 fn is_resolving_htlc_output<L: Logger>(
6384 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithContext<L>,
6385 ) {
6386 let funding_spent = get_confirmed_funding_scope!(self);
6387
6388 'outer_loop: for input in &tx.input {
6389 let mut payment_data = None;
6390 let htlc_claim = HTLCClaim::from_witness(&input.witness);
6391 let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
6392 let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
6393 #[cfg(not(fuzzing))]
6394 let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
6395 let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
6396 #[cfg(not(fuzzing))]
6397 let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
6398
6399 let mut payment_preimage = PaymentPreimage([0; 32]);
6400 if offered_preimage_claim || accepted_preimage_claim {
6401 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
6402 }
6403
6404 macro_rules! log_claim {
6405 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
6406 let outbound_htlc = $holder_tx == $htlc.offered;
6407 if ($holder_tx && revocation_sig_claim) ||
6408 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
6409 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
6410 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
6411 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
6412 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" });
6413 } else {
6414 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
6415 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
6416 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
6417 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
6418 }
6419 #[cfg(not(fuzzing))] assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim, "offered {htlc_claim:?}");
6423 #[cfg(not(fuzzing))] assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim, "!offered {htlc_claim:?}");
6425 #[cfg(not(fuzzing))] assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
6429 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
6430 revocation_sig_claim as u8, 1);
6431 }
6432 }
6433
6434 macro_rules! check_htlc_valid_counterparty {
6435 ($htlc_output: expr, $per_commitment_data: expr) => {
6436 for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
6437 if pending_htlc.offered == $htlc_output.offered && pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
6438 if let &Some(ref source) = pending_source {
6439 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
6440 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
6441 break;
6442 }
6443 }
6444 }
6445 }
6446 }
6447
6448 macro_rules! scan_commitment {
6449 ($funding_spent: expr, $htlcs: expr, $tx_info: expr, $holder_tx: expr, $spent_counterparty_revoked: expr) => {
6450 for (ref htlc_output, source_option) in $htlcs {
6451 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
6452 if let Some(ref source) = source_option {
6453 log_claim!($tx_info, $holder_tx, htlc_output, true);
6454 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
6460 } else if $spent_counterparty_revoked {
6461 if let Some(current_counterparty_commitment_txid) = &$funding_spent.current_counterparty_commitment_txid {
6462 check_htlc_valid_counterparty!(htlc_output, $funding_spent.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
6463 }
6464 if payment_data.is_none() {
6465 if let Some(prev_counterparty_commitment_txid) = &$funding_spent.prev_counterparty_commitment_txid {
6466 check_htlc_valid_counterparty!(htlc_output, $funding_spent.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
6467 }
6468 }
6469 }
6470 if payment_data.is_none() {
6471 log_claim!($tx_info, $holder_tx, htlc_output, false);
6472 let outbound_htlc = $holder_tx == htlc_output.offered;
6473 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6474 txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
6475 event: OnchainEvent::HTLCSpendConfirmation {
6476 commitment_tx_output_idx: input.previous_output.vout,
6477 preimage: if accepted_preimage_claim || offered_preimage_claim {
6478 Some(payment_preimage) } else { None },
6479 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
6484 Some(self.on_holder_tx_csv) } else { None },
6485 },
6486 });
6487 continue 'outer_loop;
6488 }
6489 }
6490 }
6491 }
6492 }
6493
6494 if input.previous_output.txid == funding_spent.current_holder_commitment_tx.trust().txid() {
6495 scan_commitment!(
6496 funding_spent, holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES),
6497 "our latest holder commitment tx", true, false
6498 );
6499 }
6500 if let Some(prev_holder_commitment_tx) = funding_spent.prev_holder_commitment_tx.as_ref() {
6501 if input.previous_output.txid == prev_holder_commitment_tx.trust().txid() {
6502 scan_commitment!(
6503 funding_spent, holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(),
6504 "our previous holder commitment tx", true, false
6505 );
6506 }
6507 }
6508 if let Some(ref htlc_outputs) = funding_spent.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
6509 let mut spent_counterparty_revoked = true;
6510 if funding_spent.current_counterparty_commitment_txid == Some(input.previous_output.txid) {
6511 spent_counterparty_revoked = false;
6512 }
6513 if funding_spent.prev_counterparty_commitment_txid == Some(input.previous_output.txid) {
6514 spent_counterparty_revoked = false;
6515 }
6516 let htlcs = htlc_outputs.iter()
6517 .map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed)));
6518 scan_commitment!(funding_spent, htlcs, "counterparty commitment tx", false, spent_counterparty_revoked);
6519 }
6520
6521 if let Some((source, payment_hash, amount_msat)) = payment_data {
6524 if accepted_preimage_claim || offered_preimage_claim {
6525 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6529 txid: tx.compute_txid(),
6530 height,
6531 block_hash: Some(*block_hash),
6532 transaction: Some(tx.clone()),
6533 event: OnchainEvent::HTLCSpendConfirmation {
6534 commitment_tx_output_idx: input.previous_output.vout,
6535 preimage: Some(payment_preimage),
6536 on_to_local_output_csv: None,
6537 },
6538 });
6539 self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
6540 if !self.pending_monitor_events.iter().any(
6541 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
6542 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
6543 source,
6544 payment_preimage: Some(payment_preimage),
6545 payment_hash,
6546 htlc_value_satoshis: amount_msat / 1000,
6547 }));
6548 }
6549 } else {
6550 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
6551 if entry.height != height { return true; }
6552 match entry.event {
6553 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
6554 *htlc_source != source
6555 },
6556 _ => true,
6557 }
6558 });
6559 let entry = OnchainEventEntry {
6560 txid: tx.compute_txid(),
6561 transaction: Some(tx.clone()),
6562 height,
6563 block_hash: Some(*block_hash),
6564 event: OnchainEvent::HTLCUpdate {
6565 source,
6566 payment_hash,
6567 htlc_value_satoshis: amount_msat / 1000,
6568 commitment_tx_output_idx: Some(input.previous_output.vout),
6569 },
6570 };
6571 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
6572 self.onchain_events_awaiting_threshold_conf.push(entry);
6573 }
6574 }
6575 }
6576 }
6577
6578 #[rustfmt::skip]
6579 fn get_spendable_outputs(&self, funding_spent: &FundingScope, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
6580 let mut spendable_outputs = Vec::new();
6581 for (i, outp) in tx.output.iter().enumerate() {
6582 if outp.script_pubkey == self.destination_script {
6583 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
6584 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6585 output: outp.clone(),
6586 channel_keys_id: Some(self.channel_keys_id),
6587 });
6588 }
6589 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
6590 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
6591 spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
6592 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6593 per_commitment_point: broadcasted_holder_revokable_script.1,
6594 to_self_delay: self.on_holder_tx_csv,
6595 output: outp.clone(),
6596 revocation_pubkey: broadcasted_holder_revokable_script.2,
6597 channel_keys_id: self.channel_keys_id,
6598 channel_value_satoshis: funding_spent.channel_parameters.channel_value_satoshis,
6599 channel_transaction_parameters: Some(funding_spent.channel_parameters.clone()),
6600 }));
6601 }
6602 }
6603 if self.counterparty_payment_script == outp.script_pubkey {
6604 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
6605 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6606 output: outp.clone(),
6607 channel_keys_id: self.channel_keys_id,
6608 channel_value_satoshis: funding_spent.channel_parameters.channel_value_satoshis,
6609 channel_transaction_parameters: Some(funding_spent.channel_parameters.clone()),
6610 }));
6611 }
6612 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
6613 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
6614 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6615 output: outp.clone(),
6616 channel_keys_id: Some(self.channel_keys_id),
6617 });
6618 }
6619 }
6620 spendable_outputs
6621 }
6622
6623 #[rustfmt::skip]
6626 fn check_tx_and_push_spendable_outputs<L: Logger>(
6627 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithContext<L>,
6628 ) {
6629 let funding_spent = get_confirmed_funding_scope!(self);
6630 for spendable_output in self.get_spendable_outputs(funding_spent, tx) {
6631 let entry = OnchainEventEntry {
6632 txid: tx.compute_txid(),
6633 transaction: Some(tx.clone()),
6634 height,
6635 block_hash: Some(*block_hash),
6636 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
6637 };
6638 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
6639 self.onchain_events_awaiting_threshold_conf.push(entry);
6640 }
6641 }
6642
6643 fn channel_type_features(&self) -> &ChannelTypeFeatures {
6644 &self.funding.channel_parameters.channel_type_features
6645 }
6646}
6647
6648impl<Signer: EcdsaChannelSigner, T: BroadcasterInterface, F: FeeEstimator, L: Logger> chain::Listen
6649 for (ChannelMonitor<Signer>, T, F, L)
6650{
6651 fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
6652 self.0.block_connected(header, txdata, height, &self.1, &self.2, &self.3);
6653 }
6654
6655 fn blocks_disconnected(&self, fork_point: BlockLocator) {
6656 self.0.blocks_disconnected(fork_point, &self.1, &self.2, &self.3);
6657 }
6658}
6659
6660impl<Signer: EcdsaChannelSigner, M, T: BroadcasterInterface, F: FeeEstimator, L: Logger>
6661 chain::Confirm for (M, T, F, L)
6662where
6663 M: Deref<Target = ChannelMonitor<Signer>>,
6664{
6665 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
6666 self.0.transactions_confirmed(header, txdata, height, &self.1, &self.2, &self.3);
6667 }
6668
6669 fn transaction_unconfirmed(&self, txid: &Txid) {
6670 self.0.transaction_unconfirmed(txid, &self.1, &self.2, &self.3);
6671 }
6672
6673 fn best_block_updated(&self, header: &Header, height: u32) {
6674 self.0.best_block_updated(header, height, &self.1, &self.2, &self.3);
6675 }
6676
6677 fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
6678 self.0.get_relevant_txids()
6679 }
6680}
6681
6682const MAX_ALLOC_SIZE: usize = 64 * 1024;
6683
6684impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
6685 for (BlockLocator, ChannelMonitor<SP::EcdsaSigner>)
6686{
6687 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
6688 match <Option<Self>>::read(reader, args) {
6689 Ok(Some(res)) => Ok(res),
6690 Ok(None) => Err(DecodeError::UnknownRequiredFeature),
6691 Err(e) => Err(e),
6692 }
6693 }
6694}
6695
6696impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
6697 for Option<(BlockLocator, ChannelMonitor<SP::EcdsaSigner>)>
6698{
6699 #[rustfmt::skip]
6700 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
6701 macro_rules! unwrap_obj {
6702 ($key: expr) => {
6703 match $key {
6704 Ok(res) => res,
6705 Err(_) => return Err(DecodeError::InvalidValue),
6706 }
6707 }
6708 }
6709
6710 let (entropy_source, signer_provider) = args;
6711
6712 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
6713
6714 let latest_update_id: u64 = Readable::read(reader)?;
6715 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
6716
6717 let destination_script = Readable::read(reader)?;
6718 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
6719 0 => {
6720 let revokable_address = Readable::read(reader)?;
6721 let per_commitment_point = Readable::read(reader)?;
6722 let revokable_script = Readable::read(reader)?;
6723 Some((revokable_address, per_commitment_point, revokable_script))
6724 },
6725 1 => { None },
6726 _ => return Err(DecodeError::InvalidValue),
6727 };
6728 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
6729 let shutdown_script = {
6730 let script = <ScriptBuf as Readable>::read(reader)?;
6731 if script.is_empty() { None } else { Some(script) }
6732 };
6733
6734 let channel_keys_id = Readable::read(reader)?;
6735 let holder_revocation_basepoint = Readable::read(reader)?;
6736 let outpoint = OutPoint {
6739 txid: Readable::read(reader)?,
6740 index: Readable::read(reader)?,
6741 };
6742 let _funding_script: ScriptBuf = Readable::read(reader)?;
6743 let current_counterparty_commitment_txid = Readable::read(reader)?;
6744 let prev_counterparty_commitment_txid = Readable::read(reader)?;
6745
6746 let counterparty_commitment_params = Readable::read(reader)?;
6747 let _funding_redeemscript: ScriptBuf = Readable::read(reader)?;
6748 let channel_value_satoshis = Readable::read(reader)?;
6749
6750 let their_cur_per_commitment_points = {
6751 let first_idx = <U48 as Readable>::read(reader)?.0;
6752 if first_idx == 0 {
6753 None
6754 } else {
6755 let first_point = Readable::read(reader)?;
6756 let second_point_slice: [u8; 33] = Readable::read(reader)?;
6757 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
6758 Some((first_idx, first_point, None))
6759 } else {
6760 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
6761 }
6762 }
6763 };
6764
6765 let on_holder_tx_csv: u16 = Readable::read(reader)?;
6766
6767 let commitment_secrets = Readable::read(reader)?;
6768
6769 macro_rules! read_htlc_in_commitment {
6770 () => {
6771 {
6772 let offered: bool = Readable::read(reader)?;
6773 let amount_msat: u64 = Readable::read(reader)?;
6774 let cltv_expiry: u32 = Readable::read(reader)?;
6775 let payment_hash: PaymentHash = Readable::read(reader)?;
6776 let transaction_output_index: Option<u32> = Readable::read(reader)?;
6777
6778 HTLCOutputInCommitment {
6779 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
6780 }
6781 }
6782 }
6783 }
6784
6785 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
6786 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
6787 for _ in 0..counterparty_claimable_outpoints_len {
6788 let txid: Txid = Readable::read(reader)?;
6789 let htlcs_count: u64 = Readable::read(reader)?;
6790 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
6791 for _ in 0..htlcs_count {
6792 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
6793 }
6794 if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
6795 return Err(DecodeError::InvalidValue);
6796 }
6797 }
6798
6799 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
6800 let mut counterparty_commitment_txn_on_chain = hash_map_with_capacity(cmp::min(counterparty_commitment_txn_on_chain_len as usize, MAX_ALLOC_SIZE / 32));
6801 for _ in 0..counterparty_commitment_txn_on_chain_len {
6802 let txid: Txid = Readable::read(reader)?;
6803 let commitment_number = <U48 as Readable>::read(reader)?.0;
6804 if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
6805 return Err(DecodeError::InvalidValue);
6806 }
6807 }
6808
6809 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
6810 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
6811 for _ in 0..counterparty_hash_commitment_number_len {
6812 let payment_hash: PaymentHash = Readable::read(reader)?;
6813 let commitment_number = <U48 as Readable>::read(reader)?.0;
6814 if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
6815 return Err(DecodeError::InvalidValue);
6816 }
6817 }
6818
6819 let prev_holder_signed_tx: Option<HolderSignedTx> =
6820 match <u8 as Readable>::read(reader)? {
6821 0 => None,
6822 1 => Some(Readable::read(reader)?),
6823 _ => return Err(DecodeError::InvalidValue),
6824 };
6825 let current_holder_signed_tx: HolderSignedTx = Readable::read(reader)?;
6826
6827 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
6828 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
6829
6830 let payment_preimages_len: u64 = Readable::read(reader)?;
6831 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
6832 for _ in 0..payment_preimages_len {
6833 let preimage: PaymentPreimage = Readable::read(reader)?;
6834 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
6835 if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
6836 return Err(DecodeError::InvalidValue);
6837 }
6838 }
6839
6840 let pending_monitor_events_len: u64 = Readable::read(reader)?;
6841 let mut pending_monitor_events = Some(
6842 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
6843 for _ in 0..pending_monitor_events_len {
6844 let ev = match <u8 as Readable>::read(reader)? {
6845 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
6846 1 => MonitorEvent::HolderForceClosed(outpoint),
6847 _ => return Err(DecodeError::InvalidValue)
6848 };
6849 pending_monitor_events.as_mut().unwrap().push(ev);
6850 }
6851
6852 let pending_events_len: u64 = Readable::read(reader)?;
6853 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
6854 for _ in 0..pending_events_len {
6855 if let Some(event) = MaybeReadable::read(reader)? {
6856 pending_events.push(event);
6857 }
6858 }
6859
6860 let mut best_block = BlockLocator::new(Readable::read(reader)?, Readable::read(reader)?);
6861
6862 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
6863 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
6864 for _ in 0..waiting_threshold_conf_len {
6865 if let Some(val) = MaybeReadable::read(reader)? {
6866 onchain_events_awaiting_threshold_conf.push(val);
6867 }
6868 }
6869
6870 let outputs_to_watch_len: u64 = Readable::read(reader)?;
6871 let mut outputs_to_watch = hash_map_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<ScriptBuf>>())));
6872 for _ in 0..outputs_to_watch_len {
6873 let txid = Readable::read(reader)?;
6874 let outputs_len: u64 = Readable::read(reader)?;
6875 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
6876 for _ in 0..outputs_len {
6877 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
6878 }
6879 if outputs_to_watch.insert(txid, outputs).is_some() {
6880 return Err(DecodeError::InvalidValue);
6881 }
6882 }
6883 let mut onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
6884 reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
6885 )?;
6886
6887 let lockdown_from_offchain = Readable::read(reader)?;
6888 let holder_tx_signed = Readable::read(reader)?;
6889
6890 let mut funding_spend_confirmed = None;
6891 let mut htlcs_resolved_on_chain = Some(Vec::new());
6892 let mut htlcs_resolved_to_user = Some(new_hash_set());
6893 let mut funding_spend_seen = Some(false);
6894 let mut counterparty_node_id = None;
6895 let mut confirmed_commitment_tx_counterparty_output = None;
6896 let mut spendable_txids_confirmed = Some(Vec::new());
6897 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
6898 let mut initial_counterparty_commitment_info = None;
6899 let mut initial_counterparty_commitment_tx = None;
6900 let mut balances_empty_height = None;
6901 let mut channel_id = None;
6902 let mut holder_pays_commitment_tx_fee = None;
6903 let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
6904 let mut first_negotiated_funding_txo = RequiredWrapper(None);
6905 let mut channel_parameters = None;
6906 let mut pending_funding = None;
6907 let mut legacy_alternative_funding_confirmed: Option<(Txid, u32)> = None;
6908 let mut is_manual_broadcast = RequiredWrapper(None);
6909 let mut funding_seen_onchain = RequiredWrapper(None);
6910 let mut best_block_previous_blocks = None;
6911 let mut current_funding_contribution = None;
6912 let mut funding_tx_confirmed_in = None;
6913 let mut alternative_funding_confirmed_block = None;
6914 read_tlv_fields!(reader, {
6915 (1, funding_spend_confirmed, option),
6916 (3, htlcs_resolved_on_chain, optional_vec),
6917 (5, pending_monitor_events, optional_vec),
6918 (7, funding_spend_seen, option),
6919 (9, counterparty_node_id, option),
6920 (11, confirmed_commitment_tx_counterparty_output, option),
6921 (13, spendable_txids_confirmed, optional_vec),
6922 (15, counterparty_fulfilled_htlcs, option),
6923 (17, initial_counterparty_commitment_info, option),
6924 (19, channel_id, option),
6925 (21, balances_empty_height, option),
6926 (23, holder_pays_commitment_tx_fee, option),
6927 (25, payment_preimages_with_info, option),
6928 (27, first_negotiated_funding_txo, (default_value, outpoint)),
6929 (29, initial_counterparty_commitment_tx, option),
6930 (31, channel_parameters, (option: ReadableArgs, None)),
6931 (32, pending_funding, optional_vec),
6932 (33, htlcs_resolved_to_user, option),
6933 (34, legacy_alternative_funding_confirmed, option),
6934 (35, is_manual_broadcast, (default_value, false)),
6935 (37, funding_seen_onchain, (default_value, true)),
6936 (39, best_block_previous_blocks, option), (41, current_funding_contribution, option),
6938 (43, funding_tx_confirmed_in, option),
6939 (45, alternative_funding_confirmed_block, option),
6940 });
6941 if let Some(previous_blocks) = best_block_previous_blocks {
6942 best_block.previous_blocks = previous_blocks;
6943 }
6944
6945 if alternative_funding_confirmed_block.is_some()
6946 && legacy_alternative_funding_confirmed.is_none()
6947 {
6948 return Err(DecodeError::InvalidValue);
6949 }
6950 let alternative_funding_confirmed = legacy_alternative_funding_confirmed
6951 .map(|(txid, height)| (txid, height, alternative_funding_confirmed_block));
6952
6953 let written_by_0_1_or_later = payment_preimages_with_info.is_some();
6956 if let Some(payment_preimages_with_info) = payment_preimages_with_info {
6957 if payment_preimages_with_info.len() != payment_preimages.len() {
6958 return Err(DecodeError::InvalidValue);
6959 }
6960 for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
6961 let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
6966 if new_preimage != Some(payment_preimage) {
6967 return Err(DecodeError::InvalidValue);
6968 }
6969 }
6970 payment_preimages = payment_preimages_with_info;
6971 }
6972
6973 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
6976 if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
6977 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
6978 {
6979 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
6980 }
6981 }
6982
6983 let channel_parameters = channel_parameters.unwrap_or_else(|| {
6984 onchain_tx_handler.channel_parameters().clone()
6985 });
6986
6987 if channel_parameters.channel_type_features.supports_anchors_zero_fee_htlc_tx() &&
6991 counterparty_payment_script.is_p2wpkh()
6992 {
6993 let payment_point = channel_parameters.holder_pubkeys.payment_point;
6994 counterparty_payment_script =
6995 chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point).to_p2wsh();
6996 }
6997
6998 let channel_id = channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint));
6999 onchain_tx_handler.set_channel_id(channel_id);
7000
7001 let (current_holder_commitment_tx, current_holder_htlc_data) = {
7002 let holder_commitment_tx = onchain_tx_handler.current_holder_commitment_tx();
7003
7004 #[cfg(debug_assertions)]
7005 let holder_signed_tx_copy = current_holder_signed_tx.clone();
7006
7007 let holder_commitment_htlc_data = CommitmentHTLCData::try_from(current_holder_signed_tx)
7008 .map_err(|_| DecodeError::InvalidValue)?;
7009
7010 #[cfg(debug_assertions)] {
7011 let mut stream = crate::util::ser::VecWriter(Vec::new());
7012 write_legacy_holder_commitment_data(
7013 &mut stream, &holder_commitment_tx, &holder_commitment_htlc_data
7014 ).map_err(|_| DecodeError::InvalidValue)?;
7015 let mut cursor = crate::io::Cursor::new(stream.0);
7016 if holder_signed_tx_copy != <HolderSignedTx as Readable>::read(&mut cursor)? {
7017 return Err(DecodeError::InvalidValue);
7018 }
7019 }
7020
7021 (holder_commitment_tx.clone(), holder_commitment_htlc_data)
7022 };
7023
7024 let (prev_holder_commitment_tx, prev_holder_htlc_data) =
7025 if let Some(prev_holder_signed_tx) = prev_holder_signed_tx {
7026 let holder_commitment_tx = onchain_tx_handler.prev_holder_commitment_tx();
7027 if holder_commitment_tx.is_none() {
7028 return Err(DecodeError::InvalidValue);
7029 }
7030
7031 #[cfg(debug_assertions)]
7032 let holder_signed_tx_copy = prev_holder_signed_tx.clone();
7033
7034 let holder_commitment_htlc_data = CommitmentHTLCData::try_from(prev_holder_signed_tx)
7035 .map_err(|_| DecodeError::InvalidValue)?;
7036
7037 #[cfg(debug_assertions)] {
7038 let mut stream = crate::util::ser::VecWriter(Vec::new());
7039 write_legacy_holder_commitment_data(
7040 &mut stream, &holder_commitment_tx.unwrap(), &holder_commitment_htlc_data
7041 ).map_err(|_| DecodeError::InvalidValue)?;
7042 let mut cursor = crate::io::Cursor::new(stream.0);
7043 if holder_signed_tx_copy != <HolderSignedTx as Readable>::read(&mut cursor)? {
7044 return Err(DecodeError::InvalidValue);
7045 }
7046 }
7047
7048 (holder_commitment_tx.cloned(), Some(holder_commitment_htlc_data))
7049 } else {
7050 (None, None)
7051 };
7052
7053 let dummy_node_id = PublicKey::from_slice(&[2; 33]).unwrap();
7054 onchain_tx_handler
7055 .set_counterparty_node_id(counterparty_node_id.unwrap_or(dummy_node_id));
7056 let monitor = ChannelMonitor::from_impl(ChannelMonitorImpl {
7057 funding: FundingScope {
7058 channel_parameters,
7059
7060 current_counterparty_commitment_txid,
7061 prev_counterparty_commitment_txid,
7062 counterparty_claimable_outpoints,
7063
7064 current_holder_commitment_tx,
7065 prev_holder_commitment_tx,
7066 contribution: current_funding_contribution,
7067 },
7068 pending_funding: pending_funding.unwrap_or(vec![]),
7069 is_manual_broadcast: is_manual_broadcast.0.unwrap(),
7070 funding_seen_onchain: funding_seen_onchain.0.unwrap(),
7073
7074 latest_update_id,
7075 commitment_transaction_number_obscure_factor,
7076
7077 destination_script,
7078 broadcasted_holder_revokable_script,
7079 counterparty_payment_script,
7080 shutdown_script,
7081
7082 channel_keys_id,
7083 holder_revocation_basepoint,
7084 channel_id,
7085 first_negotiated_funding_txo: first_negotiated_funding_txo.0.unwrap(),
7086
7087 counterparty_commitment_params,
7088 their_cur_per_commitment_points,
7089
7090 on_holder_tx_csv,
7091
7092 commitment_secrets,
7093 counterparty_commitment_txn_on_chain,
7094 counterparty_hash_commitment_number,
7095 counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
7096
7097 current_counterparty_commitment_number,
7098 current_holder_commitment_number,
7099
7100 payment_preimages,
7101 pending_monitor_events: pending_monitor_events.unwrap(),
7102 pending_events,
7103 is_processing_pending_events: false,
7104
7105 onchain_events_awaiting_threshold_conf,
7106 outputs_to_watch,
7107
7108 onchain_tx_handler,
7109
7110 lockdown_from_offchain,
7111 holder_tx_signed,
7112 holder_pays_commitment_tx_fee,
7113 funding_spend_seen: funding_spend_seen.unwrap(),
7114 funding_spend_confirmed,
7115 confirmed_commitment_tx_counterparty_output,
7116 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
7117 htlcs_resolved_to_user: htlcs_resolved_to_user.unwrap(),
7118 spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
7119
7120 best_block,
7121 counterparty_node_id: counterparty_node_id.unwrap_or(dummy_node_id),
7122 initial_counterparty_commitment_info,
7123 initial_counterparty_commitment_tx,
7124 balances_empty_height,
7125 failed_back_htlc_ids: new_hash_set(),
7126
7127 current_holder_htlc_data,
7128 prev_holder_htlc_data,
7129
7130 funding_tx_confirmed_in,
7131 alternative_funding_confirmed,
7132
7133 written_by_0_1_or_later,
7134 });
7135
7136 if counterparty_node_id.is_none() {
7137 if (holder_tx_signed || lockdown_from_offchain) && monitor.get_claimable_balances().is_empty() {
7138 return Ok(None);
7141 } else {
7142 panic!("Found monitor for channel {channel_id} with no updates since v0.0.118. \
7143 These monitors are no longer supported. \
7144 To continue, run a v0.1 release, send/route a payment over the channel or close it.");
7145 }
7146 }
7147 Ok(Some((best_block, monitor)))
7148 }
7149}
7150
7151#[cfg(test)]
7152pub(super) fn dummy_monitor<S: EcdsaChannelSigner + 'static>(
7153 channel_id: ChannelId, wrap_signer: impl FnOnce(crate::sign::InMemorySigner) -> S,
7154) -> ChannelMonitor<S> {
7155 use crate::ln::chan_utils::{ChannelPublicKeys, CounterpartyChannelTransactionParameters};
7156 use crate::sign::{ChannelSigner, InMemorySigner};
7157 use bitcoin::network::Network;
7158
7159 let secp_ctx = Secp256k1::new();
7160 let dummy_key =
7161 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7162 let keys = InMemorySigner::new(
7163 SecretKey::from_slice(&[41; 32]).unwrap(),
7164 SecretKey::from_slice(&[41; 32]).unwrap(),
7165 SecretKey::from_slice(&[41; 32]).unwrap(),
7166 SecretKey::from_slice(&[41; 32]).unwrap(),
7167 true,
7168 SecretKey::from_slice(&[41; 32]).unwrap(),
7169 SecretKey::from_slice(&[41; 32]).unwrap(),
7170 [41; 32],
7171 [0; 32],
7172 [0; 32],
7173 );
7174 let counterparty_pubkeys = ChannelPublicKeys {
7175 funding_pubkey: dummy_key,
7176 revocation_basepoint: RevocationBasepoint::from(dummy_key),
7177 payment_point: dummy_key,
7178 delayed_payment_basepoint: DelayedPaymentBasepoint::from(dummy_key),
7179 htlc_basepoint: HtlcBasepoint::from(dummy_key),
7180 };
7181 let funding_outpoint =
7182 crate::chain::transaction::OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7183 let channel_parameters = ChannelTransactionParameters {
7184 holder_pubkeys: keys.pubkeys(&secp_ctx),
7185 holder_selected_contest_delay: 66,
7186 is_outbound_from_holder: true,
7187 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
7188 pubkeys: counterparty_pubkeys,
7189 selected_contest_delay: 67,
7190 }),
7191 funding_outpoint: Some(funding_outpoint),
7192 splice_parent_funding_txid: None,
7193 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
7194 channel_value_satoshis: 0,
7195 };
7196 let shutdown_script = crate::ln::script::ShutdownScript::new_p2wpkh_from_pubkey(dummy_key);
7197 let best_block = BlockLocator::from_network(Network::Testnet);
7198 let signer = wrap_signer(keys);
7199 ChannelMonitor::new(
7200 secp_ctx,
7201 signer,
7202 Some(shutdown_script.into_inner()),
7203 0,
7204 &ScriptBuf::new(),
7205 &channel_parameters,
7206 true,
7207 0,
7208 HolderCommitmentTransaction::dummy(0, funding_outpoint, Vec::new()),
7209 best_block,
7210 dummy_key,
7211 channel_id,
7212 false,
7213 )
7214}
7215
7216#[cfg(test)]
7217mod tests {
7218 use bitcoin::amount::Amount;
7219 use bitcoin::hash_types::Txid;
7220 use bitcoin::hashes::sha256::Hash as Sha256;
7221 use bitcoin::hashes::Hash;
7222 use bitcoin::hex::FromHex;
7223 use bitcoin::locktime::absolute::LockTime;
7224 use bitcoin::network::Network;
7225 use bitcoin::opcodes;
7226 use bitcoin::script::{Builder, ScriptBuf};
7227 use bitcoin::secp256k1::Secp256k1;
7228 use bitcoin::secp256k1::{PublicKey, SecretKey};
7229 use bitcoin::sighash;
7230 use bitcoin::sighash::EcdsaSighashType;
7231 use bitcoin::transaction::OutPoint as BitcoinOutPoint;
7232 use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
7233 use bitcoin::{Sequence, Witness};
7234
7235 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
7236 use crate::events::{ClosureReason, Event};
7237
7238 use super::ChannelMonitorUpdateStep;
7239 use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
7240 use crate::chain::package::{
7241 weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc,
7242 weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT,
7243 };
7244 use crate::chain::transaction::OutPoint;
7245 use crate::chain::{BlockLocator, Confirm};
7246 use crate::io;
7247 use crate::ln::chan_utils::{self, HTLCOutputInCommitment, HolderCommitmentTransaction};
7248 use crate::ln::channel_keys::{
7249 DelayedPaymentBasepoint, DelayedPaymentKey, RevocationBasepoint, RevocationKey,
7250 };
7251 use crate::ln::channelmanager::{HTLCSource, PaymentId};
7252 use crate::ln::functional_test_utils::*;
7253 use crate::ln::outbound_payment::RecipientOnionFields;
7254 use crate::ln::types::ChannelId;
7255 use crate::sync::Arc;
7256 use crate::types::features::ChannelTypeFeatures;
7257 use crate::types::payment::{PaymentHash, PaymentPreimage};
7258 use crate::util::logger::Logger;
7259 use crate::util::ser::{ReadableArgs, Writeable};
7260 use crate::util::test_utils::{TestBroadcaster, TestFeeEstimator, TestLogger};
7261 use crate::{check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash};
7262
7263 #[allow(unused_imports)]
7264 use crate::prelude::*;
7265
7266 use std::str::FromStr;
7267
7268 #[rustfmt::skip]
7269 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
7270 let chanmon_cfgs = create_chanmon_cfgs(3);
7282 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7283 let legacy_cfg = test_legacy_channel_config();
7284 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg.clone()), Some(legacy_cfg)]);
7285 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7286 nodes[1].disable_monitor_completeness_assertion();
7287 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
7288 create_announced_chan_between_nodes(&nodes, 1, 2);
7289
7290 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
7292
7293 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
7295 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
7296
7297 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
7298 assert_eq!(local_txn.len(), 1);
7299 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
7300 assert_eq!(remote_txn.len(), 3); check_spends!(remote_txn[1], remote_txn[0]);
7302 check_spends!(remote_txn[2], remote_txn[0]);
7303 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
7304
7305 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
7308 let conf_height = nodes[0].best_block_info().1 + 1;
7309 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
7310 &[(0, broadcast_tx)], conf_height);
7311
7312 let (_, pre_update_monitor) = <(BlockLocator, ChannelMonitor<_>)>::read(
7313 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
7314 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
7315
7316 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
7319 nodes[1].node.send_payment_with_route(route, payment_hash,
7320 RecipientOnionFields::secret_only(payment_secret, 100_000), PaymentId(payment_hash.0)
7321 ).unwrap();
7322 check_added_monitors(&nodes[1], 1);
7323
7324 let replay_update = {
7328 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
7329 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().next_back().unwrap().clone();
7330 assert_eq!(replay_update.updates.len(), 1);
7331 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
7332 } else { panic!(); }
7333 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
7334 payment_preimage: payment_preimage_1, payment_info: None,
7335 });
7336 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
7337 payment_preimage: payment_preimage_2, payment_info: None,
7338 });
7339 replay_update
7340 };
7341
7342 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
7343 assert!(
7344 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
7345 .is_err());
7346
7347 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7350 assert!(txn_broadcasted.len() >= 2);
7351 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
7352 assert_eq!(tx.input.len(), 1);
7353 tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
7354 }).collect::<Vec<_>>();
7355 assert_eq!(htlc_txn.len(), 2);
7356 check_spends!(htlc_txn[0], broadcast_tx);
7357 check_spends!(htlc_txn[1], broadcast_tx);
7358
7359 check_closed_broadcast(&nodes[1], 1, true);
7360 if !use_local_txn {
7361 let events = nodes[1].node.get_and_clear_pending_events();
7366 assert_eq!(events.len(), 3);
7367 assert!(events.iter().any(|e| matches!(e, Event::PaymentPathFailed { .. })));
7368 assert!(events.iter().any(|e| matches!(e, Event::PaymentFailed { .. })));
7369 assert!(events.iter().any(|e| matches!(e, Event::ChannelClosed { .. })));
7370 check_added_monitors(&nodes[1], 2);
7371 } else {
7372 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, &[nodes[0].node.get_our_node_id()], 100000);
7373 check_added_monitors(&nodes[1], 1);
7374 }
7375 }
7376
7377 #[test]
7378 fn test_funding_spend_refuses_updates() {
7379 do_test_funding_spend_refuses_updates(true);
7380 do_test_funding_spend_refuses_updates(false);
7381 }
7382
7383 #[test]
7384 #[rustfmt::skip]
7385 fn test_prune_preimages() {
7386 let secp_ctx = Secp256k1::new();
7387 let logger = Arc::new(TestLogger::new());
7388 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
7389 let fee_estimator = TestFeeEstimator::new(253);
7390
7391 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7392
7393 let mut preimages = Vec::new();
7394 {
7395 for i in 0..20 {
7396 let preimage = PaymentPreimage([i; 32]);
7397 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
7398 preimages.push((preimage, hash));
7399 }
7400 }
7401
7402 let dummy_source = HTLCSource::dummy();
7403
7404 macro_rules! preimages_slice_to_htlcs {
7405 ($preimages_slice: expr) => {
7406 {
7407 let mut res = Vec::new();
7408 for (idx, preimage) in $preimages_slice.iter().enumerate() {
7409 res.push(HTLCOutputInCommitment {
7410 offered: true,
7411 amount_msat: 0,
7412 cltv_expiry: 0,
7413 payment_hash: preimage.1.clone(),
7414 transaction_output_index: Some(idx as u32),
7415 });
7416 }
7417 res
7418 }
7419 }
7420 }
7421 macro_rules! preimages_slice_to_htlc_outputs {
7422 ($preimages_slice: expr) => {
7423 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|htlc| (htlc, None)).collect()
7424 }
7425 }
7426 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
7427 &bitcoin::secp256k1::Message::from_digest([42; 32]),
7428 &SecretKey::from_slice(&[42; 32]).unwrap());
7429
7430 macro_rules! test_preimages_exist {
7431 ($preimages_slice: expr, $monitor: expr) => {
7432 for preimage in $preimages_slice {
7433 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
7434 }
7435 }
7436 }
7437
7438 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7439 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
7440 let monitor = super::dummy_monitor(channel_id, |keys| keys);
7443
7444 let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
7445 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7446 let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7448
7449 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7450 &nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7451 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
7452 preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
7453 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
7454 preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
7455 for &(ref preimage, ref hash) in preimages.iter() {
7456 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
7457 monitor.provide_payment_preimage_unsafe_legacy(
7458 hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
7459 );
7460 }
7461
7462 let mut secret = [0; 32];
7464 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
7465 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
7466 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
7467 test_preimages_exist!(&preimages[0..10], monitor);
7468 test_preimages_exist!(&preimages[15..20], monitor);
7469
7470 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
7471 preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
7472
7473 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
7475 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
7476 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
7477 test_preimages_exist!(&preimages[0..10], monitor);
7478 test_preimages_exist!(&preimages[17..20], monitor);
7479
7480 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
7481 preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
7482
7483 let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
7486 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7487 let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7489 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7490 &nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7491 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
7492 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
7493 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
7494 test_preimages_exist!(&preimages[0..10], monitor);
7495 test_preimages_exist!(&preimages[18..20], monitor);
7496
7497 let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
7499 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7500 let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7502 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7503 &nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7504 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
7505 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
7506 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
7507 test_preimages_exist!(&preimages[0..5], monitor);
7508 }
7509
7510 #[test]
7511 #[rustfmt::skip]
7512 fn test_claim_txn_weight_computation() {
7513 let secp_ctx = Secp256k1::new();
7517 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
7518 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
7519
7520 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
7521 macro_rules! sign_input {
7522 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
7523 let htlc = HTLCOutputInCommitment {
7524 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
7525 amount_msat: 0,
7526 cltv_expiry: 2 << 16,
7527 payment_hash: PaymentHash([1; 32]),
7528 transaction_output_index: Some($idx as u32),
7529 };
7530 let redeem_script = if *$weight == WEIGHT_REVOKED_OUTPUT { chan_utils::get_revokeable_redeemscript(&RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey), 256, &DelayedPaymentKey::from_basepoint(&secp_ctx, &DelayedPaymentBasepoint::from(pubkey), &pubkey)) } else { chan_utils::get_htlc_redeemscript_with_explicit_keys(&htlc, $opt_anchors, &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &HtlcKey::from_basepoint(&secp_ctx, &HtlcBasepoint::from(pubkey), &pubkey), &RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(pubkey), &pubkey)) };
7531 let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
7532 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
7533 let mut ser_sig = sig.serialize_der().to_vec();
7534 ser_sig.push(EcdsaSighashType::All as u8);
7535 $sum_actual_sigs += ser_sig.len() as u64;
7536 let witness = $sighash_parts.witness_mut($idx).unwrap();
7537 witness.push(ser_sig);
7538 if *$weight == WEIGHT_REVOKED_OUTPUT {
7539 witness.push(vec!(1));
7540 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
7541 witness.push(pubkey.clone().serialize().to_vec());
7542 } else if *$weight == weight_received_htlc($opt_anchors) {
7543 witness.push(vec![0]);
7544 } else {
7545 witness.push(PaymentPreimage([1; 32]).0.to_vec());
7546 }
7547 witness.push(redeem_script.into_bytes());
7548 let witness = witness.to_vec();
7549 println!("witness[0] {}", witness[0].len());
7550 println!("witness[1] {}", witness[1].len());
7551 println!("witness[2] {}", witness[2].len());
7552 }
7553 }
7554
7555 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
7556 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
7557
7558 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7560 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7561 let mut sum_actual_sigs = 0;
7562 for i in 0..4 {
7563 claim_tx.input.push(TxIn {
7564 previous_output: BitcoinOutPoint {
7565 txid,
7566 vout: i,
7567 },
7568 script_sig: ScriptBuf::new(),
7569 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7570 witness: Witness::new(),
7571 });
7572 }
7573 claim_tx.output.push(TxOut {
7574 script_pubkey: script_pubkey.clone(),
7575 value: Amount::ZERO,
7576 });
7577 let base_weight = claim_tx.weight().to_wu();
7578 let inputs_weight = [WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(channel_type_features), weight_revoked_offered_htlc(channel_type_features), weight_revoked_received_htlc(channel_type_features)];
7579 let mut inputs_total_weight = 2; {
7581 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7582 for (idx, inp) in inputs_weight.iter().enumerate() {
7583 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7584 inputs_total_weight += inp;
7585 }
7586 }
7587 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7588 }
7589
7590 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7592 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7593 let mut sum_actual_sigs = 0;
7594 for i in 0..4 {
7595 claim_tx.input.push(TxIn {
7596 previous_output: BitcoinOutPoint {
7597 txid,
7598 vout: i,
7599 },
7600 script_sig: ScriptBuf::new(),
7601 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7602 witness: Witness::new(),
7603 });
7604 }
7605 claim_tx.output.push(TxOut {
7606 script_pubkey: script_pubkey.clone(),
7607 value: Amount::ZERO,
7608 });
7609 let base_weight = claim_tx.weight().to_wu();
7610 let inputs_weight = [weight_offered_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features)];
7611 let mut inputs_total_weight = 2; {
7613 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7614 for (idx, inp) in inputs_weight.iter().enumerate() {
7615 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7616 inputs_total_weight += inp;
7617 }
7618 }
7619 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7620 }
7621
7622 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7624 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7625 let mut sum_actual_sigs = 0;
7626 claim_tx.input.push(TxIn {
7627 previous_output: BitcoinOutPoint {
7628 txid,
7629 vout: 0,
7630 },
7631 script_sig: ScriptBuf::new(),
7632 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7633 witness: Witness::new(),
7634 });
7635 claim_tx.output.push(TxOut {
7636 script_pubkey: script_pubkey.clone(),
7637 value: Amount::ZERO,
7638 });
7639 let base_weight = claim_tx.weight().to_wu();
7640 let inputs_weight = [WEIGHT_REVOKED_OUTPUT];
7641 let mut inputs_total_weight = 2; {
7643 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7644 for (idx, inp) in inputs_weight.iter().enumerate() {
7645 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7646 inputs_total_weight += inp;
7647 }
7648 }
7649 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7650 }
7651 }
7652
7653 #[test]
7654 #[rustfmt::skip]
7655 fn test_with_channel_monitor_impl_logger() {
7656 let secp_ctx = Secp256k1::new();
7657 let logger = Arc::new(TestLogger::new());
7658
7659 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7660
7661 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7662 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
7663 let monitor = super::dummy_monitor(channel_id, |keys| keys);
7664
7665 let chan_id = monitor.inner.lock().unwrap().channel_id();
7666 let payment_hash = PaymentHash([1; 32]);
7667 let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
7668 log_error!(context_logger, "This is an error");
7669 log_warn!(context_logger, "This is an error");
7670 log_debug!(context_logger, "This is an error");
7671 log_trace!(context_logger, "This is an error");
7672 log_gossip!(context_logger, "This is an error");
7673 log_info!(context_logger, "This is an error");
7674 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
7675 }
7676 }