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::Filter;
46use crate::chain::{BestBlock, WatchedOutput};
47use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent};
48use crate::events::{ClosureReason, Event, EventHandler, PaidBolt12Invoice, ReplayEvent};
49use crate::ln::chan_utils::{
50 self, ChannelTransactionParameters, CommitmentTransaction, CounterpartyCommitmentSecrets,
51 HTLCClaim, HTLCOutputInCommitment, HolderCommitmentTransaction,
52};
53use crate::ln::channel::INITIAL_COMMITMENT_NUMBER;
54use crate::ln::channel_keys::{
55 DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, HtlcKey, RevocationBasepoint,
56 RevocationKey,
57};
58use crate::ln::channelmanager::{HTLCSource, PaymentClaimDetails, SentHTLCId};
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, Record};
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: Option<u64>,
258}
259impl_writeable_tlv_based!(HTLCUpdate, {
260 (0, payment_hash, required),
261 (1, htlc_value_satoshis, option),
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: &BestBlock) -> 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: Option<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, option),
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 },
685 ShutdownScript {
686 scriptpubkey: ScriptBuf,
687 },
688 RenegotiatedFunding {
689 channel_parameters: ChannelTransactionParameters,
690 holder_commitment_tx: HolderCommitmentTransaction,
691 counterparty_commitment_tx: CommitmentTransaction,
692 },
693 RenegotiatedFundingLocked {
694 funding_txid: Txid,
695 },
696 ReleasePaymentComplete {
708 htlc: SentHTLCId,
709 },
710}
711
712impl ChannelMonitorUpdateStep {
713 #[rustfmt::skip]
714 fn variant_name(&self) -> &'static str {
715 match self {
716 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
717 ChannelMonitorUpdateStep::LatestHolderCommitment { .. } => "LatestHolderCommitment",
718 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
719 ChannelMonitorUpdateStep::LatestCounterpartyCommitment { .. } => "LatestCounterpartyCommitment",
720 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
721 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
722 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
723 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
724 ChannelMonitorUpdateStep::RenegotiatedFunding { .. } => "RenegotiatedFunding",
725 ChannelMonitorUpdateStep::RenegotiatedFundingLocked { .. } => "RenegotiatedFundingLocked",
726 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => "ReleasePaymentComplete",
727 }
728 }
729}
730
731impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
732 (0, LatestHolderCommitmentTXInfo) => {
733 (0, commitment_tx, required),
734 (1, claimed_htlcs, optional_vec),
735 (2, htlc_outputs, required_vec),
736 (4, nondust_htlc_sources, optional_vec),
737 },
738 (1, LatestCounterpartyCommitmentTXInfo) => {
739 (0, commitment_txid, required),
740 (1, feerate_per_kw, option),
741 (2, commitment_number, required),
742 (3, to_broadcaster_value_sat, option),
743 (4, their_per_commitment_point, required),
744 (5, to_countersignatory_value_sat, option),
745 (6, htlc_outputs, required_vec),
746 },
747 (2, PaymentPreimage) => {
748 (0, payment_preimage, required),
749 (1, payment_info, option),
750 },
751 (3, CommitmentSecret) => {
752 (0, idx, required),
753 (2, secret, required),
754 },
755 (4, ChannelForceClosed) => {
756 (0, should_broadcast, required),
757 },
758 (5, ShutdownScript) => {
759 (0, scriptpubkey, required),
760 },
761 (6, LatestCounterpartyCommitment) => {
762 (1, commitment_txs, required_vec),
763 (3, htlc_data, required),
764 },
765 (7, ReleasePaymentComplete) => {
766 (1, htlc, required),
767 },
768 (8, LatestHolderCommitment) => {
769 (1, commitment_txs, required_vec),
770 (3, htlc_data, required),
771 (5, claimed_htlcs, required_vec),
772 },
773 (10, RenegotiatedFunding) => {
774 (1, channel_parameters, (required: ReadableArgs, None)),
775 (3, holder_commitment_tx, required),
776 (5, counterparty_commitment_tx, required),
777 },
778 (12, RenegotiatedFundingLocked) => {
779 (1, funding_txid, required),
780 },
781);
782
783#[derive(Clone, Debug, PartialEq, Eq)]
786#[cfg_attr(test, derive(PartialOrd, Ord))]
787pub enum BalanceSource {
788 HolderForceClosed,
790 CounterpartyForceClosed,
792 CoopClose,
794 Htlc,
796}
797
798#[derive(Clone, Debug, PartialEq, Eq)]
800#[cfg_attr(test, derive(PartialOrd, Ord))]
801pub struct HolderCommitmentTransactionBalance {
802 pub amount_satoshis: u64,
805 pub transaction_fee_satoshis: u64,
814}
815
816#[derive(Clone, Debug, PartialEq, Eq)]
821#[cfg_attr(test, derive(PartialOrd, Ord))]
822pub enum Balance {
823 ClaimableOnChannelClose {
826 balance_candidates: Vec<HolderCommitmentTransactionBalance>,
844 confirmed_balance_candidate_index: usize,
849 outbound_payment_htlc_rounded_msat: u64,
858 outbound_forwarded_htlc_rounded_msat: u64,
866 inbound_claiming_htlc_rounded_msat: u64,
876 inbound_htlc_rounded_msat: u64,
885 },
886 ClaimableAwaitingConfirmations {
889 amount_satoshis: u64,
892 confirmation_height: u32,
895 source: BalanceSource,
897 },
898 ContentiousClaimable {
906 amount_satoshis: u64,
909 timeout_height: u32,
912 payment_hash: PaymentHash,
914 payment_preimage: PaymentPreimage,
916 },
917 MaybeTimeoutClaimableHTLC {
921 amount_satoshis: u64,
924 claimable_height: u32,
927 payment_hash: PaymentHash,
929 outbound_payment: bool,
933 },
934 MaybePreimageClaimableHTLC {
938 amount_satoshis: u64,
941 expiry_height: u32,
944 payment_hash: PaymentHash,
946 },
947 CounterpartyRevokedOutputClaimable {
953 amount_satoshis: u64,
958 },
959}
960
961impl Balance {
962 #[rustfmt::skip]
982 pub fn claimable_amount_satoshis(&self) -> u64 {
983 match self {
984 Balance::ClaimableOnChannelClose {
985 balance_candidates, confirmed_balance_candidate_index, ..
986 } => {
987 if *confirmed_balance_candidate_index != 0 {
988 balance_candidates[*confirmed_balance_candidate_index].amount_satoshis
989 } else {
990 balance_candidates.last().map(|balance| balance.amount_satoshis).unwrap_or(0)
991 }
992 },
993 Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
994 Balance::ContentiousClaimable { amount_satoshis, .. }|
995 Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
996 => *amount_satoshis,
997 Balance::MaybeTimeoutClaimableHTLC { amount_satoshis, outbound_payment, .. }
998 => if *outbound_payment { 0 } else { *amount_satoshis },
999 Balance::MaybePreimageClaimableHTLC { .. } => 0,
1000 }
1001 }
1002}
1003
1004#[derive(Clone, PartialEq, Eq)]
1006struct IrrevocablyResolvedHTLC {
1007 commitment_tx_output_idx: Option<u32>,
1008 resolving_txid: Option<Txid>, resolving_tx: Option<Transaction>,
1013 payment_preimage: Option<PaymentPreimage>,
1015}
1016
1017impl Writeable for IrrevocablyResolvedHTLC {
1022 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1023 let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::MAX);
1024 write_tlv_fields!(writer, {
1025 (0, mapped_commitment_tx_output_idx, required),
1026 (1, self.resolving_txid, option),
1027 (2, self.payment_preimage, option),
1028 (3, self.resolving_tx, option),
1029 });
1030 Ok(())
1031 }
1032}
1033
1034impl Readable for IrrevocablyResolvedHTLC {
1035 #[rustfmt::skip]
1036 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1037 let mut mapped_commitment_tx_output_idx = 0;
1038 let mut resolving_txid = None;
1039 let mut payment_preimage = None;
1040 let mut resolving_tx = None;
1041 read_tlv_fields!(reader, {
1042 (0, mapped_commitment_tx_output_idx, required),
1043 (1, resolving_txid, option),
1044 (2, payment_preimage, option),
1045 (3, resolving_tx, option),
1046 });
1047 Ok(Self {
1048 commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::MAX { None } else { Some(mapped_commitment_tx_output_idx) },
1049 resolving_txid,
1050 payment_preimage,
1051 resolving_tx,
1052 })
1053 }
1054}
1055
1056pub struct ChannelMonitor<Signer: EcdsaChannelSigner> {
1078 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
1079}
1080
1081impl<Signer: EcdsaChannelSigner> Clone for ChannelMonitor<Signer>
1082where
1083 Signer: Clone,
1084{
1085 fn clone(&self) -> Self {
1086 let inner = self.inner.lock().unwrap().clone();
1087 ChannelMonitor::from_impl(inner)
1088 }
1089}
1090
1091#[derive(Clone, Debug, PartialEq, Eq)]
1092pub(crate) struct CommitmentHTLCData {
1093 pub nondust_htlc_sources: Vec<HTLCSource>,
1096 pub dust_htlcs: Vec<(HTLCOutputInCommitment, Option<HTLCSource>)>,
1097}
1098
1099impl CommitmentHTLCData {
1100 fn new() -> Self {
1101 Self { nondust_htlc_sources: Vec::new(), dust_htlcs: Vec::new() }
1102 }
1103}
1104
1105impl_writeable_tlv_based!(CommitmentHTLCData, {
1106 (1, nondust_htlc_sources, required_vec),
1107 (3, dust_htlcs, required_vec),
1108});
1109
1110impl TryFrom<HolderSignedTx> for CommitmentHTLCData {
1111 type Error = ();
1112 #[rustfmt::skip]
1113 fn try_from(value: HolderSignedTx) -> Result<Self, Self::Error> {
1114 let mut missing_nondust_source = false;
1118 let mut nondust_htlc_sources = Vec::with_capacity(value.htlc_outputs.len());
1119 let dust_htlcs = value.htlc_outputs.into_iter().filter_map(|(htlc, _, source)| {
1120 if htlc.transaction_output_index.is_none() {
1123 return Some((htlc, source))
1124 }
1125 if htlc.offered {
1126 if let Some(source) = source {
1127 nondust_htlc_sources.push(source);
1128 } else {
1129 missing_nondust_source = true;
1130 }
1131 }
1132 None
1133 }).collect();
1134 if missing_nondust_source {
1135 return Err(());
1136 }
1137
1138 Ok(Self {
1139 nondust_htlc_sources,
1140 dust_htlcs,
1141 })
1142 }
1143}
1144
1145#[derive(Clone, PartialEq)]
1146struct FundingScope {
1147 channel_parameters: ChannelTransactionParameters,
1148
1149 current_counterparty_commitment_txid: Option<Txid>,
1150 prev_counterparty_commitment_txid: Option<Txid>,
1151
1152 counterparty_claimable_outpoints:
1162 HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
1163
1164 current_holder_commitment_tx: HolderCommitmentTransaction,
1169 prev_holder_commitment_tx: Option<HolderCommitmentTransaction>,
1170}
1171
1172impl FundingScope {
1173 fn funding_outpoint(&self) -> OutPoint {
1174 let funding_outpoint = self.channel_parameters.funding_outpoint.as_ref();
1175 *funding_outpoint.expect("Funding outpoint must be set for active monitor")
1176 }
1177
1178 fn funding_txid(&self) -> Txid {
1179 self.funding_outpoint().txid
1180 }
1181
1182 fn is_splice(&self) -> bool {
1183 self.channel_parameters.splice_parent_funding_txid.is_some()
1184 }
1185
1186 fn channel_type_features(&self) -> &ChannelTypeFeatures {
1187 &self.channel_parameters.channel_type_features
1188 }
1189}
1190
1191impl_writeable_tlv_based!(FundingScope, {
1192 (1, channel_parameters, (required: ReadableArgs, None)),
1193 (3, current_counterparty_commitment_txid, required),
1194 (5, prev_counterparty_commitment_txid, option),
1195 (7, current_holder_commitment_tx, required),
1196 (9, prev_holder_commitment_tx, option),
1197 (11, counterparty_claimable_outpoints, required),
1198});
1199
1200#[derive(Clone, PartialEq)]
1201pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
1202 funding: FundingScope,
1203 pending_funding: Vec<FundingScope>,
1204
1205 is_manual_broadcast: bool,
1208 funding_seen_onchain: bool,
1217
1218 latest_update_id: u64,
1219 commitment_transaction_number_obscure_factor: u64,
1220
1221 destination_script: ScriptBuf,
1222 broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>,
1223 counterparty_payment_script: ScriptBuf,
1224 shutdown_script: Option<ScriptBuf>,
1225
1226 channel_keys_id: [u8; 32],
1227 holder_revocation_basepoint: RevocationBasepoint,
1228 channel_id: ChannelId,
1229 first_negotiated_funding_txo: OutPoint,
1230
1231 counterparty_commitment_params: CounterpartyCommitmentParameters,
1232
1233 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
1235
1236 on_holder_tx_csv: u16,
1237
1238 commitment_secrets: CounterpartyCommitmentSecrets,
1239 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
1245 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
1250
1251 counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
1252
1253 current_counterparty_commitment_number: u64,
1256 current_holder_commitment_number: u64,
1259
1260 payment_preimages: HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)>,
1273
1274 pending_monitor_events: Vec<MonitorEvent>,
1284
1285 pub(super) pending_events: Vec<Event>,
1286 pub(super) is_processing_pending_events: bool,
1287
1288 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
1292
1293 outputs_to_watch: HashMap<Txid, Vec<(u32, ScriptBuf)>>,
1298
1299 #[cfg(any(test, feature = "_test_utils"))]
1300 pub onchain_tx_handler: OnchainTxHandler<Signer>,
1301 #[cfg(not(any(test, feature = "_test_utils")))]
1302 onchain_tx_handler: OnchainTxHandler<Signer>,
1303
1304 lockdown_from_offchain: bool,
1308
1309 holder_tx_signed: bool,
1317
1318 funding_spend_seen: bool,
1322
1323 holder_pays_commitment_tx_fee: Option<bool>,
1326
1327 funding_spend_confirmed: Option<Txid>,
1330
1331 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
1332 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
1336
1337 htlcs_resolved_to_user: HashSet<SentHTLCId>,
1344
1345 spendable_txids_confirmed: Vec<Txid>,
1351
1352 best_block: BestBlock,
1358
1359 counterparty_node_id: PublicKey,
1361
1362 initial_counterparty_commitment_info: Option<(PublicKey, u32, u64, u64)>,
1369 initial_counterparty_commitment_tx: Option<CommitmentTransaction>,
1374
1375 balances_empty_height: Option<u32>,
1377
1378 failed_back_htlc_ids: HashSet<SentHTLCId>,
1383
1384 current_holder_htlc_data: CommitmentHTLCData,
1390 prev_holder_htlc_data: Option<CommitmentHTLCData>,
1391
1392 alternative_funding_confirmed: Option<(Txid, u32)>,
1400
1401 written_by_0_1_or_later: bool,
1405}
1406
1407macro_rules! get_confirmed_funding_scope {
1410 ($self: expr) => {
1411 $self
1412 .alternative_funding_confirmed
1413 .map(|(alternative_funding_txid, _)| {
1414 $self
1415 .pending_funding
1416 .iter()
1417 .find(|funding| funding.funding_txid() == alternative_funding_txid)
1418 .expect("FundingScope for confirmed alternative funding must exist")
1419 })
1420 .unwrap_or(&$self.funding)
1421 };
1422}
1423
1424#[rustfmt::skip]
1429macro_rules! holder_commitment_htlcs {
1430 ($self: expr, CURRENT) => {{
1431 let funding = get_confirmed_funding_scope!($self);
1432 funding.current_holder_commitment_tx.nondust_htlcs().iter()
1433 .chain($self.current_holder_htlc_data.dust_htlcs.iter().map(|(htlc, _)| htlc))
1434 }};
1435 ($self: expr, CURRENT_WITH_SOURCES) => {{
1436 let funding = get_confirmed_funding_scope!($self);
1437 holder_commitment_htlcs!(
1438 &funding.current_holder_commitment_tx, &$self.current_holder_htlc_data
1439 )
1440 }};
1441 ($self: expr, PREV) => {{
1442 let funding = get_confirmed_funding_scope!($self);
1443 funding.prev_holder_commitment_tx.as_ref().map(|tx| {
1444 let dust_htlcs = $self.prev_holder_htlc_data.as_ref().unwrap().dust_htlcs.iter()
1445 .map(|(htlc, _)| htlc);
1446 tx.nondust_htlcs().iter().chain(dust_htlcs)
1447 })
1448 }};
1449 ($self: expr, PREV_WITH_SOURCES) => {{
1450 let funding = get_confirmed_funding_scope!($self);
1451 funding.prev_holder_commitment_tx.as_ref().map(|tx| {
1452 holder_commitment_htlcs!(tx, $self.prev_holder_htlc_data.as_ref().unwrap())
1453 })
1454 }};
1455 ($commitment_tx: expr, $htlc_data: expr) => {{
1456 let mut sources = $htlc_data.nondust_htlc_sources.iter();
1457 let nondust_htlcs = $commitment_tx.nondust_htlcs().iter().map(move |htlc| {
1458 let mut source = None;
1459 if htlc.offered {
1460 debug_assert!(htlc.transaction_output_index.is_some());
1461 source = sources.next();
1462 if source.is_none() {
1463 panic!("Every offered non-dust HTLC should have a corresponding source");
1464 }
1465 }
1466 (htlc, source)
1467 });
1468 let dust_htlcs = $htlc_data.dust_htlcs.iter().map(|(htlc, source)| (htlc, source.as_ref()));
1469 nondust_htlcs.chain(dust_htlcs)
1470 }};
1471}
1472
1473pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
1475
1476#[cfg(any(feature = "_test_utils", test))]
1480impl<Signer: EcdsaChannelSigner> PartialEq for ChannelMonitor<Signer>
1481where
1482 Signer: PartialEq,
1483{
1484 fn eq(&self, other: &Self) -> bool {
1485 use crate::sync::LockTestExt;
1486 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1490 let a = if ord {
1491 self.inner.unsafe_well_ordered_double_lock_self()
1492 } else {
1493 other.inner.unsafe_well_ordered_double_lock_self()
1494 };
1495 let b = if ord {
1496 other.inner.unsafe_well_ordered_double_lock_self()
1497 } else {
1498 self.inner.unsafe_well_ordered_double_lock_self()
1499 };
1500 a.eq(&b)
1501 }
1502}
1503
1504impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
1505 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1506 self.inner.lock().unwrap().write(writer)
1507 }
1508}
1509
1510const SERIALIZATION_VERSION: u8 = 1;
1512const MIN_SERIALIZATION_VERSION: u8 = 1;
1513
1514pub(crate) fn write_chanmon_internal<Signer: EcdsaChannelSigner, W: Writer>(
1522 channel_monitor: &ChannelMonitorImpl<Signer>, _is_stub: bool, writer: &mut W,
1523) -> Result<(), Error> {
1524 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1525
1526 channel_monitor.latest_update_id.write(writer)?;
1527
1528 U48(channel_monitor.commitment_transaction_number_obscure_factor).write(writer)?;
1530
1531 channel_monitor.destination_script.write(writer)?;
1532 if let Some(ref broadcasted_holder_revokable_script) =
1533 channel_monitor.broadcasted_holder_revokable_script
1534 {
1535 writer.write_all(&[0; 1])?;
1536 broadcasted_holder_revokable_script.0.write(writer)?;
1537 broadcasted_holder_revokable_script.1.write(writer)?;
1538 broadcasted_holder_revokable_script.2.write(writer)?;
1539 } else {
1540 writer.write_all(&[1; 1])?;
1541 }
1542
1543 channel_monitor.counterparty_payment_script.write(writer)?;
1544 match &channel_monitor.shutdown_script {
1545 Some(script) => script.write(writer)?,
1546 None => ScriptBuf::new().write(writer)?,
1547 }
1548
1549 channel_monitor.channel_keys_id.write(writer)?;
1550 channel_monitor.holder_revocation_basepoint.write(writer)?;
1551 let funding_outpoint = channel_monitor.get_funding_txo();
1552 writer.write_all(&funding_outpoint.txid[..])?;
1553 writer.write_all(&funding_outpoint.index.to_be_bytes())?;
1554 let redeem_script = channel_monitor.funding.channel_parameters.make_funding_redeemscript();
1555 let script_pubkey = redeem_script.to_p2wsh();
1556 script_pubkey.write(writer)?;
1557 channel_monitor.funding.current_counterparty_commitment_txid.write(writer)?;
1558 channel_monitor.funding.prev_counterparty_commitment_txid.write(writer)?;
1559
1560 channel_monitor.counterparty_commitment_params.write(writer)?;
1561 redeem_script.write(writer)?;
1562 channel_monitor.funding.channel_parameters.channel_value_satoshis.write(writer)?;
1563
1564 match channel_monitor.their_cur_per_commitment_points {
1565 Some((idx, pubkey, second_option)) => {
1566 writer.write_all(&byte_utils::be48_to_array(idx))?;
1567 writer.write_all(&pubkey.serialize())?;
1568 match second_option {
1569 Some(second_pubkey) => {
1570 writer.write_all(&second_pubkey.serialize())?;
1571 },
1572 None => {
1573 writer.write_all(&[0; 33])?;
1574 },
1575 }
1576 },
1577 None => {
1578 writer.write_all(&byte_utils::be48_to_array(0))?;
1579 },
1580 }
1581
1582 writer.write_all(&channel_monitor.on_holder_tx_csv.to_be_bytes())?;
1583
1584 channel_monitor.commitment_secrets.write(writer)?;
1585
1586 #[rustfmt::skip]
1587 macro_rules! serialize_htlc_in_commitment {
1588 ($htlc_output: expr) => {
1589 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1590 writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
1591 writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
1592 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1593 $htlc_output.transaction_output_index.write(writer)?;
1594 }
1595 }
1596
1597 writer.write_all(
1598 &(channel_monitor.funding.counterparty_claimable_outpoints.len() as u64).to_be_bytes(),
1599 )?;
1600 for (ref txid, ref htlc_infos) in
1601 channel_monitor.funding.counterparty_claimable_outpoints.iter()
1602 {
1603 writer.write_all(&txid[..])?;
1604 writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
1605 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1606 debug_assert!(
1607 htlc_source.is_none()
1608 || Some(**txid) == channel_monitor.funding.current_counterparty_commitment_txid
1609 || Some(**txid) == channel_monitor.funding.prev_counterparty_commitment_txid,
1610 "HTLC Sources for all revoked commitment transactions should be none!"
1611 );
1612 serialize_htlc_in_commitment!(htlc_output);
1613 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1614 }
1615 }
1616
1617 writer.write_all(
1618 &(channel_monitor.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes(),
1619 )?;
1620 for (ref txid, commitment_number) in channel_monitor.counterparty_commitment_txn_on_chain.iter()
1621 {
1622 writer.write_all(&txid[..])?;
1623 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1624 }
1625
1626 writer.write_all(
1627 &(channel_monitor.counterparty_hash_commitment_number.len() as u64).to_be_bytes(),
1628 )?;
1629 for (ref payment_hash, commitment_number) in
1630 channel_monitor.counterparty_hash_commitment_number.iter()
1631 {
1632 writer.write_all(&payment_hash.0[..])?;
1633 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1634 }
1635
1636 if let Some(holder_commitment_tx) = &channel_monitor.funding.prev_holder_commitment_tx {
1637 writer.write_all(&[1; 1])?;
1638 write_legacy_holder_commitment_data(
1639 writer,
1640 holder_commitment_tx,
1641 &channel_monitor.prev_holder_htlc_data.as_ref().unwrap(),
1642 )?;
1643 } else {
1644 writer.write_all(&[0; 1])?;
1645 }
1646
1647 write_legacy_holder_commitment_data(
1648 writer,
1649 &channel_monitor.funding.current_holder_commitment_tx,
1650 &channel_monitor.current_holder_htlc_data,
1651 )?;
1652
1653 writer.write_all(&byte_utils::be48_to_array(
1654 channel_monitor.current_counterparty_commitment_number,
1655 ))?;
1656 writer
1657 .write_all(&byte_utils::be48_to_array(channel_monitor.current_holder_commitment_number))?;
1658
1659 writer.write_all(&(channel_monitor.payment_preimages.len() as u64).to_be_bytes())?;
1660 for (payment_preimage, _) in channel_monitor.payment_preimages.values() {
1661 writer.write_all(&payment_preimage.0[..])?;
1662 }
1663
1664 writer.write_all(
1665 &(channel_monitor
1666 .pending_monitor_events
1667 .iter()
1668 .filter(|ev| match ev {
1669 MonitorEvent::HTLCEvent(_) => true,
1670 MonitorEvent::HolderForceClosed(_) => true,
1671 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1672 _ => false,
1673 })
1674 .count() as u64)
1675 .to_be_bytes(),
1676 )?;
1677 for event in channel_monitor.pending_monitor_events.iter() {
1678 match event {
1679 MonitorEvent::HTLCEvent(upd) => {
1680 0u8.write(writer)?;
1681 upd.write(writer)?;
1682 },
1683 MonitorEvent::HolderForceClosed(_) => 1u8.write(writer)?,
1684 MonitorEvent::HolderForceClosedWithInfo { .. } => 1u8.write(writer)?,
1688 _ => {}, }
1690 }
1691
1692 writer.write_all(&(channel_monitor.pending_events.len() as u64).to_be_bytes())?;
1693 for event in channel_monitor.pending_events.iter() {
1694 event.write(writer)?;
1695 }
1696
1697 channel_monitor.best_block.block_hash.write(writer)?;
1698 writer.write_all(&channel_monitor.best_block.height.to_be_bytes())?;
1699
1700 writer.write_all(
1701 &(channel_monitor.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes(),
1702 )?;
1703 for ref entry in channel_monitor.onchain_events_awaiting_threshold_conf.iter() {
1704 entry.write(writer)?;
1705 }
1706
1707 (channel_monitor.outputs_to_watch.len() as u64).write(writer)?;
1708 for (txid, idx_scripts) in channel_monitor.outputs_to_watch.iter() {
1709 txid.write(writer)?;
1710 (idx_scripts.len() as u64).write(writer)?;
1711 for (idx, script) in idx_scripts.iter() {
1712 idx.write(writer)?;
1713 script.write(writer)?;
1714 }
1715 }
1716
1717 channel_monitor.onchain_tx_handler.write(writer)?;
1718
1719 channel_monitor.lockdown_from_offchain.write(writer)?;
1720 channel_monitor.holder_tx_signed.write(writer)?;
1721
1722 let pending_monitor_events =
1724 match channel_monitor.pending_monitor_events.iter().find(|ev| match ev {
1725 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1726 _ => false,
1727 }) {
1728 Some(MonitorEvent::HolderForceClosedWithInfo { outpoint, .. }) => {
1729 let mut pending_monitor_events = channel_monitor.pending_monitor_events.clone();
1730 pending_monitor_events.push(MonitorEvent::HolderForceClosed(*outpoint));
1731 pending_monitor_events
1732 },
1733 _ => channel_monitor.pending_monitor_events.clone(),
1734 };
1735
1736 write_tlv_fields!(writer, {
1737 (1, channel_monitor.funding_spend_confirmed, option),
1738 (3, channel_monitor.htlcs_resolved_on_chain, required_vec),
1739 (5, pending_monitor_events, required_vec),
1740 (7, channel_monitor.funding_spend_seen, required),
1741 (9, channel_monitor.counterparty_node_id, required),
1742 (11, channel_monitor.confirmed_commitment_tx_counterparty_output, option),
1743 (13, channel_monitor.spendable_txids_confirmed, required_vec),
1744 (15, channel_monitor.counterparty_fulfilled_htlcs, required),
1745 (17, channel_monitor.initial_counterparty_commitment_info, option),
1746 (19, channel_monitor.channel_id, required),
1747 (21, channel_monitor.balances_empty_height, option),
1748 (23, channel_monitor.holder_pays_commitment_tx_fee, option),
1749 (25, channel_monitor.payment_preimages, required),
1750 (27, channel_monitor.first_negotiated_funding_txo, required),
1751 (29, channel_monitor.initial_counterparty_commitment_tx, option),
1752 (31, channel_monitor.funding.channel_parameters, required),
1753 (32, channel_monitor.pending_funding, optional_vec),
1754 (33, channel_monitor.htlcs_resolved_to_user, required),
1755 (34, channel_monitor.alternative_funding_confirmed, option),
1756 (35, channel_monitor.is_manual_broadcast, required),
1757 (37, channel_monitor.funding_seen_onchain, required),
1758 });
1759
1760 Ok(())
1761}
1762
1763impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
1764 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1765 write_chanmon_internal(self, false, writer)
1766 }
1767}
1768
1769#[rustfmt::skip]
1770macro_rules! _process_events_body {
1771 ($self_opt: expr, $logger: expr, $event_to_handle: expr, $handle_event: expr) => {
1772 loop {
1773 let mut handling_res = Ok(());
1774 let (pending_events, repeated_events);
1775 if let Some(us) = $self_opt {
1776 let mut inner = us.inner.lock().unwrap();
1777 if inner.is_processing_pending_events {
1778 break handling_res;
1779 }
1780 inner.is_processing_pending_events = true;
1781
1782 pending_events = inner.pending_events.clone();
1783 repeated_events = inner.get_repeated_events();
1784 } else { break handling_res; }
1785
1786 let mut num_handled_events = 0;
1787 for event in pending_events {
1788 log_trace!($logger, "Handling event {:?}...", event);
1789 $event_to_handle = event;
1790 let event_handling_result = $handle_event;
1791 log_trace!($logger, "Done handling event, result: {:?}", event_handling_result);
1792 match event_handling_result {
1793 Ok(()) => num_handled_events += 1,
1794 Err(e) => {
1795 handling_res = Err(e);
1798 break;
1799 }
1800 }
1801 }
1802
1803 if handling_res.is_ok() {
1804 for event in repeated_events {
1805 $event_to_handle = event;
1808 let _ = $handle_event;
1809 }
1810 }
1811
1812 if let Some(us) = $self_opt {
1813 let mut inner = us.inner.lock().unwrap();
1814 inner.pending_events.drain(..num_handled_events);
1815 inner.is_processing_pending_events = false;
1816 if handling_res.is_ok() && !inner.pending_events.is_empty() {
1817 continue;
1820 }
1821 }
1822 break handling_res;
1823 }
1824 }
1825}
1826pub(super) use _process_events_body as process_events_body;
1827
1828pub(crate) struct WithChannelMonitor<'a, L: Deref>
1829where
1830 L::Target: Logger,
1831{
1832 logger: &'a L,
1833 peer_id: Option<PublicKey>,
1834 channel_id: Option<ChannelId>,
1835 payment_hash: Option<PaymentHash>,
1836}
1837
1838impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L>
1839where
1840 L::Target: Logger,
1841{
1842 fn log(&self, mut record: Record) {
1843 record.peer_id = self.peer_id;
1844 record.channel_id = self.channel_id;
1845 record.payment_hash = self.payment_hash;
1846 self.logger.log(record)
1847 }
1848}
1849
1850impl<'a, L: Deref> WithChannelMonitor<'a, L>
1851where
1852 L::Target: Logger,
1853{
1854 pub(crate) fn from<S: EcdsaChannelSigner>(
1855 logger: &'a L, monitor: &ChannelMonitor<S>, payment_hash: Option<PaymentHash>,
1856 ) -> Self {
1857 Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash)
1858 }
1859
1860 #[rustfmt::skip]
1861 pub(crate) fn from_impl<S: EcdsaChannelSigner>(logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>, payment_hash: Option<PaymentHash>) -> Self {
1862 let peer_id = Some(monitor_impl.counterparty_node_id);
1863 let channel_id = Some(monitor_impl.channel_id());
1864 WithChannelMonitor {
1865 logger, peer_id, channel_id, payment_hash,
1866 }
1867 }
1868}
1869
1870impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
1871 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1875 ChannelMonitor { inner: Mutex::new(imp) }
1876 }
1877
1878 #[rustfmt::skip]
1879 pub(crate) fn new(
1880 secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1881 on_counterparty_tx_csv: u16, destination_script: &Script,
1882 channel_parameters: &ChannelTransactionParameters, holder_pays_commitment_tx_fee: bool,
1883 commitment_transaction_number_obscure_factor: u64,
1884 initial_holder_commitment_tx: HolderCommitmentTransaction, best_block: BestBlock,
1885 counterparty_node_id: PublicKey, channel_id: ChannelId,
1886 is_manual_broadcast: bool,
1887 ) -> ChannelMonitor<Signer> {
1888
1889 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1890 let holder_pubkeys = &channel_parameters.holder_pubkeys;
1891 let counterparty_payment_script = chan_utils::get_countersigner_payment_script(
1892 &channel_parameters.channel_type_features, &holder_pubkeys.payment_point
1893 );
1894
1895 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1896 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1897 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1898 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1899
1900 let channel_keys_id = keys.channel_keys_id();
1901 let holder_revocation_basepoint = holder_pubkeys.revocation_basepoint;
1902
1903 let current_holder_commitment_number =
1904 initial_holder_commitment_tx.trust().commitment_number();
1905
1906 let onchain_tx_handler = OnchainTxHandler::new(
1907 channel_parameters.channel_value_satoshis, channel_keys_id, destination_script.into(),
1908 keys, channel_parameters.clone(), initial_holder_commitment_tx.clone(), secp_ctx
1909 );
1910
1911 let funding_outpoint = channel_parameters.funding_outpoint
1912 .expect("Funding outpoint must be known during initialization");
1913 let funding_redeem_script = channel_parameters.make_funding_redeemscript();
1914 let funding_script = funding_redeem_script.to_p2wsh();
1915 let mut outputs_to_watch = new_hash_map();
1916 outputs_to_watch.insert(
1917 funding_outpoint.txid, vec![(funding_outpoint.index as u32, funding_script.clone())],
1918 );
1919
1920 Self::from_impl(ChannelMonitorImpl {
1921 funding: FundingScope {
1922 channel_parameters: channel_parameters.clone(),
1923
1924 current_counterparty_commitment_txid: None,
1925 prev_counterparty_commitment_txid: None,
1926 counterparty_claimable_outpoints: new_hash_map(),
1927
1928 current_holder_commitment_tx: initial_holder_commitment_tx,
1929 prev_holder_commitment_tx: None,
1930 },
1931 pending_funding: vec![],
1932
1933 is_manual_broadcast,
1934 funding_seen_onchain: false,
1935
1936 latest_update_id: 0,
1937 commitment_transaction_number_obscure_factor,
1938
1939 destination_script: destination_script.into(),
1940 broadcasted_holder_revokable_script: None,
1941 counterparty_payment_script,
1942 shutdown_script,
1943
1944 channel_keys_id,
1945 holder_revocation_basepoint,
1946 channel_id,
1947 first_negotiated_funding_txo: funding_outpoint,
1948
1949 counterparty_commitment_params,
1950 their_cur_per_commitment_points: None,
1951
1952 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1953
1954 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1955 counterparty_commitment_txn_on_chain: new_hash_map(),
1956 counterparty_hash_commitment_number: new_hash_map(),
1957 counterparty_fulfilled_htlcs: new_hash_map(),
1958
1959 current_counterparty_commitment_number: 1 << 48,
1960 current_holder_commitment_number,
1961
1962 payment_preimages: new_hash_map(),
1963 pending_monitor_events: Vec::new(),
1964 pending_events: Vec::new(),
1965 is_processing_pending_events: false,
1966
1967 onchain_events_awaiting_threshold_conf: Vec::new(),
1968 outputs_to_watch,
1969
1970 onchain_tx_handler,
1971
1972 holder_pays_commitment_tx_fee: Some(holder_pays_commitment_tx_fee),
1973 lockdown_from_offchain: false,
1974 holder_tx_signed: false,
1975 funding_spend_seen: false,
1976 funding_spend_confirmed: None,
1977 confirmed_commitment_tx_counterparty_output: None,
1978 htlcs_resolved_on_chain: Vec::new(),
1979 htlcs_resolved_to_user: new_hash_set(),
1980 spendable_txids_confirmed: Vec::new(),
1981
1982 best_block,
1983 counterparty_node_id: counterparty_node_id,
1984 initial_counterparty_commitment_info: None,
1985 initial_counterparty_commitment_tx: None,
1986 balances_empty_height: None,
1987
1988 failed_back_htlc_ids: new_hash_set(),
1989
1990 current_holder_htlc_data: CommitmentHTLCData::new(),
1992 prev_holder_htlc_data: None,
1993
1994 alternative_funding_confirmed: None,
1995
1996 written_by_0_1_or_later: true,
1997 })
1998 }
1999
2000 pub fn persistence_key(&self) -> MonitorName {
2010 let inner = self.inner.lock().unwrap();
2011 let funding_outpoint = inner.first_negotiated_funding_txo;
2012 let channel_id = inner.channel_id;
2013 if ChannelId::v1_from_funding_outpoint(funding_outpoint) == channel_id {
2014 MonitorName::V1Channel(funding_outpoint)
2015 } else {
2016 MonitorName::V2Channel(channel_id)
2017 }
2018 }
2019
2020 #[cfg(test)]
2021 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2022 self.inner.lock().unwrap().provide_secret(idx, secret)
2023 }
2024
2025 pub(crate) fn provide_initial_counterparty_commitment_tx(
2033 &self, commitment_tx: CommitmentTransaction,
2034 ) {
2035 let mut inner = self.inner.lock().unwrap();
2036 inner.provide_initial_counterparty_commitment_tx(commitment_tx);
2037 }
2038
2039 #[cfg(test)]
2044 fn provide_latest_counterparty_commitment_tx(
2045 &self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2046 commitment_number: u64, their_per_commitment_point: PublicKey,
2047 ) {
2048 let mut inner = self.inner.lock().unwrap();
2049 inner.provide_latest_counterparty_commitment_tx(
2050 txid,
2051 htlc_outputs,
2052 commitment_number,
2053 their_per_commitment_point,
2054 )
2055 }
2056
2057 #[cfg(test)]
2058 #[rustfmt::skip]
2059 fn provide_latest_holder_commitment_tx(
2060 &self, holder_commitment_tx: HolderCommitmentTransaction,
2061 htlc_outputs: &[(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)],
2062 ) {
2063 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(
2064 holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new(),
2065 ).unwrap()
2066 }
2067
2068 #[rustfmt::skip]
2079 pub(crate) fn provide_payment_preimage_unsafe_legacy<B: Deref, F: Deref, L: Deref>(
2080 &self,
2081 payment_hash: &PaymentHash,
2082 payment_preimage: &PaymentPreimage,
2083 broadcaster: &B,
2084 fee_estimator: &LowerBoundedFeeEstimator<F>,
2085 logger: &L,
2086 ) where
2087 B::Target: BroadcasterInterface,
2088 F::Target: FeeEstimator,
2089 L::Target: Logger,
2090 {
2091 let mut inner = self.inner.lock().unwrap();
2092 let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash));
2093 inner.provide_payment_preimage(
2097 payment_hash, payment_preimage, &None, broadcaster, fee_estimator, &logger)
2098 }
2099
2100 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
2105 &self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L,
2106 ) -> Result<(), ()>
2107 where
2108 B::Target: BroadcasterInterface,
2109 F::Target: FeeEstimator,
2110 L::Target: Logger,
2111 {
2112 let mut inner = self.inner.lock().unwrap();
2113 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2114 inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
2115 }
2116
2117 pub fn get_latest_update_id(&self) -> u64 {
2122 self.inner.lock().unwrap().get_latest_update_id()
2123 }
2124
2125 pub fn get_funding_txo(&self) -> OutPoint {
2127 self.inner.lock().unwrap().get_funding_txo()
2128 }
2129
2130 pub(crate) fn written_by_0_1_or_later(&self) -> bool {
2131 self.inner.lock().unwrap().written_by_0_1_or_later
2132 }
2133
2134 pub fn get_funding_script(&self) -> ScriptBuf {
2136 self.inner.lock().unwrap().get_funding_script()
2137 }
2138
2139 pub fn channel_id(&self) -> ChannelId {
2141 self.inner.lock().unwrap().channel_id()
2142 }
2143
2144 pub fn channel_type_features(&self) -> ChannelTypeFeatures {
2146 self.inner.lock().unwrap().channel_type_features().clone()
2147 }
2148
2149 #[rustfmt::skip]
2152 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
2153 self.inner.lock().unwrap().get_outputs_to_watch()
2154 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
2155 }
2156
2157 #[rustfmt::skip]
2161 pub fn load_outputs_to_watch<F: Deref, L: Deref>(&self, filter: &F, logger: &L)
2162 where
2163 F::Target: chain::Filter, L::Target: Logger,
2164 {
2165 let lock = self.inner.lock().unwrap();
2166 let logger = WithChannelMonitor::from_impl(logger, &*lock, None);
2167 for funding in core::iter::once(&lock.funding).chain(&lock.pending_funding) {
2168 let funding_outpoint = funding.funding_outpoint();
2169 log_trace!(&logger, "Registering funding outpoint {} with the filter to monitor confirmations", &funding_outpoint);
2170 let script_pubkey = funding.channel_parameters.make_funding_redeemscript().to_p2wsh();
2171 filter.register_tx(&funding_outpoint.txid, &script_pubkey);
2172 }
2173 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
2174 for (index, script_pubkey) in outputs.iter() {
2175 assert!(*index <= u16::MAX as u32);
2176 let outpoint = OutPoint { txid: *txid, index: *index as u16 };
2177 log_trace!(logger, "Registering outpoint {} with the filter to monitor spend", outpoint);
2178 filter.register_output(WatchedOutput {
2179 block_hash: None,
2180 outpoint,
2181 script_pubkey: script_pubkey.clone(),
2182 });
2183 }
2184 }
2185 }
2186
2187 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
2190 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
2191 }
2192
2193 pub fn process_pending_events<H: Deref, L: Deref>(
2209 &self, handler: &H, logger: &L,
2210 ) -> Result<(), ReplayEvent>
2211 where
2212 H::Target: EventHandler,
2213 L::Target: Logger,
2214 {
2215 let mut ev;
2216 process_events_body!(Some(self), logger, ev, handler.handle_event(ev))
2217 }
2218
2219 pub async fn process_pending_events_async<
2223 Future: core::future::Future<Output = Result<(), ReplayEvent>>,
2224 H: Fn(Event) -> Future,
2225 L: Deref,
2226 >(
2227 &self, handler: &H, logger: &L,
2228 ) -> Result<(), ReplayEvent>
2229 where
2230 L::Target: Logger,
2231 {
2232 let mut ev;
2233 process_events_body!(Some(self), logger, ev, { handler(ev).await })
2234 }
2235
2236 #[cfg(test)]
2237 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
2238 let mut ret = Vec::new();
2239 let mut lck = self.inner.lock().unwrap();
2240 mem::swap(&mut ret, &mut lck.pending_events);
2241 ret.append(&mut lck.get_repeated_events());
2242 ret
2243 }
2244
2245 pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
2258 self.inner.lock().unwrap().initial_counterparty_commitment_tx()
2259 }
2260
2261 pub fn counterparty_commitment_txs_from_update(
2282 &self, update: &ChannelMonitorUpdate,
2283 ) -> Vec<CommitmentTransaction> {
2284 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
2285 }
2286
2287 #[rustfmt::skip]
2309 pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
2310 self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
2311 }
2312
2313 pub(crate) fn get_min_seen_secret(&self) -> u64 {
2314 self.inner.lock().unwrap().get_min_seen_secret()
2315 }
2316
2317 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
2318 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
2319 }
2320
2321 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
2322 self.inner.lock().unwrap().get_cur_holder_commitment_number()
2323 }
2324
2325 pub(crate) fn no_further_updates_allowed(&self) -> bool {
2332 self.inner.lock().unwrap().no_further_updates_allowed()
2333 }
2334
2335 pub fn get_counterparty_node_id(&self) -> PublicKey {
2337 self.inner.lock().unwrap().counterparty_node_id
2338 }
2339
2340 pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
2360 &self, broadcaster: &B, fee_estimator: &F, logger: &L,
2361 ) where
2362 B::Target: BroadcasterInterface,
2363 F::Target: FeeEstimator,
2364 L::Target: Logger,
2365 {
2366 let mut inner = self.inner.lock().unwrap();
2367 let fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
2368 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2369
2370 inner.queue_latest_holder_commitment_txn_for_broadcast(
2371 broadcaster,
2372 &fee_estimator,
2373 &logger,
2374 false,
2375 );
2376 }
2377
2378 #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
2382 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
2383 where
2384 L::Target: Logger,
2385 {
2386 let mut inner = self.inner.lock().unwrap();
2387 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2388 inner.unsafe_get_latest_holder_commitment_txn(&logger)
2389 }
2390
2391 #[rustfmt::skip]
2403 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
2404 &self,
2405 header: &Header,
2406 txdata: &TransactionData,
2407 height: u32,
2408 broadcaster: B,
2409 fee_estimator: F,
2410 logger: &L,
2411 ) -> Vec<TransactionOutputs>
2412 where
2413 B::Target: BroadcasterInterface,
2414 F::Target: FeeEstimator,
2415 L::Target: Logger,
2416 {
2417 let mut inner = self.inner.lock().unwrap();
2418 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2419 inner.block_connected(
2420 header, txdata, height, broadcaster, fee_estimator, &logger)
2421 }
2422
2423 pub fn blocks_disconnected<B: Deref, F: Deref, L: Deref>(
2426 &self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &L,
2427 ) where
2428 B::Target: BroadcasterInterface,
2429 F::Target: FeeEstimator,
2430 L::Target: Logger,
2431 {
2432 let mut inner = self.inner.lock().unwrap();
2433 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2434 inner.blocks_disconnected(fork_point, broadcaster, fee_estimator, &logger)
2435 }
2436
2437 #[rustfmt::skip]
2445 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
2446 &self,
2447 header: &Header,
2448 txdata: &TransactionData,
2449 height: u32,
2450 broadcaster: B,
2451 fee_estimator: F,
2452 logger: &L,
2453 ) -> Vec<TransactionOutputs>
2454 where
2455 B::Target: BroadcasterInterface,
2456 F::Target: FeeEstimator,
2457 L::Target: Logger,
2458 {
2459 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2460 let mut inner = self.inner.lock().unwrap();
2461 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2462 inner.transactions_confirmed(
2463 header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
2464 }
2465
2466 #[rustfmt::skip]
2473 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
2474 &self,
2475 txid: &Txid,
2476 broadcaster: B,
2477 fee_estimator: F,
2478 logger: &L,
2479 ) where
2480 B::Target: BroadcasterInterface,
2481 F::Target: FeeEstimator,
2482 L::Target: Logger,
2483 {
2484 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2485 let mut inner = self.inner.lock().unwrap();
2486 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2487 inner.transaction_unconfirmed(
2488 txid, broadcaster, &bounded_fee_estimator, &logger
2489 );
2490 }
2491
2492 #[rustfmt::skip]
2500 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
2501 &self,
2502 header: &Header,
2503 height: u32,
2504 broadcaster: B,
2505 fee_estimator: F,
2506 logger: &L,
2507 ) -> Vec<TransactionOutputs>
2508 where
2509 B::Target: BroadcasterInterface,
2510 F::Target: FeeEstimator,
2511 L::Target: Logger,
2512 {
2513 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2514 let mut inner = self.inner.lock().unwrap();
2515 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2516 inner.best_block_updated(
2517 header, height, broadcaster, &bounded_fee_estimator, &logger
2518 )
2519 }
2520
2521 #[rustfmt::skip]
2523 pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
2524 let inner = self.inner.lock().unwrap();
2525 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
2526 .iter()
2527 .map(|entry| (entry.txid, entry.height, entry.block_hash))
2528 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
2529 .collect();
2530 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
2531 txids.dedup_by_key(|(txid, _, _)| *txid);
2532 txids
2533 }
2534
2535 pub fn current_best_block(&self) -> BestBlock {
2538 self.inner.lock().unwrap().best_block.clone()
2539 }
2540
2541 #[rustfmt::skip]
2547 pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
2548 &self, broadcaster: B, fee_estimator: F, logger: &L,
2549 )
2550 where
2551 B::Target: BroadcasterInterface,
2552 F::Target: FeeEstimator,
2553 L::Target: Logger,
2554 {
2555 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2556 let mut lock = self.inner.lock().unwrap();
2557 let inner = &mut *lock;
2558 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2559 let current_height = inner.best_block.height;
2560 let conf_target = inner.closure_conf_target();
2561 inner.onchain_tx_handler.rebroadcast_pending_claims(
2562 current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, conf_target,
2563 &inner.destination_script, &fee_estimator, &logger,
2564 );
2565 }
2566
2567 pub fn has_pending_claims(&self) -> bool {
2569 self.inner.lock().unwrap().onchain_tx_handler.has_pending_claims()
2570 }
2571
2572 #[rustfmt::skip]
2575 pub fn signer_unblocked<B: Deref, F: Deref, L: Deref>(
2576 &self, broadcaster: B, fee_estimator: F, logger: &L,
2577 )
2578 where
2579 B::Target: BroadcasterInterface,
2580 F::Target: FeeEstimator,
2581 L::Target: Logger,
2582 {
2583 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2584 let mut lock = self.inner.lock().unwrap();
2585 let inner = &mut *lock;
2586 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2587 let current_height = inner.best_block.height;
2588 let conf_target = inner.closure_conf_target();
2589 inner.onchain_tx_handler.rebroadcast_pending_claims(
2590 current_height, FeerateStrategy::RetryPrevious, &broadcaster, conf_target,
2591 &inner.destination_script, &fee_estimator, &logger,
2592 );
2593 }
2594
2595 #[rustfmt::skip]
2614 pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
2615 let inner = self.inner.lock().unwrap();
2616 let current_height = inner.best_block.height;
2617 let funding = get_confirmed_funding_scope!(inner);
2618 let mut spendable_outputs = inner.get_spendable_outputs(&funding, tx);
2619 spendable_outputs.retain(|descriptor| {
2620 let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
2621 if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
2622 conf_threshold = cmp::min(conf_threshold,
2623 current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
2624 }
2625 conf_threshold >= confirmation_height
2626 });
2627 spendable_outputs
2628 }
2629
2630 #[rustfmt::skip]
2645 pub fn check_and_update_full_resolution_status<L: Logger>(&self, logger: &L) -> (bool, bool) {
2646 let mut is_all_funds_claimed = self.get_claimable_balances().is_empty();
2647 let current_height = self.current_best_block().height;
2648 let mut inner = self.inner.lock().unwrap();
2649
2650 if inner.is_closed_without_updates()
2651 && is_all_funds_claimed
2652 && !inner.funding_spend_seen
2653 {
2654 return (true, false);
2658 }
2659
2660 if is_all_funds_claimed && !inner.funding_spend_seen {
2661 debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2662 is_all_funds_claimed = false;
2663 }
2664
2665 let preimages_not_needed_elsewhere = inner.pending_monitor_events.is_empty();
2669
2670 match (inner.balances_empty_height, is_all_funds_claimed, preimages_not_needed_elsewhere) {
2671 (Some(balances_empty_height), true, true) => {
2672 (current_height >= balances_empty_height + ARCHIVAL_DELAY_BLOCKS, false)
2674 },
2675 (Some(_), false, _)|(Some(_), _, false) => {
2676 debug_assert!(false,
2681 "Thought we were done claiming funds, but claimable_balances now has entries");
2682 log_error!(logger,
2683 "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",
2684 inner.get_funding_txo());
2685 inner.balances_empty_height = None;
2686 (false, true)
2687 },
2688 (None, true, true) => {
2689 log_debug!(logger,
2692 "ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
2693 inner.get_funding_txo(), ARCHIVAL_DELAY_BLOCKS);
2694 inner.balances_empty_height = Some(current_height);
2695 (false, true)
2696 },
2697 (None, false, _)|(None, _, false) => {
2698 (false, false)
2700 },
2701 }
2702 }
2703
2704 #[cfg(test)]
2705 pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
2706 self.inner.lock().unwrap().counterparty_payment_script.clone()
2707 }
2708
2709 #[cfg(test)]
2710 pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
2711 self.inner.lock().unwrap().counterparty_payment_script = script;
2712 }
2713
2714 #[cfg(any(test, feature = "_test_utils"))]
2715 pub fn do_mut_signer_call<F: FnMut(&mut Signer) -> ()>(&self, mut f: F) {
2716 let mut inner = self.inner.lock().unwrap();
2717 f(&mut inner.onchain_tx_handler.signer);
2718 }
2719}
2720
2721impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2722 #[rustfmt::skip]
2725 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, source: Option<&HTLCSource>,
2726 holder_commitment: bool, counterparty_revoked_commitment: bool,
2727 confirmed_txid: Option<Txid>
2728 ) -> Option<Balance> {
2729 let htlc_commitment_tx_output_idx = htlc.transaction_output_index?;
2730
2731 let mut htlc_spend_txid_opt = None;
2732 let mut htlc_spend_tx_opt = None;
2733 let mut holder_timeout_spend_pending = None;
2734 let mut htlc_spend_pending = None;
2735 let mut holder_delayed_output_pending = None;
2736 for event in self.onchain_events_awaiting_threshold_conf.iter() {
2737 match event.event {
2738 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
2739 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
2740 debug_assert!(htlc_spend_txid_opt.is_none());
2741 htlc_spend_txid_opt = Some(&event.txid);
2742 debug_assert!(htlc_spend_tx_opt.is_none());
2743 htlc_spend_tx_opt = event.transaction.as_ref();
2744 debug_assert!(holder_timeout_spend_pending.is_none());
2745 debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
2746 holder_timeout_spend_pending = Some(event.confirmation_threshold());
2747 },
2748 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
2749 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
2750 debug_assert!(htlc_spend_txid_opt.is_none());
2751 htlc_spend_txid_opt = Some(&event.txid);
2752 debug_assert!(htlc_spend_tx_opt.is_none());
2753 htlc_spend_tx_opt = event.transaction.as_ref();
2754 debug_assert!(htlc_spend_pending.is_none());
2755 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
2756 },
2757 OnchainEvent::MaturingOutput {
2758 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
2759 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
2760 .any(|(input_idx, inp)|
2761 Some(inp.previous_output.txid) == confirmed_txid &&
2762 inp.previous_output.vout == htlc_commitment_tx_output_idx &&
2763 descriptor.outpoint.index as usize == input_idx
2769 ))
2770 .unwrap_or(false)
2771 => {
2772 debug_assert!(holder_delayed_output_pending.is_none());
2773 holder_delayed_output_pending = Some(event.confirmation_threshold());
2774 },
2775 _ => {},
2776 }
2777 }
2778 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
2779 .any(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
2780 debug_assert!(htlc_spend_txid_opt.is_none());
2781 htlc_spend_txid_opt = v.resolving_txid.as_ref();
2782 debug_assert!(htlc_spend_tx_opt.is_none());
2783 htlc_spend_tx_opt = v.resolving_tx.as_ref();
2784 true
2785 } else { false });
2786 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved as u8 <= 1);
2787
2788 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
2789 let htlc_output_to_spend =
2790 if let Some(txid) = htlc_spend_txid_opt {
2791 if let Some(ref tx) = htlc_spend_tx_opt {
2796 let htlc_input_idx_opt = tx.input.iter().enumerate()
2797 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2798 .map(|(idx, _)| idx as u32);
2799 debug_assert!(htlc_input_idx_opt.is_some());
2800 BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2801 } else {
2802 let funding = get_confirmed_funding_scope!(self);
2803 debug_assert!(!funding.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2804 debug_assert!(!funding.channel_type_features().supports_anchor_zero_fee_commitments());
2805 BitcoinOutPoint::new(*txid, 0)
2806 }
2807 } else {
2808 htlc_commitment_outpoint
2809 };
2810 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2811
2812 if let Some(conf_thresh) = holder_delayed_output_pending {
2813 debug_assert!(holder_commitment);
2814 return Some(Balance::ClaimableAwaitingConfirmations {
2815 amount_satoshis: htlc.amount_msat / 1000,
2816 confirmation_height: conf_thresh,
2817 source: BalanceSource::Htlc,
2818 });
2819 } else if htlc_resolved && !htlc_output_spend_pending {
2820 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2826 } else if counterparty_revoked_commitment {
2827 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2828 if let OnchainEvent::MaturingOutput {
2829 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2830 } = &event.event {
2831 event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2832 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2833 tx.compute_txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2834 } else {
2835 Some(inp.previous_output.txid) == confirmed_txid &&
2836 inp.previous_output.vout == htlc_commitment_tx_output_idx
2837 }
2838 })).unwrap_or(false)
2839 } else {
2840 false
2841 }
2842 });
2843 if htlc_output_claim_pending {
2844 } else {
2849 debug_assert!(holder_timeout_spend_pending.is_none(),
2850 "HTLCUpdate OnchainEvents should never appear for preimage claims");
2851 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2852 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2853 return Some(Balance::CounterpartyRevokedOutputClaimable {
2854 amount_satoshis: htlc.amount_msat / 1000,
2855 });
2856 }
2857 } else if htlc.offered == holder_commitment {
2858 if let Some(conf_thresh) = holder_timeout_spend_pending {
2862 return Some(Balance::ClaimableAwaitingConfirmations {
2863 amount_satoshis: htlc.amount_msat / 1000,
2864 confirmation_height: conf_thresh,
2865 source: BalanceSource::Htlc,
2866 });
2867 } else {
2868 let outbound_payment = match source {
2869 None => panic!("Outbound HTLCs should have a source"),
2870 Some(&HTLCSource::PreviousHopData(_)) => 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::OutboundRoute { .. }) => true,
3084 };
3085 if outbound_payment {
3086 outbound_payment_htlc_rounded_msat += rounded_value_msat;
3087 } else {
3088 outbound_forwarded_htlc_rounded_msat += rounded_value_msat;
3089 }
3090 if htlc.transaction_output_index.is_some() {
3091 res.push(Balance::MaybeTimeoutClaimableHTLC {
3092 amount_satoshis: htlc.amount_msat / 1000,
3093 claimable_height: htlc.cltv_expiry,
3094 payment_hash: htlc.payment_hash,
3095 outbound_payment,
3096 });
3097 }
3098 } else if us.payment_preimages.contains_key(&htlc.payment_hash) {
3099 inbound_claiming_htlc_rounded_msat += rounded_value_msat;
3100 if htlc.transaction_output_index.is_some() {
3101 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
3102 }
3103 } else {
3104 inbound_htlc_rounded_msat += rounded_value_msat;
3105 if htlc.transaction_output_index.is_some() {
3106 res.push(Balance::MaybePreimageClaimableHTLC {
3109 amount_satoshis: htlc.amount_msat / 1000,
3110 expiry_height: htlc.cltv_expiry,
3111 payment_hash: htlc.payment_hash,
3112 });
3113 }
3114 }
3115 }
3116 let balance_candidates = core::iter::once(&us.funding)
3117 .chain(us.pending_funding.iter())
3118 .map(|funding| {
3119 let to_self_value_sat = funding.current_holder_commitment_tx.to_broadcaster_value_sat();
3120 let transaction_fee_satoshis = if us.holder_pays_commitment_tx_fee.unwrap_or(true) {
3123 let transaction = &funding.current_holder_commitment_tx.trust().built_transaction().transaction;
3124 let output_value_sat: u64 = transaction.output.iter().map(|txout| txout.value.to_sat()).sum();
3125 funding.channel_parameters.channel_value_satoshis - output_value_sat
3126 } else {
3127 0
3128 };
3129 HolderCommitmentTransactionBalance {
3130 amount_satoshis: to_self_value_sat + claimable_inbound_htlc_value_sat,
3131 transaction_fee_satoshis,
3132 }
3133 })
3134 .collect::<Vec<_>>();
3135 let confirmed_balance_candidate_index = core::iter::once(&us.funding)
3136 .chain(us.pending_funding.iter())
3137 .enumerate()
3138 .find(|(_, funding)| {
3139 us.alternative_funding_confirmed
3140 .map(|(funding_txid_confirmed, _)| funding.funding_txid() == funding_txid_confirmed)
3141 .unwrap_or(true)
3144 })
3145 .map(|(idx, _)| idx)
3146 .expect("We must have one FundingScope that is confirmed");
3147
3148 if !us.is_closed_without_updates()
3155 || balance_candidates.iter().any(|bal| bal.amount_satoshis != 0)
3156 {
3157 res.push(Balance::ClaimableOnChannelClose {
3158 balance_candidates,
3159 confirmed_balance_candidate_index,
3160 outbound_payment_htlc_rounded_msat,
3161 outbound_forwarded_htlc_rounded_msat,
3162 inbound_claiming_htlc_rounded_msat,
3163 inbound_htlc_rounded_msat,
3164 });
3165 }
3166 }
3167
3168 res
3169 }
3170
3171 pub(crate) fn get_all_current_outbound_htlcs(
3175 &self,
3176 ) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
3177 let mut res = new_hash_map();
3178 let us = self.inner.lock().unwrap();
3181 let mut walk_counterparty_commitment = |txid| {
3182 if let Some(latest_outpoints) = us.funding.counterparty_claimable_outpoints.get(txid) {
3183 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
3184 if let &Some(ref source) = source_option {
3185 let htlc_id = SentHTLCId::from_source(source);
3186 if !us.htlcs_resolved_to_user.contains(&htlc_id) {
3187 let preimage_opt =
3188 us.counterparty_fulfilled_htlcs.get(&htlc_id).cloned();
3189 res.insert((**source).clone(), (htlc.clone(), preimage_opt));
3190 }
3191 }
3192 }
3193 }
3194 };
3195 if let Some(ref txid) = us.funding.current_counterparty_commitment_txid {
3196 walk_counterparty_commitment(txid);
3197 }
3198 if let Some(ref txid) = us.funding.prev_counterparty_commitment_txid {
3199 walk_counterparty_commitment(txid);
3200 }
3201 res
3202 }
3203
3204 pub(crate) fn get_onchain_failed_outbound_htlcs(&self) -> HashMap<HTLCSource, PaymentHash> {
3208 let mut res = new_hash_map();
3209 let us = self.inner.lock().unwrap();
3210
3211 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
3215 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
3216 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
3217 if event.height + ANTI_REORG_DELAY - 1 <= us.best_block.height {
3218 Some(event.txid)
3219 } else {
3220 None
3221 }
3222 } else {
3223 None
3224 }
3225 })
3226 });
3227
3228 let confirmed_txid = if let Some(txid) = confirmed_txid {
3229 txid
3230 } else {
3231 return res;
3232 };
3233
3234 macro_rules! walk_htlcs {
3235 ($htlc_iter: expr) => {
3236 let mut walk_candidate_htlcs = |htlcs| {
3237 for &(ref candidate_htlc, ref candidate_source) in htlcs {
3238 let candidate_htlc: &HTLCOutputInCommitment = &candidate_htlc;
3239 let candidate_source: &Option<Box<HTLCSource>> = &candidate_source;
3240
3241 let source: &HTLCSource = if let Some(source) = candidate_source {
3242 source
3243 } else {
3244 continue;
3245 };
3246 let htlc_id = SentHTLCId::from_source(source);
3247 if us.htlcs_resolved_to_user.contains(&htlc_id) {
3248 continue;
3249 }
3250
3251 let confirmed = $htlc_iter.find(|(_, conf_src)| Some(source) == *conf_src);
3252 if let Some((confirmed_htlc, _)) = confirmed {
3253 let filter = |v: &&IrrevocablyResolvedHTLC| {
3254 v.commitment_tx_output_idx
3255 == confirmed_htlc.transaction_output_index
3256 };
3257
3258 if confirmed_htlc.transaction_output_index.is_none() {
3261 res.insert(source.clone(), confirmed_htlc.payment_hash);
3264 } else if let Some(state) =
3265 us.htlcs_resolved_on_chain.iter().filter(filter).next()
3266 {
3267 if state.payment_preimage.is_none() {
3268 res.insert(source.clone(), confirmed_htlc.payment_hash);
3269 }
3270 }
3271 } else {
3272 res.insert(source.clone(), candidate_htlc.payment_hash);
3276 }
3277 }
3278 };
3279
3280 if let Some(ref txid) = us.funding.current_counterparty_commitment_txid {
3283 let htlcs = us.funding.counterparty_claimable_outpoints.get(txid);
3284 walk_candidate_htlcs(htlcs.expect("Missing tx info for latest tx"));
3285 }
3286 if let Some(ref txid) = us.funding.prev_counterparty_commitment_txid {
3287 let htlcs = us.funding.counterparty_claimable_outpoints.get(txid);
3288 walk_candidate_htlcs(htlcs.expect("Missing tx info for previous tx"));
3289 }
3290 };
3291 }
3292
3293 let funding = get_confirmed_funding_scope!(us);
3294
3295 if Some(confirmed_txid) == funding.current_counterparty_commitment_txid
3296 || Some(confirmed_txid) == funding.prev_counterparty_commitment_txid
3297 {
3298 let htlcs = funding.counterparty_claimable_outpoints.get(&confirmed_txid).unwrap();
3299 walk_htlcs!(htlcs.iter().filter_map(|(a, b)| {
3300 if let &Some(ref source) = b {
3301 Some((a, Some(&**source)))
3302 } else {
3303 None
3304 }
3305 }));
3306 } else if confirmed_txid == funding.current_holder_commitment_tx.trust().txid() {
3307 walk_htlcs!(holder_commitment_htlcs!(us, CURRENT_WITH_SOURCES));
3308 } else if let Some(prev_commitment_tx) = &funding.prev_holder_commitment_tx {
3309 if confirmed_txid == prev_commitment_tx.trust().txid() {
3310 walk_htlcs!(holder_commitment_htlcs!(us, PREV_WITH_SOURCES).unwrap());
3311 } else {
3312 let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
3313 walk_htlcs!(htlcs_confirmed.iter());
3314 }
3315 } else {
3316 let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
3317 walk_htlcs!(htlcs_confirmed.iter());
3318 }
3319
3320 res
3321 }
3322
3323 pub(crate) fn get_stored_preimages(
3324 &self,
3325 ) -> HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)> {
3326 self.inner.lock().unwrap().payment_preimages.clone()
3327 }
3328}
3329
3330macro_rules! fail_unbroadcast_htlcs {
3346 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
3347 $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
3348 debug_assert_eq!($commitment_tx_confirmed.compute_txid(), $commitment_txid_confirmed);
3349
3350 macro_rules! check_htlc_fails {
3351 ($txid: expr, $commitment_tx: expr, $per_commitment_outpoints: expr) => {
3352 if let Some(ref latest_outpoints) = $per_commitment_outpoints {
3353 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
3354 if let &Some(ref source) = source_option {
3355 let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
3365
3366 let mut matched_htlc = false;
3367 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
3368 if broadcast_htlc.transaction_output_index.is_some() &&
3369 (Some(&**source) == *broadcast_source ||
3370 (broadcast_source.is_none() &&
3371 broadcast_htlc.payment_hash == htlc.payment_hash &&
3372 broadcast_htlc.amount_msat == htlc.amount_msat)) {
3373 matched_htlc = true;
3374 break;
3375 }
3376 }
3377 if matched_htlc { continue; }
3378 if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
3379 continue;
3380 }
3381 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
3382 if entry.height != $commitment_tx_conf_height { return true; }
3383 match entry.event {
3384 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
3385 *update_source != **source
3386 },
3387 _ => true,
3388 }
3389 });
3390 let entry = OnchainEventEntry {
3391 txid: $commitment_txid_confirmed,
3392 transaction: Some($commitment_tx_confirmed.clone()),
3393 height: $commitment_tx_conf_height,
3394 block_hash: Some(*$commitment_tx_conf_hash),
3395 event: OnchainEvent::HTLCUpdate {
3396 source: (**source).clone(),
3397 payment_hash: htlc.payment_hash.clone(),
3398 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
3399 commitment_tx_output_idx: None,
3400 },
3401 };
3402 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
3403 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
3404 $commitment_txid_confirmed, entry.confirmation_threshold());
3405 $self.onchain_events_awaiting_threshold_conf.push(entry);
3406 }
3407 }
3408 }
3409 }
3410 }
3411 if let Some(ref txid) = $self.funding.current_counterparty_commitment_txid {
3412 check_htlc_fails!(txid, "current", $self.funding.counterparty_claimable_outpoints.get(txid));
3413 }
3414 if let Some(ref txid) = $self.funding.prev_counterparty_commitment_txid {
3415 check_htlc_fails!(txid, "previous", $self.funding.counterparty_claimable_outpoints.get(txid));
3416 }
3417 } }
3418}
3419
3420#[cfg(any(test, feature = "_test_utils"))]
3425pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
3426 use bitcoin::opcodes;
3427 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
3428 ret[131] = opcodes::all::OP_DROP.to_u8();
3429 ret[132] = opcodes::all::OP_DROP.to_u8();
3430 ret[133] = opcodes::all::OP_DROP.to_u8();
3431 ret[134] = opcodes::all::OP_DROP.to_u8();
3432 ret[135] = opcodes::OP_TRUE.to_u8();
3433 Vec::from(&ret[..])
3434}
3435
3436#[cfg(any(test, feature = "_test_utils"))]
3437#[rustfmt::skip]
3438pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
3439 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
3440}
3441
3442impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
3443 #[rustfmt::skip]
3446 fn closure_conf_target(&self) -> ConfirmationTarget {
3447 if holder_commitment_htlcs!(self, CURRENT).next().is_some() {
3451 return ConfirmationTarget::UrgentOnChainSweep;
3452 }
3453 if holder_commitment_htlcs!(self, PREV).map(|mut htlcs| htlcs.next().is_some()).unwrap_or(false) {
3454 return ConfirmationTarget::UrgentOnChainSweep;
3455 }
3456 if let Some(txid) = self.funding.current_counterparty_commitment_txid {
3457 if !self.funding.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
3458 return ConfirmationTarget::UrgentOnChainSweep;
3459 }
3460 }
3461 if let Some(txid) = self.funding.prev_counterparty_commitment_txid {
3462 if !self.funding.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
3463 return ConfirmationTarget::UrgentOnChainSweep;
3464 }
3465 }
3466 ConfirmationTarget::OutputSpendingFee
3467 }
3468
3469 #[rustfmt::skip]
3473 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
3474 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
3475 return Err("Previous secret did not match new one");
3476 }
3477
3478 let mut removed_fulfilled_htlcs = false;
3481 let prune_htlc_sources = |funding: &mut FundingScope| {
3482 if let Some(txid) = funding.prev_counterparty_commitment_txid.take() {
3483 if funding.current_counterparty_commitment_txid.unwrap() != txid {
3484 let cur_claimables = funding.counterparty_claimable_outpoints.get(
3485 &funding.current_counterparty_commitment_txid.unwrap()).unwrap();
3486 if !removed_fulfilled_htlcs {
3489 for (_, ref source_opt) in funding.counterparty_claimable_outpoints.get(&txid).unwrap() {
3490 if let Some(source) = source_opt {
3491 if !cur_claimables.iter()
3492 .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
3493 {
3494 self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
3495 }
3496 }
3497 }
3498 removed_fulfilled_htlcs = true;
3499 }
3500 for &mut (_, ref mut source_opt) in funding.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
3501 *source_opt = None;
3502 }
3503 } else {
3504 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
3505 }
3506 }
3507 };
3508 core::iter::once(&mut self.funding).chain(&mut self.pending_funding).for_each(prune_htlc_sources);
3509
3510 if !self.payment_preimages.is_empty() {
3511 let min_idx = self.get_min_seen_secret();
3512 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
3513
3514 self.payment_preimages.retain(|&k, _| {
3515 for htlc in holder_commitment_htlcs!(self, CURRENT) {
3516 if k == htlc.payment_hash {
3517 return true
3518 }
3519 }
3520 if let Some(htlcs) = holder_commitment_htlcs!(self, PREV) {
3521 for htlc in htlcs {
3522 if k == htlc.payment_hash {
3523 return true
3524 }
3525 }
3526 }
3527 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
3528 if *cn < min_idx {
3529 return true
3530 }
3531 true
3532 } else { false };
3533 if contains {
3534 counterparty_hash_commitment_number.remove(&k);
3535 }
3536 false
3537 });
3538 }
3539
3540 Ok(())
3541 }
3542
3543 #[rustfmt::skip]
3544 fn provide_initial_counterparty_commitment_tx(
3545 &mut self, commitment_tx: CommitmentTransaction,
3546 ) {
3547 self.initial_counterparty_commitment_info = Some((commitment_tx.per_commitment_point(),
3549 commitment_tx.negotiated_feerate_per_kw(), commitment_tx.to_broadcaster_value_sat(), commitment_tx.to_countersignatory_value_sat()));
3550
3551 #[cfg(debug_assertions)] {
3552 let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
3553 debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), commitment_tx.trust().txid());
3554 }
3555
3556 self.provide_latest_counterparty_commitment_tx(commitment_tx.trust().txid(), Vec::new(), commitment_tx.commitment_number(),
3557 commitment_tx.per_commitment_point());
3558 self.initial_counterparty_commitment_tx = Some(commitment_tx);
3560 }
3561
3562 #[rustfmt::skip]
3563 fn provide_latest_counterparty_commitment_tx(
3564 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
3565 commitment_number: u64, their_per_commitment_point: PublicKey,
3566 ) {
3567 for &(ref htlc, _) in &htlc_outputs {
3572 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
3573 }
3574
3575 self.funding.prev_counterparty_commitment_txid = self.funding.current_counterparty_commitment_txid.take();
3576 self.funding.current_counterparty_commitment_txid = Some(txid);
3577 self.funding.counterparty_claimable_outpoints.insert(txid, htlc_outputs);
3578 self.current_counterparty_commitment_number = commitment_number;
3579
3580 match self.their_cur_per_commitment_points {
3582 Some(old_points) => {
3583 if old_points.0 == commitment_number + 1 {
3584 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
3585 } else if old_points.0 == commitment_number + 2 {
3586 if let Some(old_second_point) = old_points.2 {
3587 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
3588 } else {
3589 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3590 }
3591 } else {
3592 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3593 }
3594 },
3595 None => {
3596 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
3597 }
3598 }
3599 }
3600
3601 fn update_counterparty_commitment_data(
3602 &mut self, commitment_txs: &[CommitmentTransaction], htlc_data: &CommitmentHTLCData,
3603 ) -> Result<(), &'static str> {
3604 self.verify_matching_commitment_transactions(commitment_txs.iter())?;
3605
3606 let htlcs_for_commitment = |commitment: &CommitmentTransaction| {
3607 debug_assert!(htlc_data.nondust_htlc_sources.len() <= commitment.nondust_htlcs().len());
3608 let mut nondust_htlcs = commitment.nondust_htlcs().iter();
3609 let mut sources = htlc_data.nondust_htlc_sources.iter();
3610 let nondust_htlcs = core::iter::from_fn(move || {
3611 let htlc = nondust_htlcs.next()?.clone();
3612 let source = (!htlc.offered).then(|| {
3613 let source = sources
3614 .next()
3615 .expect("Every inbound non-dust HTLC should have a corresponding source")
3616 .clone();
3617 Box::new(source)
3618 });
3619 Some((htlc, source))
3620 });
3621
3622 let dust_htlcs = htlc_data.dust_htlcs.iter().map(|(htlc, source)| {
3623 (htlc.clone(), source.as_ref().map(|source| Box::new(source.clone())))
3624 });
3625
3626 nondust_htlcs.chain(dust_htlcs).collect::<Vec<_>>()
3627 };
3628
3629 let current_funding_commitment_tx = commitment_txs.first().unwrap();
3630 self.provide_latest_counterparty_commitment_tx(
3631 current_funding_commitment_tx.trust().txid(),
3632 htlcs_for_commitment(current_funding_commitment_tx),
3633 current_funding_commitment_tx.commitment_number(),
3634 current_funding_commitment_tx.per_commitment_point(),
3635 );
3636
3637 for (pending_funding, commitment_tx) in
3638 self.pending_funding.iter_mut().zip(commitment_txs.iter().skip(1))
3639 {
3640 let commitment_txid = commitment_tx.trust().txid();
3641 pending_funding.prev_counterparty_commitment_txid =
3642 pending_funding.current_counterparty_commitment_txid.take();
3643 pending_funding.current_counterparty_commitment_txid = Some(commitment_txid);
3644 pending_funding
3645 .counterparty_claimable_outpoints
3646 .insert(commitment_txid, htlcs_for_commitment(commitment_tx));
3647 }
3648
3649 Ok(())
3650 }
3651
3652 #[rustfmt::skip]
3658 fn provide_latest_holder_commitment_tx(
3659 &mut self, holder_commitment_tx: HolderCommitmentTransaction,
3660 htlc_outputs: &[(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)],
3661 claimed_htlcs: &[(SentHTLCId, PaymentPreimage)], mut nondust_htlc_sources: Vec<HTLCSource>,
3662 ) -> Result<(), &'static str> {
3663 let dust_htlcs = if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
3664 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().nondust_htlcs().len());
3668 for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().nondust_htlcs().iter()) {
3669 debug_assert_eq!(a, b);
3670 }
3671 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
3672 for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
3673 debug_assert_eq!(a, b);
3674 }
3675
3676 debug_assert!(nondust_htlc_sources.is_empty());
3678 nondust_htlc_sources.reserve_exact(holder_commitment_tx.nondust_htlcs().len());
3679 htlc_outputs.iter().filter_map(|(htlc, _, source)| {
3680 if htlc.transaction_output_index.is_none() {
3683 return Some((htlc.clone(), source.clone()));
3684 }
3685 if htlc.offered {
3686 nondust_htlc_sources.push(source.clone().expect("Outbound HTLCs should have a source"));
3687 }
3688 None
3689 }).collect()
3690 } else {
3691 {
3695 let mut prev = -1;
3696 for htlc in holder_commitment_tx.trust().nondust_htlcs().iter() {
3697 assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
3698 prev = htlc.transaction_output_index.unwrap() as i32;
3699 }
3700 }
3701
3702 debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
3703 debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
3704 debug_assert_eq!(holder_commitment_tx.trust().nondust_htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
3705
3706 let mut sources = nondust_htlc_sources.iter();
3707 for htlc in holder_commitment_tx.trust().nondust_htlcs().iter() {
3708 if htlc.offered {
3709 let source = sources.next().expect("Non-dust HTLC sources didn't match commitment tx");
3710 assert!(source.possibly_matches_output(htlc));
3711 }
3712 }
3713 assert!(sources.next().is_none(), "All HTLC sources should have been exhausted");
3714
3715 htlc_outputs.iter().map(|(htlc, _, source)| (htlc.clone(), source.clone())).collect()
3717 };
3718
3719 let htlc_data = CommitmentHTLCData { nondust_htlc_sources, dust_htlcs };
3720 self.update_holder_commitment_data(vec![holder_commitment_tx], htlc_data, claimed_htlcs)
3721 }
3722
3723 fn verify_matching_commitment_transactions<
3724 'a,
3725 I: ExactSizeIterator<Item = &'a CommitmentTransaction>,
3726 >(
3727 &self, commitment_txs: I,
3728 ) -> Result<(), &'static str> {
3729 if self.pending_funding.len() + 1 != commitment_txs.len() {
3730 return Err("Commitment transaction count mismatch");
3731 }
3732
3733 let mut other_commitment_tx = None::<&CommitmentTransaction>;
3734 for (funding, commitment_tx) in
3735 core::iter::once(&self.funding).chain(self.pending_funding.iter()).zip(commitment_txs)
3736 {
3737 let trusted_tx = &commitment_tx.trust().built_transaction().transaction;
3738 if trusted_tx.input.len() != 1 {
3739 return Err("Commitment transactions must only spend one input");
3740 }
3741 let funding_outpoint_spent = trusted_tx.input[0].previous_output;
3742 if funding_outpoint_spent != funding.funding_outpoint().into_bitcoin_outpoint() {
3743 return Err("Commitment transaction spends invalid funding outpoint");
3744 }
3745
3746 if let Some(other_commitment_tx) = other_commitment_tx {
3747 if commitment_tx.commitment_number() != other_commitment_tx.commitment_number() {
3748 return Err("Commitment number mismatch");
3749 }
3750 if commitment_tx.per_commitment_point()
3751 != other_commitment_tx.per_commitment_point()
3752 {
3753 return Err("Per-commitment-point mismatch");
3754 }
3755 if commitment_tx.negotiated_feerate_per_kw()
3756 != other_commitment_tx.negotiated_feerate_per_kw()
3757 {
3758 return Err("Commitment fee rate mismatch");
3759 }
3760 let nondust_htlcs = commitment_tx.nondust_htlcs();
3761 let other_nondust_htlcs = other_commitment_tx.nondust_htlcs();
3762 if nondust_htlcs.len() != other_nondust_htlcs.len() {
3763 return Err("Non-dust HTLC count mismatch");
3764 }
3765 for (nondust_htlc, other_nondust_htlc) in
3766 nondust_htlcs.iter().zip(other_nondust_htlcs.iter())
3767 {
3768 if !nondust_htlc.is_data_equal(other_nondust_htlc) {
3769 return Err("Non-dust HTLC mismatch");
3770 }
3771 }
3772 }
3773
3774 other_commitment_tx = Some(commitment_tx);
3775 }
3776
3777 Ok(())
3778 }
3779
3780 fn update_holder_commitment_data(
3781 &mut self, commitment_txs: Vec<HolderCommitmentTransaction>,
3782 mut htlc_data: CommitmentHTLCData, claimed_htlcs: &[(SentHTLCId, PaymentPreimage)],
3783 ) -> Result<(), &'static str> {
3784 self.verify_matching_commitment_transactions(
3785 commitment_txs.iter().map(|holder_commitment_tx| holder_commitment_tx.deref()),
3786 )?;
3787
3788 let current_funding_commitment_tx = commitment_txs.first().unwrap();
3789 self.current_holder_commitment_number = current_funding_commitment_tx.commitment_number();
3790 self.onchain_tx_handler.provide_latest_holder_tx(current_funding_commitment_tx.clone());
3791 for (funding, mut commitment_tx) in core::iter::once(&mut self.funding)
3792 .chain(self.pending_funding.iter_mut())
3793 .zip(commitment_txs.into_iter())
3794 {
3795 mem::swap(&mut commitment_tx, &mut funding.current_holder_commitment_tx);
3796 funding.prev_holder_commitment_tx = Some(commitment_tx);
3797 }
3798
3799 mem::swap(&mut htlc_data, &mut self.current_holder_htlc_data);
3800 self.prev_holder_htlc_data = Some(htlc_data);
3801
3802 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
3803 #[cfg(debug_assertions)]
3804 {
3805 let cur_counterparty_htlcs = self
3806 .funding
3807 .counterparty_claimable_outpoints
3808 .get(&self.funding.current_counterparty_commitment_txid.unwrap())
3809 .unwrap();
3810 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
3811 if let Some(source) = source_opt {
3812 SentHTLCId::from_source(source) == *claimed_htlc_id
3813 } else {
3814 false
3815 }
3816 }));
3817 }
3818 self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
3819 }
3820
3821 Ok(())
3822 }
3823
3824 #[rustfmt::skip]
3829 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
3830 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage,
3831 payment_info: &Option<PaymentClaimDetails>, broadcaster: &B,
3832 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
3833 where B::Target: BroadcasterInterface,
3834 F::Target: FeeEstimator,
3835 L::Target: Logger,
3836 {
3837 self.payment_preimages.entry(payment_hash.clone())
3838 .and_modify(|(_, payment_infos)| {
3839 if let Some(payment_info) = payment_info {
3840 if !payment_infos.contains(&payment_info) {
3841 payment_infos.push(payment_info.clone());
3842 }
3843 }
3844 })
3845 .or_insert_with(|| {
3846 (payment_preimage.clone(), payment_info.clone().into_iter().collect())
3847 });
3848
3849 let confirmed_spend_info = self.funding_spend_confirmed
3850 .map(|txid| (txid, None))
3851 .or_else(|| {
3852 self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3853 OnchainEvent::FundingSpendConfirmation { .. } => Some((event.txid, Some(event.height))),
3854 _ => None,
3855 })
3856 });
3857 let (confirmed_spend_txid, confirmed_spend_height) =
3858 if let Some((txid, height)) = confirmed_spend_info {
3859 (txid, height)
3860 } else {
3861 return;
3862 };
3863 let funding_spent = get_confirmed_funding_scope!(self);
3864
3865 macro_rules! claim_htlcs {
3868 ($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3869 let htlc_claim_reqs = self.get_counterparty_output_claims_for_preimage(*payment_preimage, funding_spent, $commitment_number, $txid, $htlcs, confirmed_spend_height);
3870 let conf_target = self.closure_conf_target();
3871 self.onchain_tx_handler.update_claims_view_from_requests(
3872 htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster,
3873 conf_target, &self.destination_script, fee_estimator, logger,
3874 );
3875 }
3876 }
3877 if let Some(txid) = funding_spent.current_counterparty_commitment_txid {
3878 if txid == confirmed_spend_txid {
3879 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3880 claim_htlcs!(*commitment_number, txid, funding_spent.counterparty_claimable_outpoints.get(&txid));
3881 } else {
3882 debug_assert!(false);
3883 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3884 }
3885 return;
3886 }
3887 }
3888 if let Some(txid) = funding_spent.prev_counterparty_commitment_txid {
3889 if txid == confirmed_spend_txid {
3890 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3891 claim_htlcs!(*commitment_number, txid, funding_spent.counterparty_claimable_outpoints.get(&txid));
3892 } else {
3893 debug_assert!(false);
3894 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3895 }
3896 return;
3897 }
3898 }
3899
3900 if self.broadcasted_holder_revokable_script.is_some() {
3906 let holder_commitment_tx = if funding_spent.current_holder_commitment_tx.trust().txid() == confirmed_spend_txid {
3907 Some(&funding_spent.current_holder_commitment_tx)
3908 } else if let Some(prev_holder_commitment_tx) = &funding_spent.prev_holder_commitment_tx {
3909 if prev_holder_commitment_tx.trust().txid() == confirmed_spend_txid {
3910 Some(prev_holder_commitment_tx)
3911 } else {
3912 None
3913 }
3914 } else {
3915 None
3916 };
3917 if let Some(holder_commitment_tx) = holder_commitment_tx {
3918 let (claim_reqs, _) = self.get_broadcasted_holder_claims(
3922 funding_spent, holder_commitment_tx, self.best_block.height,
3923 );
3924 let conf_target = self.closure_conf_target();
3925 self.onchain_tx_handler.update_claims_view_from_requests(
3926 claim_reqs, self.best_block.height, self.best_block.height, broadcaster,
3927 conf_target, &self.destination_script, fee_estimator, logger,
3928 );
3929 }
3930 }
3931 }
3932
3933 #[rustfmt::skip]
3934 fn generate_claimable_outpoints_and_watch_outputs(
3935 &mut self, generate_monitor_event_with_reason: Option<ClosureReason>,
3936 require_funding_seen: bool,
3937 ) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3938 let funding = get_confirmed_funding_scope!(self);
3939 let holder_commitment_tx = &funding.current_holder_commitment_tx;
3940 let funding_outp = HolderFundingOutput::build(
3941 holder_commitment_tx.clone(),
3942 funding.channel_parameters.clone(),
3943 );
3944 let funding_outpoint = funding.funding_outpoint();
3945 let commitment_package = PackageTemplate::build_package(
3946 funding_outpoint.txid.clone(), funding_outpoint.index as u32,
3947 PackageSolvingData::HolderFundingOutput(funding_outp),
3948 self.best_block.height,
3949 );
3950 let mut claimable_outpoints = vec![commitment_package];
3951 if let Some(reason) = generate_monitor_event_with_reason {
3952 let event = MonitorEvent::HolderForceClosedWithInfo {
3953 reason,
3954 outpoint: funding_outpoint,
3955 channel_id: self.channel_id,
3956 };
3957 self.pending_monitor_events.push(event);
3958 }
3959
3960 self.holder_tx_signed = true;
3964
3965 if require_funding_seen && self.is_manual_broadcast && !self.funding_seen_onchain {
3968 return (Vec::new(), Vec::new());
3969 }
3970
3971 let mut watch_outputs = Vec::new();
3972 let zero_fee_htlcs =
3980 self.channel_type_features().supports_anchors_zero_fee_htlc_tx();
3981 let zero_fee_commitments =
3982 self.channel_type_features().supports_anchor_zero_fee_commitments();
3983 if !zero_fee_htlcs && !zero_fee_commitments {
3984 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3988 funding, holder_commitment_tx, self.best_block.height,
3989 );
3990 let new_outputs = self.get_broadcasted_holder_watch_outputs(holder_commitment_tx);
3991 if !new_outputs.is_empty() {
3992 watch_outputs.push((holder_commitment_tx.trust().txid(), new_outputs));
3993 }
3994 claimable_outpoints.append(&mut new_outpoints);
3995 }
3996 (claimable_outpoints, watch_outputs)
3997 }
3998
3999 #[rustfmt::skip]
4000 pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
4009 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>,
4010 require_funding_seen: bool,
4011 )
4012 where
4013 B::Target: BroadcasterInterface,
4014 F::Target: FeeEstimator,
4015 L::Target: Logger,
4016 {
4017 let reason = ClosureReason::HolderForceClosed {
4018 broadcasted_latest_txn: Some(true),
4019 message: "ChannelMonitor-initiated commitment transaction broadcast".to_owned(),
4020 };
4021 let (claimable_outpoints, _) =
4022 self.generate_claimable_outpoints_and_watch_outputs(Some(reason), require_funding_seen);
4023 if require_funding_seen && self.is_manual_broadcast && !self.funding_seen_onchain {
4026 log_info!(logger, "Not broadcasting holder commitment for manual-broadcast channel before funding appears on-chain");
4027 return;
4028 }
4029 let conf_target = self.closure_conf_target();
4030 self.onchain_tx_handler.update_claims_view_from_requests(
4031 claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
4032 conf_target, &self.destination_script, fee_estimator, logger,
4033 );
4034 }
4035
4036 fn renegotiated_funding<L: Deref>(
4037 &mut self, logger: &WithChannelMonitor<L>,
4038 channel_parameters: &ChannelTransactionParameters,
4039 alternative_holder_commitment_tx: &HolderCommitmentTransaction,
4040 alternative_counterparty_commitment_tx: &CommitmentTransaction,
4041 ) -> Result<(), ()>
4042 where
4043 L::Target: Logger,
4044 {
4045 let alternative_counterparty_commitment_txid =
4046 alternative_counterparty_commitment_tx.trust().txid();
4047
4048 let current_counterparty_commitment_htlcs =
4056 if let Some(txid) = &self.funding.current_counterparty_commitment_txid {
4057 self.funding.counterparty_claimable_outpoints.get(txid).unwrap()
4058 } else {
4059 debug_assert!(false);
4060 log_error!(
4061 logger,
4062 "Received funding renegotiation while initial funding negotiation is still pending"
4063 );
4064 return Err(());
4065 };
4066 let mut htlcs_with_sources = current_counterparty_commitment_htlcs.clone();
4067 let alternative_htlcs = alternative_counterparty_commitment_tx.nondust_htlcs();
4068
4069 let expected_non_dust_htlc_count = htlcs_with_sources
4070 .iter()
4071 .position(|(htlc, _)| htlc.transaction_output_index.is_none())
4074 .unwrap_or(htlcs_with_sources.len());
4075 if alternative_htlcs.len() != expected_non_dust_htlc_count {
4076 log_error!(
4077 logger,
4078 "Received alternative counterparty commitment with HTLC count mismatch"
4079 );
4080 return Err(());
4081 }
4082
4083 for (alternative_htlc, (htlc, _)) in
4084 alternative_htlcs.iter().zip(htlcs_with_sources.iter_mut())
4085 {
4086 debug_assert!(htlc.transaction_output_index.is_some());
4087 debug_assert!(alternative_htlc.transaction_output_index.is_some());
4088 if !alternative_htlc.is_data_equal(htlc) {
4089 log_error!(
4090 logger,
4091 "Received alternative counterparty commitment with non-dust HTLC mismatch"
4092 );
4093 return Err(());
4094 }
4095 htlc.transaction_output_index = alternative_htlc.transaction_output_index;
4096 }
4097
4098 let mut counterparty_claimable_outpoints = new_hash_map();
4099 counterparty_claimable_outpoints
4100 .insert(alternative_counterparty_commitment_txid, htlcs_with_sources);
4101
4102 let alternative_funding = FundingScope {
4104 channel_parameters: channel_parameters.clone(),
4105 current_counterparty_commitment_txid: Some(alternative_counterparty_commitment_txid),
4106 prev_counterparty_commitment_txid: None,
4107 counterparty_claimable_outpoints,
4108 current_holder_commitment_tx: alternative_holder_commitment_tx.clone(),
4109 prev_holder_commitment_tx: None,
4110 };
4111 let alternative_funding_outpoint = alternative_funding.funding_outpoint();
4112
4113 if self
4114 .pending_funding
4115 .iter()
4116 .any(|funding| funding.funding_txid() == alternative_funding_outpoint.txid)
4117 {
4118 log_error!(
4119 logger,
4120 "Renegotiated funding transaction with a duplicate funding txid {}",
4121 alternative_funding_outpoint.txid
4122 );
4123 return Err(());
4124 }
4125
4126 if let Some(parent_funding_txid) = channel_parameters.splice_parent_funding_txid.as_ref() {
4127 if !self.pending_funding.is_empty() {
4130 log_error!(
4131 logger,
4132 "Negotiated splice while channel is pending channel_ready/splice_locked"
4133 );
4134 return Err(());
4135 }
4136 if *parent_funding_txid != self.funding.funding_txid() {
4137 log_error!(
4138 logger,
4139 "Negotiated splice that does not spend currently locked funding transaction"
4140 );
4141 return Err(());
4142 }
4143 } else if self.funding.is_splice() {
4144 return Err(());
4147 }
4148
4149 let script_pubkey = channel_parameters.make_funding_redeemscript().to_p2wsh();
4150 self.outputs_to_watch.insert(
4151 alternative_funding_outpoint.txid,
4152 vec![(alternative_funding_outpoint.index as u32, script_pubkey)],
4153 );
4154 self.pending_funding.push(alternative_funding);
4155
4156 Ok(())
4157 }
4158
4159 fn promote_funding(&mut self, new_funding_txid: Txid) -> Result<(), ()> {
4160 let prev_funding_txid = self.funding.funding_txid();
4161
4162 let new_funding = self
4163 .pending_funding
4164 .iter_mut()
4165 .find(|funding| funding.funding_txid() == new_funding_txid);
4166 if new_funding.is_none() {
4167 return Err(());
4168 }
4169 let mut new_funding = new_funding.unwrap();
4170
4171 mem::swap(&mut self.funding, &mut new_funding);
4172 self.onchain_tx_handler.update_after_renegotiated_funding_locked(
4173 self.funding.channel_parameters.clone(),
4174 self.funding.current_holder_commitment_tx.clone(),
4175 self.funding.prev_holder_commitment_tx.clone(),
4176 );
4177
4178 if self.funding.prev_holder_commitment_tx.is_none() {
4183 self.prev_holder_htlc_data.take();
4184 }
4185
4186 let no_further_updates_allowed = self.no_further_updates_allowed();
4187
4188 for funding in self.pending_funding.drain(..) {
4190 let funding_txid = funding.funding_txid();
4191 self.outputs_to_watch.remove(&funding_txid);
4192 if no_further_updates_allowed && funding_txid != prev_funding_txid {
4193 self.pending_events.push(Event::DiscardFunding {
4194 channel_id: self.channel_id,
4195 funding_info: crate::events::FundingInfo::OutPoint {
4196 outpoint: funding.funding_outpoint(),
4197 },
4198 });
4199 }
4200 }
4201 if let Some((alternative_funding_txid, _)) = self.alternative_funding_confirmed.take() {
4202 debug_assert_eq!(alternative_funding_txid, new_funding_txid);
4206 }
4207
4208 Ok(())
4209 }
4210
4211 #[rustfmt::skip]
4212 fn update_monitor<B: Deref, F: Deref, L: Deref>(
4213 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
4214 ) -> Result<(), ()>
4215 where B::Target: BroadcasterInterface,
4216 F::Target: FeeEstimator,
4217 L::Target: Logger,
4218 {
4219 if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4220 log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
4221 log_funding_info!(self), updates.updates.len());
4222 } else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4223 log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
4224 log_funding_info!(self), updates.updates.len());
4225 } else {
4226 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
4227 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
4228 }
4229
4230 if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
4239 assert_eq!(updates.updates.len(), 1);
4240 match updates.updates[0] {
4241 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
4242 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
4243 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
4246 debug_assert!(self.lockdown_from_offchain),
4247 _ => {
4248 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
4249 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
4250 },
4251 }
4252 }
4253 if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
4254 if self.latest_update_id + 1 != updates.update_id {
4255 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
4256 }
4257 }
4258 let mut ret = Ok(());
4259 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
4260 for update in updates.updates.iter() {
4261 match update {
4262 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
4263 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
4264 if self.lockdown_from_offchain { panic!(); }
4265 if let Err(e) = self.provide_latest_holder_commitment_tx(
4266 commitment_tx.clone(), htlc_outputs, &claimed_htlcs,
4267 nondust_htlc_sources.clone()
4268 ) {
4269 log_error!(logger, "Failed updating latest holder commitment transaction info: {}", e);
4270 ret = Err(());
4271 }
4272 }
4273 ChannelMonitorUpdateStep::LatestHolderCommitment {
4274 commitment_txs, htlc_data, claimed_htlcs,
4275 } => {
4276 log_trace!(logger, "Updating ChannelMonitor with {} latest holder commitment(s)", commitment_txs.len());
4277 assert!(!self.lockdown_from_offchain);
4278 if let Err(e) = self.update_holder_commitment_data(
4279 commitment_txs.clone(), htlc_data.clone(), claimed_htlcs,
4280 ) {
4281 log_error!(logger, "Failed updating latest holder commitment state: {}", e);
4282 ret = Err(());
4283 }
4284 },
4285 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
4289 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
4290 if self.pending_funding.is_empty() {
4291 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point)
4292 } else {
4293 log_error!(logger, "Received unexpected non-splice counterparty commitment monitor update");
4294 ret = Err(());
4295 }
4296 },
4297 ChannelMonitorUpdateStep::LatestCounterpartyCommitment {
4298 commitment_txs, htlc_data,
4299 } => {
4300 log_trace!(logger, "Updating ChannelMonitor with {} latest counterparty commitments", commitment_txs.len());
4301 if let Err(e) = self.update_counterparty_commitment_data(commitment_txs, htlc_data) {
4302 log_error!(logger, "Failed updating latest counterparty commitment state: {}", e);
4303 ret = Err(());
4304 }
4305 },
4306 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
4307 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
4308 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
4309 },
4310 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
4311 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
4312 if let Err(e) = self.provide_secret(*idx, *secret) {
4313 debug_assert!(false, "Latest counterparty commitment secret was invalid");
4314 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
4315 log_error!(logger, " {}", e);
4316 ret = Err(());
4317 }
4318 },
4319 ChannelMonitorUpdateStep::RenegotiatedFunding {
4320 channel_parameters, holder_commitment_tx, counterparty_commitment_tx,
4321 } => {
4322 log_trace!(logger, "Updating ChannelMonitor with alternative holder and counterparty commitment transactions for funding txid {}",
4323 channel_parameters.funding_outpoint.unwrap().txid);
4324 if let Err(_) = self.renegotiated_funding(
4325 logger, channel_parameters, holder_commitment_tx, counterparty_commitment_tx,
4326 ) {
4327 ret = Err(());
4328 }
4329 },
4330 ChannelMonitorUpdateStep::RenegotiatedFundingLocked { funding_txid } => {
4331 log_trace!(logger, "Updating ChannelMonitor with locked renegotiated funding txid {}", funding_txid);
4332 if let Err(_) = self.promote_funding(*funding_txid) {
4333 log_error!(logger, "Unknown funding with txid {} became locked", funding_txid);
4334 ret = Err(());
4335 }
4336 },
4337 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
4338 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
4339 self.lockdown_from_offchain = true;
4340 if *should_broadcast {
4341 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
4345 self.onchain_events_awaiting_threshold_conf.iter().any(
4346 |event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
4347 if detected_funding_spend {
4348 log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
4349 continue;
4350 }
4351 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger, true);
4352 } else if !self.holder_tx_signed {
4353 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
4354 log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
4355 log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
4356 } else {
4357 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
4361 }
4362 },
4363 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
4364 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
4365 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
4366 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
4367 }
4368 },
4369 ChannelMonitorUpdateStep::ReleasePaymentComplete { htlc } => {
4370 log_trace!(logger, "HTLC {htlc:?} permanently and fully resolved");
4371 self.htlcs_resolved_to_user.insert(*htlc);
4372 },
4373 }
4374 }
4375
4376 #[cfg(debug_assertions)] {
4377 self.counterparty_commitment_txs_from_update(updates);
4378 }
4379
4380 self.latest_update_id = updates.update_id;
4381
4382 let mut is_pre_close_update = false;
4386 for update in updates.updates.iter() {
4387 match update {
4388 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
4389 |ChannelMonitorUpdateStep::LatestHolderCommitment { .. }
4390 |ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
4391 |ChannelMonitorUpdateStep::LatestCounterpartyCommitment { .. }
4392 |ChannelMonitorUpdateStep::ShutdownScript { .. }
4393 |ChannelMonitorUpdateStep::CommitmentSecret { .. }
4394 |ChannelMonitorUpdateStep::RenegotiatedFunding { .. }
4395 |ChannelMonitorUpdateStep::RenegotiatedFundingLocked { .. } =>
4396 is_pre_close_update = true,
4397 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
4403 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
4404 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
4405 }
4406 }
4407
4408 if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
4409 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
4410 Err(())
4411 } else { ret }
4412 }
4413
4414 fn is_closed_without_updates(&self) -> bool {
4417 let mut commitment_not_advanced =
4418 self.current_counterparty_commitment_number == INITIAL_COMMITMENT_NUMBER;
4419 commitment_not_advanced &=
4420 self.current_holder_commitment_number == INITIAL_COMMITMENT_NUMBER;
4421 (self.holder_tx_signed || self.lockdown_from_offchain) && commitment_not_advanced
4422 }
4423
4424 fn no_further_updates_allowed(&self) -> bool {
4425 self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
4426 }
4427
4428 fn get_latest_update_id(&self) -> u64 {
4429 self.latest_update_id
4430 }
4431
4432 #[rustfmt::skip]
4435 fn get_funding_txo(&self) -> OutPoint {
4436 self.funding.channel_parameters.funding_outpoint
4437 .expect("Funding outpoint must be set for active monitor")
4438 }
4439
4440 fn get_funding_script(&self) -> ScriptBuf {
4443 self.funding.channel_parameters.make_funding_redeemscript().to_p2wsh()
4444 }
4445
4446 pub fn channel_id(&self) -> ChannelId {
4447 self.channel_id
4448 }
4449
4450 fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
4451 for txid in self.counterparty_commitment_txn_on_chain.keys() {
4455 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
4456 }
4457 &self.outputs_to_watch
4458 }
4459
4460 fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
4461 let mut ret = Vec::new();
4462 mem::swap(&mut ret, &mut self.pending_monitor_events);
4463 ret
4464 }
4465
4466 #[rustfmt::skip]
4470 pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
4471 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
4472 let mut ret = Vec::with_capacity(pending_claim_events.len());
4473 for (claim_id, claim_event) in pending_claim_events {
4474 match claim_event {
4475 ClaimEvent::BumpCommitment {
4476 package_target_feerate_sat_per_1000_weight, commitment_tx,
4477 commitment_tx_fee_satoshis, pending_nondust_htlcs, anchor_output_idx,
4478 channel_parameters,
4479 } => {
4480 let channel_id = self.channel_id;
4481 let counterparty_node_id = self.counterparty_node_id;
4482 let commitment_txid = commitment_tx.compute_txid();
4483 ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
4484 channel_id,
4485 counterparty_node_id,
4486 claim_id,
4487 package_target_feerate_sat_per_1000_weight,
4488 anchor_descriptor: AnchorDescriptor {
4489 channel_derivation_parameters: ChannelDerivationParameters {
4490 keys_id: self.channel_keys_id,
4491 value_satoshis: channel_parameters.channel_value_satoshis,
4492 transaction_parameters: channel_parameters,
4493 },
4494 outpoint: BitcoinOutPoint {
4495 txid: commitment_txid,
4496 vout: anchor_output_idx,
4497 },
4498 value: commitment_tx.output[anchor_output_idx as usize].value,
4499 },
4500 pending_htlcs: pending_nondust_htlcs,
4501 commitment_tx,
4502 commitment_tx_fee_satoshis,
4503 }));
4504 },
4505 ClaimEvent::BumpHTLC {
4506 target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
4507 } => {
4508 let channel_id = self.channel_id;
4509 let counterparty_node_id = self.counterparty_node_id;
4510 ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
4511 channel_id,
4512 counterparty_node_id,
4513 claim_id,
4514 target_feerate_sat_per_1000_weight,
4515 htlc_descriptors: htlcs,
4516 tx_lock_time,
4517 }));
4518 }
4519 }
4520 }
4521 ret
4522 }
4523
4524 fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
4525 self.initial_counterparty_commitment_tx.clone().or_else(|| {
4526 self.initial_counterparty_commitment_info.map(
4529 |(
4530 their_per_commitment_point,
4531 feerate_per_kw,
4532 to_broadcaster_value,
4533 to_countersignatory_value,
4534 )| {
4535 let nondust_htlcs = vec![];
4536 debug_assert!(self.pending_funding.is_empty());
4540 let channel_parameters = &self.funding.channel_parameters;
4541
4542 let commitment_tx = self.build_counterparty_commitment_tx(
4543 channel_parameters,
4544 INITIAL_COMMITMENT_NUMBER,
4545 &their_per_commitment_point,
4546 to_broadcaster_value,
4547 to_countersignatory_value,
4548 feerate_per_kw,
4549 nondust_htlcs,
4550 );
4551 self.initial_counterparty_commitment_tx = Some(commitment_tx.clone());
4553 commitment_tx
4554 },
4555 )
4556 })
4557 }
4558
4559 #[rustfmt::skip]
4560 fn build_counterparty_commitment_tx(
4561 &self, channel_parameters: &ChannelTransactionParameters, commitment_number: u64,
4562 their_per_commitment_point: &PublicKey, to_broadcaster_value: u64,
4563 to_countersignatory_value: u64, feerate_per_kw: u32,
4564 nondust_htlcs: Vec<HTLCOutputInCommitment>
4565 ) -> CommitmentTransaction {
4566 let channel_parameters = &channel_parameters.as_counterparty_broadcastable();
4567 CommitmentTransaction::new(commitment_number, their_per_commitment_point,
4568 to_broadcaster_value, to_countersignatory_value, feerate_per_kw, nondust_htlcs, channel_parameters, &self.onchain_tx_handler.secp_ctx)
4569 }
4570
4571 #[rustfmt::skip]
4572 fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
4573 update.updates.iter().filter_map(|update| {
4574 match update {
4578 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
4579 ref htlc_outputs, commitment_number, their_per_commitment_point,
4580 feerate_per_kw: Some(feerate_per_kw),
4581 to_broadcaster_value_sat: Some(to_broadcaster_value),
4582 to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
4583
4584 let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
4585 htlc.transaction_output_index.map(|_| htlc).cloned()
4586 }).collect::<Vec<_>>();
4587
4588 debug_assert!(self.pending_funding.is_empty());
4592 let channel_parameters = &self.funding.channel_parameters;
4593 let commitment_tx = self.build_counterparty_commitment_tx(
4594 channel_parameters,
4595 commitment_number,
4596 &their_per_commitment_point,
4597 to_broadcaster_value,
4598 to_countersignatory_value,
4599 feerate_per_kw,
4600 nondust_htlcs,
4601 );
4602
4603 debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
4604
4605 Some(vec![commitment_tx])
4606 },
4607 &ChannelMonitorUpdateStep::LatestCounterpartyCommitment { ref commitment_txs, .. } => {
4608 Some(commitment_txs.clone())
4609 },
4610 &ChannelMonitorUpdateStep::RenegotiatedFunding { ref counterparty_commitment_tx, .. } => {
4611 Some(vec![counterparty_commitment_tx.clone()])
4612 },
4613 _ => None,
4614 }
4615 }).flatten().collect()
4616 }
4617
4618 #[rustfmt::skip]
4619 fn sign_to_local_justice_tx(
4620 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
4621 ) -> Result<Transaction, ()> {
4622 let secret = self.get_secret(commitment_number).ok_or(())?;
4623 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
4624 let their_per_commitment_point = PublicKey::from_secret_key(
4625 &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4626
4627 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
4628 &self.holder_revocation_basepoint, &their_per_commitment_point);
4629 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
4630 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
4631 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
4632 self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
4633
4634 let commitment_txid = &justice_tx.input[input_idx].previous_output.txid;
4635 let channel_parameters = core::iter::once(&self.funding)
4641 .chain(&self.pending_funding)
4642 .find(|funding| funding.counterparty_claimable_outpoints.contains_key(commitment_txid))
4643 .map(|funding| &funding.channel_parameters)
4644 .ok_or(())?;
4645 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
4646 &channel_parameters, &justice_tx, input_idx, value, &per_commitment_key,
4647 &self.onchain_tx_handler.secp_ctx,
4648 )?;
4649 justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
4650 justice_tx.input[input_idx].witness.push(&[1u8]);
4651 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
4652 Ok(justice_tx)
4653 }
4654
4655 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
4657 self.commitment_secrets.get_secret(idx)
4658 }
4659
4660 fn get_min_seen_secret(&self) -> u64 {
4661 self.commitment_secrets.get_min_seen_secret()
4662 }
4663
4664 fn get_cur_counterparty_commitment_number(&self) -> u64 {
4665 self.current_counterparty_commitment_number
4666 }
4667
4668 fn get_cur_holder_commitment_number(&self) -> u64 {
4669 self.current_holder_commitment_number
4670 }
4671
4672 #[rustfmt::skip]
4680 fn check_spend_counterparty_transaction<L: Deref>(&mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
4681 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
4682 where L::Target: Logger {
4683 let mut claimable_outpoints = Vec::new();
4686 let mut to_counterparty_output_info = None;
4687
4688 let funding_spent = get_confirmed_funding_scope!(self);
4689 let per_commitment_option = funding_spent.counterparty_claimable_outpoints.get(&commitment_txid);
4690
4691 macro_rules! ignore_error {
4692 ( $thing : expr ) => {
4693 match $thing {
4694 Ok(a) => a,
4695 Err(_) => return (claimable_outpoints, to_counterparty_output_info)
4696 }
4697 };
4698 }
4699
4700 let funding_txid_spent = commitment_tx.input[0].previous_output.txid;
4701 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);
4702 if commitment_number >= self.get_min_seen_secret() {
4703 assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
4704
4705 let secret = self.get_secret(commitment_number).unwrap();
4706 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
4707 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4708 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point,);
4709 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));
4710
4711 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
4712 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
4713
4714 for (idx, outp) in commitment_tx.output.iter().enumerate() {
4716 if outp.script_pubkey == revokeable_p2wsh {
4717 let revk_outp = RevokedOutput::build(
4718 per_commitment_point, per_commitment_key, outp.value,
4719 funding_spent.channel_parameters.clone(), height,
4720 );
4721 let justice_package = PackageTemplate::build_package(
4722 commitment_txid, idx as u32,
4723 PackageSolvingData::RevokedOutput(revk_outp),
4724 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
4725 );
4726 claimable_outpoints.push(justice_package);
4727 to_counterparty_output_info =
4728 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
4729 }
4730 }
4731
4732 if let Some(per_commitment_claimable_data) = per_commitment_option {
4734 for (htlc, _) in per_commitment_claimable_data {
4735 if let Some(transaction_output_index) = htlc.transaction_output_index {
4736 if transaction_output_index as usize >= commitment_tx.output.len() ||
4737 commitment_tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
4738 return (claimable_outpoints, to_counterparty_output_info);
4740 }
4741 let revk_htlc_outp = RevokedHTLCOutput::build(
4742 per_commitment_point, per_commitment_key, htlc.clone(),
4743 funding_spent.channel_parameters.clone(), height,
4744 );
4745 let counterparty_spendable_height = if htlc.offered {
4746 htlc.cltv_expiry
4747 } else {
4748 height
4749 };
4750 let justice_package = PackageTemplate::build_package(
4751 commitment_txid,
4752 transaction_output_index,
4753 PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
4754 counterparty_spendable_height,
4755 );
4756 claimable_outpoints.push(justice_package);
4757 }
4758 }
4759 }
4760
4761 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());
4765 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
4766
4767 if let Some(per_commitment_claimable_data) = per_commitment_option {
4768 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, commitment_tx, height,
4769 block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
4770 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
4771 ), logger);
4772 } else {
4773 debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
4778 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, commitment_tx, height,
4779 block_hash, [].iter().map(|reference| *reference), logger);
4780 }
4781 }
4782 } else if let Some(per_commitment_claimable_data) = per_commitment_option {
4783 assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
4784
4785 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
4793
4794 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
4795 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, commitment_tx, height, block_hash,
4796 per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
4797 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
4798 ), logger);
4799 let (htlc_claim_reqs, counterparty_output_info) =
4800 self.get_counterparty_output_claim_info(funding_spent, commitment_number, commitment_txid, commitment_tx, per_commitment_claimable_data, Some(height));
4801 to_counterparty_output_info = counterparty_output_info;
4802 for req in htlc_claim_reqs {
4803 claimable_outpoints.push(req);
4804 }
4805 }
4806
4807 (claimable_outpoints, to_counterparty_output_info)
4808 }
4809
4810 fn get_point_for_commitment_number(&self, commitment_number: u64) -> Option<PublicKey> {
4811 let per_commitment_points = &self.their_cur_per_commitment_points?;
4812
4813 if per_commitment_points.0 == commitment_number {
4816 Some(per_commitment_points.1)
4817 } else if let Some(point) = per_commitment_points.2.as_ref() {
4818 if per_commitment_points.0 == commitment_number + 1 {
4822 Some(*point)
4823 } else {
4824 None
4825 }
4826 } else {
4827 None
4828 }
4829 }
4830
4831 fn get_counterparty_output_claims_for_preimage(
4832 &self, preimage: PaymentPreimage, funding_spent: &FundingScope, commitment_number: u64,
4833 commitment_txid: Txid,
4834 per_commitment_option: Option<&Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
4835 confirmation_height: Option<u32>,
4836 ) -> Vec<PackageTemplate> {
4837 let per_commitment_claimable_data = match per_commitment_option {
4838 Some(outputs) => outputs,
4839 None => return Vec::new(),
4840 };
4841 let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
4842 Some(point) => point,
4843 None => return Vec::new(),
4844 };
4845
4846 let matching_payment_hash = PaymentHash::from(preimage);
4847 per_commitment_claimable_data
4848 .iter()
4849 .filter_map(|(htlc, _)| {
4850 if let Some(transaction_output_index) = htlc.transaction_output_index {
4851 if htlc.offered && htlc.payment_hash == matching_payment_hash {
4852 let htlc_data = PackageSolvingData::CounterpartyOfferedHTLCOutput(
4853 CounterpartyOfferedHTLCOutput::build(
4854 per_commitment_point,
4855 preimage,
4856 htlc.clone(),
4857 funding_spent.channel_parameters.clone(),
4858 confirmation_height,
4859 ),
4860 );
4861 Some(PackageTemplate::build_package(
4862 commitment_txid,
4863 transaction_output_index,
4864 htlc_data,
4865 htlc.cltv_expiry,
4866 ))
4867 } else {
4868 None
4869 }
4870 } else {
4871 None
4872 }
4873 })
4874 .collect()
4875 }
4876
4877 fn get_counterparty_output_claim_info(
4879 &self, funding_spent: &FundingScope, commitment_number: u64, commitment_txid: Txid,
4880 tx: &Transaction,
4881 per_commitment_claimable_data: &[(HTLCOutputInCommitment, Option<Box<HTLCSource>>)],
4882 confirmation_height: Option<u32>,
4883 ) -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
4884 let mut claimable_outpoints = Vec::new();
4885 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
4886
4887 let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
4888 Some(point) => point,
4889 None => return (claimable_outpoints, to_counterparty_output_info),
4890 };
4891
4892 let revocation_pubkey = RevocationKey::from_basepoint(
4893 &self.onchain_tx_handler.secp_ctx,
4894 &self.holder_revocation_basepoint,
4895 &per_commitment_point,
4896 );
4897 let delayed_key = DelayedPaymentKey::from_basepoint(
4898 &self.onchain_tx_handler.secp_ctx,
4899 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
4900 &per_commitment_point,
4901 );
4902 let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(
4903 &revocation_pubkey,
4904 self.counterparty_commitment_params.on_counterparty_tx_csv,
4905 &delayed_key,
4906 )
4907 .to_p2wsh();
4908 for (idx, outp) in tx.output.iter().enumerate() {
4909 if outp.script_pubkey == revokeable_p2wsh {
4910 to_counterparty_output_info =
4911 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
4912 }
4913 }
4914
4915 for &(ref htlc, _) in per_commitment_claimable_data.iter() {
4916 if let Some(transaction_output_index) = htlc.transaction_output_index {
4917 if transaction_output_index as usize >= tx.output.len()
4918 || tx.output[transaction_output_index as usize].value
4919 != htlc.to_bitcoin_amount()
4920 {
4921 return (claimable_outpoints, to_counterparty_output_info);
4923 }
4924 let preimage = if htlc.offered {
4925 if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) {
4926 Some(*p)
4927 } else {
4928 None
4929 }
4930 } else {
4931 None
4932 };
4933 if preimage.is_some() || !htlc.offered {
4934 let counterparty_htlc_outp = if htlc.offered {
4935 PackageSolvingData::CounterpartyOfferedHTLCOutput(
4936 CounterpartyOfferedHTLCOutput::build(
4937 per_commitment_point,
4938 preimage.unwrap(),
4939 htlc.clone(),
4940 funding_spent.channel_parameters.clone(),
4941 confirmation_height,
4942 ),
4943 )
4944 } else {
4945 PackageSolvingData::CounterpartyReceivedHTLCOutput(
4946 CounterpartyReceivedHTLCOutput::build(
4947 per_commitment_point,
4948 htlc.clone(),
4949 funding_spent.channel_parameters.clone(),
4950 confirmation_height,
4951 ),
4952 )
4953 };
4954 let counterparty_package = PackageTemplate::build_package(
4955 commitment_txid,
4956 transaction_output_index,
4957 counterparty_htlc_outp,
4958 htlc.cltv_expiry,
4959 );
4960 claimable_outpoints.push(counterparty_package);
4961 }
4962 }
4963 }
4964
4965 (claimable_outpoints, to_counterparty_output_info)
4966 }
4967
4968 #[rustfmt::skip]
4970 fn check_spend_counterparty_htlc<L: Deref>(
4971 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
4972 ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
4973 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
4974 let per_commitment_key = match SecretKey::from_slice(&secret) {
4975 Ok(key) => key,
4976 Err(_) => return (Vec::new(), None)
4977 };
4978 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
4979
4980 let funding_spent = get_confirmed_funding_scope!(self);
4981 debug_assert!(funding_spent.counterparty_claimable_outpoints.contains_key(commitment_txid));
4982
4983 let htlc_txid = tx.compute_txid();
4984 let mut claimable_outpoints = vec![];
4985 let mut outputs_to_watch = None;
4986 for (idx, input) in tx.input.iter().enumerate() {
4997 if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
4998 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
4999 let revk_outp = RevokedOutput::build(
5000 per_commitment_point, per_commitment_key, tx.output[idx].value,
5001 self.funding.channel_parameters.clone(), height,
5002 );
5003 let justice_package = PackageTemplate::build_package(
5004 htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
5005 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
5006 );
5007 claimable_outpoints.push(justice_package);
5008 if outputs_to_watch.is_none() {
5009 outputs_to_watch = Some((htlc_txid, vec![]));
5010 }
5011 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
5012 }
5013 }
5014 (claimable_outpoints, outputs_to_watch)
5015 }
5016
5017 #[rustfmt::skip]
5018 fn get_broadcasted_holder_htlc_descriptors(
5019 &self, funding: &FundingScope, holder_tx: &HolderCommitmentTransaction,
5020 ) -> Vec<HTLCDescriptor> {
5021 let tx = holder_tx.trust();
5022 let mut htlcs = Vec::with_capacity(holder_tx.nondust_htlcs().len());
5023 debug_assert_eq!(holder_tx.nondust_htlcs().len(), holder_tx.counterparty_htlc_sigs.len());
5024 for (htlc, counterparty_sig) in holder_tx.nondust_htlcs().iter().zip(holder_tx.counterparty_htlc_sigs.iter()) {
5025 assert!(htlc.transaction_output_index.is_some(), "Expected transaction output index for non-dust HTLC");
5026
5027 let preimage = if htlc.offered {
5028 None
5029 } else if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
5030 Some(*preimage)
5031 } else {
5032 continue;
5034 };
5035
5036 htlcs.push(HTLCDescriptor {
5037 channel_derivation_parameters: ChannelDerivationParameters {
5038 value_satoshis: funding.channel_parameters.channel_value_satoshis,
5039 keys_id: self.channel_keys_id,
5040 transaction_parameters: funding.channel_parameters.clone(),
5041 },
5042 commitment_txid: tx.txid(),
5043 per_commitment_number: tx.commitment_number(),
5044 per_commitment_point: tx.per_commitment_point(),
5045 feerate_per_kw: tx.negotiated_feerate_per_kw(),
5046 htlc: htlc.clone(),
5047 preimage,
5048 counterparty_sig: *counterparty_sig,
5049 });
5050 }
5051
5052 htlcs
5053 }
5054
5055 #[rustfmt::skip]
5059 fn get_broadcasted_holder_claims(
5060 &self, funding: &FundingScope, holder_tx: &HolderCommitmentTransaction, conf_height: u32,
5061 ) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
5062 let tx = holder_tx.trust();
5063 let keys = tx.keys();
5064 let redeem_script = chan_utils::get_revokeable_redeemscript(
5065 &keys.revocation_key, self.on_holder_tx_csv, &keys.broadcaster_delayed_payment_key,
5066 );
5067 let broadcasted_holder_revokable_script = Some((
5068 redeem_script.to_p2wsh(), holder_tx.per_commitment_point(), keys.revocation_key.clone(),
5069 ));
5070
5071 let claim_requests = self.get_broadcasted_holder_htlc_descriptors(funding, holder_tx).into_iter()
5072 .map(|htlc_descriptor| {
5073 let counterparty_spendable_height = if htlc_descriptor.htlc.offered {
5074 conf_height
5075 } else {
5076 htlc_descriptor.htlc.cltv_expiry
5077 };
5078 let transaction_output_index = htlc_descriptor.htlc.transaction_output_index
5079 .expect("Expected transaction output index for non-dust HTLC");
5080 PackageTemplate::build_package(
5081 tx.txid(), transaction_output_index,
5082 PackageSolvingData::HolderHTLCOutput(HolderHTLCOutput::build(htlc_descriptor, conf_height)),
5083 counterparty_spendable_height,
5084 )
5085 })
5086 .collect();
5087
5088 (claim_requests, broadcasted_holder_revokable_script)
5089 }
5090
5091 #[rustfmt::skip]
5093 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderCommitmentTransaction) -> Vec<(u32, TxOut)> {
5094 let mut watch_outputs = Vec::with_capacity(holder_tx.nondust_htlcs().len());
5095 let tx = holder_tx.trust();
5096 for htlc in holder_tx.nondust_htlcs() {
5097 if let Some(transaction_output_index) = htlc.transaction_output_index {
5098 watch_outputs.push((
5099 transaction_output_index,
5100 tx.built_transaction().transaction.output[transaction_output_index as usize].clone(),
5101 ));
5102 } else {
5103 debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5104 }
5105 }
5106 watch_outputs
5107 }
5108
5109 fn check_spend_holder_transaction<L: Deref>(
5114 &mut self, commitment_txid: Txid, commitment_tx: &Transaction, height: u32,
5115 block_hash: &BlockHash, logger: &L,
5116 ) -> Option<(Vec<PackageTemplate>, TransactionOutputs)>
5117 where
5118 L::Target: Logger,
5119 {
5120 let funding_spent = get_confirmed_funding_scope!(self);
5121
5122 let holder_commitment_tx = Some((&funding_spent.current_holder_commitment_tx, true))
5124 .filter(|(current_holder_commitment_tx, _)| {
5125 current_holder_commitment_tx.trust().txid() == commitment_txid
5126 })
5127 .or_else(|| {
5128 funding_spent
5129 .prev_holder_commitment_tx
5130 .as_ref()
5131 .map(|prev_holder_commitment_tx| (prev_holder_commitment_tx, false))
5132 .filter(|(prev_holder_commitment_tx, _)| {
5133 prev_holder_commitment_tx.trust().txid() == commitment_txid
5134 })
5135 });
5136
5137 if let Some((holder_commitment_tx, current)) = holder_commitment_tx {
5138 let funding_txid_spent = commitment_tx.input[0].previous_output.txid;
5139 assert_eq!(funding_spent.funding_txid(), funding_txid_spent);
5140
5141 let current_msg = if current { "latest holder" } else { "previous holder" };
5142 log_info!(logger, "Got broadcast of {current_msg} commitment tx {commitment_txid}, searching for available HTLCs to claim");
5143
5144 let (claim_requests, broadcasted_holder_revokable_script) =
5145 self.get_broadcasted_holder_claims(funding_spent, holder_commitment_tx, height);
5146 self.broadcasted_holder_revokable_script = broadcasted_holder_revokable_script;
5147 let watch_outputs = self.get_broadcasted_holder_watch_outputs(holder_commitment_tx);
5148
5149 if current {
5150 fail_unbroadcast_htlcs!(
5151 self,
5152 current_msg,
5153 commitment_txid,
5154 commitment_tx,
5155 height,
5156 block_hash,
5157 holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES),
5158 logger
5159 );
5160 } else {
5161 fail_unbroadcast_htlcs!(
5162 self,
5163 current_msg,
5164 commitment_txid,
5165 commitment_tx,
5166 height,
5167 block_hash,
5168 holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(),
5169 logger
5170 );
5171 }
5172
5173 Some((claim_requests, (commitment_txid, watch_outputs)))
5174 } else {
5175 None
5176 }
5177 }
5178
5179 #[rustfmt::skip]
5182 pub fn cancel_prev_commitment_claims<L: Deref>(
5183 &mut self, logger: &L, confirmed_commitment_txid: &Txid
5184 ) where L::Target: Logger {
5185 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
5186 if counterparty_commitment_txid == confirmed_commitment_txid {
5188 continue;
5189 }
5190 for funding in core::iter::once(&self.funding).chain(self.pending_funding.iter()) {
5193 let mut found_claim = false;
5194 for (htlc, _) in funding.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
5195 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
5196 if let Some(vout) = htlc.transaction_output_index {
5197 outpoint.vout = vout;
5198 if self.onchain_tx_handler.abandon_claim(&outpoint) {
5199 found_claim = true;
5200 }
5201 }
5202 }
5203 if found_claim {
5204 log_trace!(logger, "Canceled claims for previously confirmed counterparty commitment with txid {counterparty_commitment_txid}");
5205 }
5206 }
5207 }
5208 for funding in core::iter::once(&self.funding).chain(self.pending_funding.iter()) {
5212 if funding.current_holder_commitment_tx.trust().txid() != *confirmed_commitment_txid {
5213 let mut found_claim = false;
5214 let txid = funding.current_holder_commitment_tx.trust().txid();
5215 let mut outpoint = BitcoinOutPoint { txid, vout: 0 };
5216 for htlc in funding.current_holder_commitment_tx.nondust_htlcs() {
5217 if let Some(vout) = htlc.transaction_output_index {
5218 outpoint.vout = vout;
5219 if self.onchain_tx_handler.abandon_claim(&outpoint) {
5220 found_claim = true;
5221 }
5222 } else {
5223 debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5224 }
5225 }
5226 if found_claim {
5227 log_trace!(logger, "Canceled claims for previously broadcast holder commitment with txid {txid}");
5228 }
5229 }
5230 if let Some(prev_holder_commitment_tx) = &funding.prev_holder_commitment_tx {
5231 let txid = prev_holder_commitment_tx.trust().txid();
5232 if txid != *confirmed_commitment_txid {
5233 let mut found_claim = false;
5234 let mut outpoint = BitcoinOutPoint { txid, vout: 0 };
5235 for htlc in prev_holder_commitment_tx.nondust_htlcs() {
5236 if let Some(vout) = htlc.transaction_output_index {
5237 outpoint.vout = vout;
5238 if self.onchain_tx_handler.abandon_claim(&outpoint) {
5239 found_claim = true;
5240 }
5241 } else {
5242 debug_assert!(false, "Expected transaction output index for non-dust HTLC");
5243 }
5244 }
5245 if found_claim {
5246 log_trace!(logger, "Canceled claims for previously broadcast holder commitment with txid {txid}");
5247 }
5248 }
5249 }
5250 }
5251 }
5252
5253 #[cfg(any(test, feature = "_test_utils", feature = "unsafe_revoked_tx_signing"))]
5254 #[rustfmt::skip]
5256 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
5257 &mut self, logger: &WithChannelMonitor<L>
5258 ) -> Vec<Transaction> where L::Target: Logger {
5259 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
5260 let commitment_tx = {
5261 let sig = self.onchain_tx_handler.signer.unsafe_sign_holder_commitment(
5262 &self.funding.channel_parameters, &self.funding.current_holder_commitment_tx,
5263 &self.onchain_tx_handler.secp_ctx,
5264 ).expect("sign holder commitment");
5265 let redeem_script = self.funding.channel_parameters.make_funding_redeemscript();
5266 self.funding.current_holder_commitment_tx.add_holder_sig(&redeem_script, sig)
5267 };
5268 let mut holder_transactions = vec![commitment_tx];
5269
5270 if self.channel_type_features().supports_anchors_zero_fee_htlc_tx()
5271 || self.channel_type_features().supports_anchor_zero_fee_commitments()
5272 {
5273 return holder_transactions;
5286 }
5287
5288 self.get_broadcasted_holder_htlc_descriptors(&self.funding, &self.funding.current_holder_commitment_tx)
5289 .into_iter()
5290 .for_each(|htlc_descriptor| {
5291 let txid = self.funding.current_holder_commitment_tx.trust().txid();
5292 let vout = htlc_descriptor.htlc.transaction_output_index
5293 .expect("Expected transaction output index for non-dust HTLC");
5294 let htlc_output = HolderHTLCOutput::build(htlc_descriptor, 0);
5295 if let Some(htlc_tx) = htlc_output.get_maybe_signed_htlc_tx(
5296 &mut self.onchain_tx_handler, &::bitcoin::OutPoint { txid, vout },
5297 ) {
5298 if htlc_tx.is_fully_signed() {
5299 holder_transactions.push(htlc_tx.0);
5300 }
5301 }
5302 });
5303
5304 holder_transactions
5305 }
5306
5307 #[rustfmt::skip]
5308 fn block_connected<B: Deref, F: Deref, L: Deref>(
5309 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
5310 fee_estimator: F, logger: &WithChannelMonitor<L>,
5311 ) -> Vec<TransactionOutputs>
5312 where B::Target: BroadcasterInterface,
5313 F::Target: FeeEstimator,
5314 L::Target: Logger,
5315 {
5316 let block_hash = header.block_hash();
5317 self.best_block = BestBlock::new(block_hash, height);
5318
5319 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
5320 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
5321 }
5322
5323 #[rustfmt::skip]
5324 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
5325 &mut self,
5326 header: &Header,
5327 height: u32,
5328 broadcaster: B,
5329 fee_estimator: &LowerBoundedFeeEstimator<F>,
5330 logger: &WithChannelMonitor<L>,
5331 ) -> Vec<TransactionOutputs>
5332 where
5333 B::Target: BroadcasterInterface,
5334 F::Target: FeeEstimator,
5335 L::Target: Logger,
5336 {
5337 let block_hash = header.block_hash();
5338
5339 if height > self.best_block.height {
5340 self.best_block = BestBlock::new(block_hash, height);
5341 log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
5342 self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
5343 } else if block_hash != self.best_block.block_hash {
5344 self.best_block = BestBlock::new(block_hash, height);
5345 log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
5346 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
5347 let conf_target = self.closure_conf_target();
5348 self.onchain_tx_handler.blocks_disconnected(
5349 height, &broadcaster, conf_target, &self.destination_script, fee_estimator, logger,
5350 );
5351 Vec::new()
5352 } else { Vec::new() }
5353 }
5354
5355 #[rustfmt::skip]
5356 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
5357 &mut self,
5358 header: &Header,
5359 txdata: &TransactionData,
5360 height: u32,
5361 broadcaster: B,
5362 fee_estimator: &LowerBoundedFeeEstimator<F>,
5363 logger: &WithChannelMonitor<L>,
5364 ) -> Vec<TransactionOutputs>
5365 where
5366 B::Target: BroadcasterInterface,
5367 F::Target: FeeEstimator,
5368 L::Target: Logger,
5369 {
5370 let funding_seen_before = self.funding_seen_onchain;
5371 let txn_matched = self.filter_block(txdata);
5372
5373 if !self.funding_seen_onchain {
5374 for &(_, tx) in txdata.iter() {
5375 let txid = tx.compute_txid();
5376 if txid == self.funding.funding_txid() ||
5377 self.pending_funding.iter().any(|f| f.funding_txid() == txid)
5378 {
5379 self.funding_seen_onchain = true;
5380 break;
5381 }
5382 }
5383 }
5384
5385 for tx in &txn_matched {
5386 let mut output_val = Amount::ZERO;
5387 for out in tx.output.iter() {
5388 if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
5389 output_val += out.value;
5390 if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
5391 }
5392 }
5393
5394 let block_hash = header.block_hash();
5395
5396 let mut should_broadcast_commitment = false;
5402
5403 let mut watch_outputs = Vec::new();
5404 let mut claimable_outpoints = Vec::new();
5405
5406 if self.is_manual_broadcast && !funding_seen_before && self.funding_seen_onchain && self.holder_tx_signed
5407 {
5408 should_broadcast_commitment = true;
5409 }
5410 'tx_iter: for tx in &txn_matched {
5411 let txid = tx.compute_txid();
5412 log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
5413 if self.alternative_funding_confirmed.map(|(alternative_funding_txid, _)| alternative_funding_txid == txid).unwrap_or(false) {
5415 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
5416 continue 'tx_iter;
5417 }
5418 if Some(txid) == self.funding_spend_confirmed {
5419 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
5420 continue 'tx_iter;
5421 }
5422 for ev in self.onchain_events_awaiting_threshold_conf.iter() {
5423 if ev.txid == txid {
5424 if let Some(conf_hash) = ev.block_hash {
5425 assert_eq!(header.block_hash(), conf_hash,
5426 "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
5427 This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
5428 }
5429 log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
5430 continue 'tx_iter;
5431 }
5432 }
5433 for htlc in self.htlcs_resolved_on_chain.iter() {
5434 if Some(txid) == htlc.resolving_txid {
5435 log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
5436 continue 'tx_iter;
5437 }
5438 }
5439 for spendable_txid in self.spendable_txids_confirmed.iter() {
5440 if txid == *spendable_txid {
5441 log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
5442 continue 'tx_iter;
5443 }
5444 }
5445
5446 if let Some(alternative_funding) = self
5451 .pending_funding
5452 .iter()
5453 .find(|funding| funding.funding_txid() == txid)
5454 {
5455 assert!(self.alternative_funding_confirmed.is_none());
5456 assert!(
5457 !self.onchain_events_awaiting_threshold_conf.iter()
5458 .any(|e| matches!(e.event, OnchainEvent::AlternativeFundingConfirmation {}))
5459 );
5460 assert!(self.funding_spend_confirmed.is_none());
5461 assert!(
5462 !self.onchain_events_awaiting_threshold_conf.iter()
5463 .any(|e| matches!(e.event, OnchainEvent::FundingSpendConfirmation { .. }))
5464 );
5465
5466 let (desc, msg) = if alternative_funding.is_splice() {
5467 debug_assert!(tx.input.iter().any(|input| {
5468 let funding_outpoint = self.funding.funding_outpoint().into_bitcoin_outpoint();
5469 input.previous_output == funding_outpoint
5470 }));
5471 ("Splice", "splice_locked")
5472 } else {
5473 ("Dual-funded RBF", "channel_ready")
5474 };
5475 let action = if self.holder_tx_signed || self.funding_spend_seen {
5476 ", broadcasting holder commitment transaction".to_string()
5477 } else if !self.no_further_updates_allowed() {
5478 format!(", waiting for `{msg}` exchange")
5479 } else {
5480 "".to_string()
5481 };
5482 log_info!(logger, "{desc} for channel {} confirmed with txid {txid}{action}", self.channel_id());
5483
5484 self.alternative_funding_confirmed = Some((txid, height));
5485
5486 if self.no_further_updates_allowed() {
5487 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
5491 txid,
5492 transaction: Some((*tx).clone()),
5493 height,
5494 block_hash: Some(block_hash),
5495 event: OnchainEvent::AlternativeFundingConfirmation {},
5496 });
5497 }
5498
5499 if self.holder_tx_signed || self.funding_spend_seen {
5500 let new_holder_commitment_txid =
5503 alternative_funding.current_holder_commitment_tx.trust().txid();
5504 self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5505
5506 should_broadcast_commitment = true;
5510 }
5511
5512 continue 'tx_iter;
5513 }
5514
5515 if tx.input.len() == 1 {
5516 if let Some(funding_txid_spent) = core::iter::once(&self.funding)
5521 .chain(self.pending_funding.iter())
5522 .find(|funding| {
5523 let funding_outpoint = funding.funding_outpoint().into_bitcoin_outpoint();
5524 funding_outpoint == tx.input[0].previous_output
5525 })
5526 .map(|funding| funding.funding_txid())
5527 {
5528 assert_eq!(
5529 funding_txid_spent,
5530 self.alternative_funding_confirmed
5531 .map(|(txid, _)| txid)
5532 .unwrap_or_else(|| self.funding.funding_txid())
5533 );
5534 log_info!(logger, "Channel {} closed by funding output spend in txid {txid}",
5535 self.channel_id());
5536 if !self.funding_spend_seen {
5537 self.pending_monitor_events.push(MonitorEvent::CommitmentTxConfirmed(()));
5538 }
5539 self.funding_spend_seen = true;
5540
5541 let mut balance_spendable_csv = None;
5542 let mut commitment_tx_to_counterparty_output = None;
5543
5544 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
5546 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(txid, &tx, height, &block_hash, &logger) {
5547 if !new_outputs.1.is_empty() {
5548 watch_outputs.push(new_outputs);
5549 }
5550
5551 claimable_outpoints.append(&mut new_outpoints);
5552 balance_spendable_csv = Some(self.on_holder_tx_csv);
5553 } else {
5554 let mut new_watch_outputs = Vec::new();
5555 for (idx, outp) in tx.output.iter().enumerate() {
5556 new_watch_outputs.push((idx as u32, outp.clone()));
5557 }
5558 watch_outputs.push((txid, new_watch_outputs));
5559
5560 let (mut new_outpoints, counterparty_output_idx_sats) =
5561 self.check_spend_counterparty_transaction(txid, &tx, height, &block_hash, &logger);
5562 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
5563
5564 claimable_outpoints.append(&mut new_outpoints);
5565 }
5566
5567 if should_broadcast_commitment {
5570 log_info!(logger, "Canceling our queued holder commitment broadcast as we've found a conflict confirm instead");
5571 should_broadcast_commitment = false;
5572 }
5573 }
5574
5575 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
5576 txid,
5577 transaction: Some((*tx).clone()),
5578 height,
5579 block_hash: Some(block_hash),
5580 event: OnchainEvent::FundingSpendConfirmation {
5581 on_local_output_csv: balance_spendable_csv,
5582 commitment_tx_to_counterparty_output,
5583 },
5584 });
5585
5586 self.cancel_prev_commitment_claims(&logger, &txid);
5590 }
5591 }
5592 if tx.input.len() >= 1 {
5593 for tx_input in &tx.input {
5597 let commitment_txid = tx_input.previous_output.txid;
5598 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
5599 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
5600 &tx, commitment_number, &commitment_txid, height, &logger
5601 );
5602 claimable_outpoints.append(&mut new_outpoints);
5603 if let Some(new_outputs) = new_outputs_option {
5604 watch_outputs.push(new_outputs);
5605 }
5606 break;
5611 }
5612 }
5613 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
5614
5615 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
5616 }
5617 }
5618
5619 if height > self.best_block.height {
5620 self.best_block = BestBlock::new(block_hash, height);
5621 }
5622
5623 if should_broadcast_commitment {
5624 let (mut claimables, mut outputs) =
5625 self.generate_claimable_outpoints_and_watch_outputs(None, false);
5626 claimable_outpoints.append(&mut claimables);
5627 watch_outputs.append(&mut outputs);
5628 }
5629
5630 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
5631 }
5632
5633 #[rustfmt::skip]
5642 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
5643 &mut self,
5644 conf_height: u32,
5645 conf_hash: BlockHash,
5646 txn_matched: Vec<&Transaction>,
5647 mut watch_outputs: Vec<TransactionOutputs>,
5648 mut claimable_outpoints: Vec<PackageTemplate>,
5649 broadcaster: &B,
5650 fee_estimator: &LowerBoundedFeeEstimator<F>,
5651 logger: &WithChannelMonitor<L>,
5652 ) -> Vec<TransactionOutputs>
5653 where
5654 B::Target: BroadcasterInterface,
5655 F::Target: FeeEstimator,
5656 L::Target: Logger,
5657 {
5658 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
5659 debug_assert!(self.best_block.height >= conf_height);
5660
5661 if claimable_outpoints.is_empty() {
5663 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
5664 if let Some(payment_hash) = should_broadcast {
5665 let reason = ClosureReason::HTLCsTimedOut { payment_hash: Some(payment_hash) };
5666 let (mut new_outpoints, mut new_outputs) =
5667 self.generate_claimable_outpoints_and_watch_outputs(Some(reason), false);
5668 if !self.is_manual_broadcast || self.funding_seen_onchain {
5669 claimable_outpoints.append(&mut new_outpoints);
5670 watch_outputs.append(&mut new_outputs);
5671 } else {
5672 log_info!(logger, "Not broadcasting holder commitment for manual-broadcast channel before funding appears on-chain");
5673 }
5674 }
5675 }
5676
5677 let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
5679 self.onchain_events_awaiting_threshold_conf.drain(..).partition(
5680 |entry| entry.has_reached_confirmation_threshold(&self.best_block));
5681 self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
5682
5683 #[cfg(debug_assertions)]
5685 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
5686 .iter()
5687 .filter_map(|entry| match &entry.event {
5688 OnchainEvent::HTLCUpdate { source, .. } => Some(source.clone()),
5689 _ => None,
5690 })
5691 .collect();
5692 #[cfg(debug_assertions)]
5693 let mut matured_htlcs = Vec::new();
5694
5695 for entry in onchain_events_reaching_threshold_conf {
5697 match entry.event {
5698 OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
5699 #[cfg(debug_assertions)]
5701 {
5702 debug_assert!(
5703 !unmatured_htlcs.contains(&source),
5704 "An unmature HTLC transaction conflicts with a maturing one; failed to \
5705 call either transaction_unconfirmed for the conflicting transaction \
5706 or blocks_disconnected for a block before it.");
5707 debug_assert!(
5708 !matured_htlcs.contains(&source),
5709 "A matured HTLC transaction conflicts with a maturing one; failed to \
5710 call either transaction_unconfirmed for the conflicting transaction \
5711 or blocks_disconnected for a block before it.");
5712 matured_htlcs.push(source.clone());
5713 }
5714
5715 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
5716 &payment_hash, entry.txid);
5717 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
5718 payment_hash,
5719 payment_preimage: None,
5720 source,
5721 htlc_value_satoshis,
5722 }));
5723 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
5724 commitment_tx_output_idx,
5725 resolving_txid: Some(entry.txid),
5726 resolving_tx: entry.transaction,
5727 payment_preimage: None,
5728 });
5729 },
5730 OnchainEvent::MaturingOutput { descriptor } => {
5731 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
5732 self.pending_events.push(Event::SpendableOutputs {
5733 outputs: vec![descriptor],
5734 channel_id: Some(self.channel_id()),
5735 });
5736 self.spendable_txids_confirmed.push(entry.txid);
5737 },
5738 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
5739 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
5740 commitment_tx_output_idx: Some(commitment_tx_output_idx),
5741 resolving_txid: Some(entry.txid),
5742 resolving_tx: entry.transaction,
5743 payment_preimage: preimage,
5744 });
5745 },
5746 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
5747 self.funding_spend_confirmed = Some(entry.txid);
5748 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
5749 if self.alternative_funding_confirmed.is_none() {
5750 for funding in self.pending_funding.drain(..) {
5751 self.outputs_to_watch.remove(&funding.funding_txid());
5752 self.pending_events.push(Event::DiscardFunding {
5753 channel_id: self.channel_id,
5754 funding_info: crate::events::FundingInfo::OutPoint {
5755 outpoint: funding.funding_outpoint(),
5756 },
5757 });
5758 }
5759 }
5760 },
5761 OnchainEvent::AlternativeFundingConfirmation {} => {
5762 debug_assert!(self.no_further_updates_allowed());
5765 debug_assert_ne!(self.funding.funding_txid(), entry.txid);
5766 if let Err(_) = self.promote_funding(entry.txid) {
5767 debug_assert!(false);
5768 log_error!(logger, "Missing scope for alternative funding confirmation with txid {}", entry.txid);
5769 }
5770 },
5771 }
5772 }
5773
5774 if self.no_further_updates_allowed() {
5775 let current_counterparty_htlcs = if let Some(txid) = self.funding.current_counterparty_commitment_txid {
5782 if let Some(htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&txid) {
5783 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
5784 } else { None }
5785 } else { None }.into_iter().flatten();
5786
5787 let prev_counterparty_htlcs = if let Some(txid) = self.funding.prev_counterparty_commitment_txid {
5788 if let Some(htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(&txid) {
5789 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
5790 } else { None }
5791 } else { None }.into_iter().flatten();
5792
5793 let htlcs = holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES)
5794 .chain(current_counterparty_htlcs)
5795 .chain(prev_counterparty_htlcs);
5796
5797 let height = self.best_block.height;
5798 for (htlc, source_opt) in htlcs {
5799 let source = match source_opt {
5801 Some(source) => source,
5802 None => continue,
5803 };
5804 let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
5805 Some(cltv_expiry) => cltv_expiry,
5806 None => continue,
5807 };
5808 let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
5809 if inbound_htlc_expiry > max_expiry_height {
5810 continue;
5811 }
5812 let duplicate_event = self.pending_monitor_events.iter().any(
5813 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
5814 upd.source == *source
5815 } else { false });
5816 if duplicate_event {
5817 continue;
5818 }
5819 if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
5820 continue;
5821 }
5822 if !duplicate_event {
5823 log_error!(logger, "Failing back HTLC {} upstream to preserve the \
5824 channel as the forward HTLC hasn't resolved and our backward HTLC \
5825 expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
5826 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
5827 source: source.clone(),
5828 payment_preimage: None,
5829 payment_hash: htlc.payment_hash,
5830 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
5831 }));
5832 }
5833 }
5834 }
5835
5836 let conf_target = self.closure_conf_target();
5837 self.onchain_tx_handler.update_claims_view_from_requests(
5838 claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target,
5839 &self.destination_script, fee_estimator, logger,
5840 );
5841 self.onchain_tx_handler.update_claims_view_from_matched_txn(
5842 &txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, conf_target,
5843 &self.destination_script, fee_estimator, logger,
5844 );
5845
5846 watch_outputs.retain(|&(ref txid, ref txouts)| {
5849 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
5850 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
5851 });
5852 #[cfg(test)]
5853 {
5854 for tx in &txn_matched {
5858 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
5859 for idx_and_script in outputs.iter() {
5860 assert!((idx_and_script.0 as usize) < tx.output.len());
5861 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
5862 }
5863 }
5864 }
5865 }
5866 watch_outputs
5867 }
5868
5869 #[rustfmt::skip]
5870 fn blocks_disconnected<B: Deref, F: Deref, L: Deref>(
5871 &mut self, fork_point: BestBlock, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
5872 ) where B::Target: BroadcasterInterface,
5873 F::Target: FeeEstimator,
5874 L::Target: Logger,
5875 {
5876 let new_height = fork_point.height;
5877 log_trace!(logger, "Block(s) disconnected to height {}", new_height);
5878 assert!(self.best_block.height > fork_point.height,
5879 "Blocks disconnected must indicate disconnection from the current best height, i.e. the new chain tip must be lower than the previous best height");
5880
5881 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= new_height);
5885
5886 let mut should_broadcast_commitment = false;
5888 if let Some((_, conf_height)) = self.alternative_funding_confirmed.as_ref() {
5889 if *conf_height > new_height {
5890 self.alternative_funding_confirmed.take();
5891 if self.holder_tx_signed || self.funding_spend_seen {
5892 let new_holder_commitment_txid =
5895 self.funding.current_holder_commitment_tx.trust().txid();
5896 self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5897
5898 should_broadcast_commitment = true;
5899 }
5900 }
5901 }
5902
5903 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
5904 let conf_target = self.closure_conf_target();
5905 self.onchain_tx_handler.blocks_disconnected(
5906 new_height, &broadcaster, conf_target, &self.destination_script, &bounded_fee_estimator, logger
5907 );
5908
5909 if should_broadcast_commitment {
5912 self.queue_latest_holder_commitment_txn_for_broadcast(&broadcaster, &bounded_fee_estimator, logger, true);
5913 }
5914
5915 self.best_block = fork_point;
5916 }
5917
5918 #[rustfmt::skip]
5919 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
5920 &mut self,
5921 txid: &Txid,
5922 broadcaster: B,
5923 fee_estimator: &LowerBoundedFeeEstimator<F>,
5924 logger: &WithChannelMonitor<L>,
5925 ) where
5926 B::Target: BroadcasterInterface,
5927 F::Target: FeeEstimator,
5928 L::Target: Logger,
5929 {
5930 let mut removed_height = None;
5931 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
5932 if entry.txid == *txid {
5933 removed_height = Some(entry.height);
5934 break;
5935 }
5936 }
5937
5938 if let Some(removed_height) = removed_height {
5939 log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
5940 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
5941 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
5942 false
5943 } else { true });
5944 }
5945
5946 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
5947
5948 let mut should_broadcast_commitment = false;
5950 if let Some((alternative_funding_txid, _)) = self.alternative_funding_confirmed.as_ref() {
5951 if alternative_funding_txid == txid {
5952 self.alternative_funding_confirmed.take();
5953 if self.holder_tx_signed || self.funding_spend_seen {
5954 let new_holder_commitment_txid =
5957 self.funding.current_holder_commitment_tx.trust().txid();
5958 self.cancel_prev_commitment_claims(&logger, &new_holder_commitment_txid);
5959
5960 should_broadcast_commitment = true;
5961 }
5962 }
5963 }
5964
5965 let conf_target = self.closure_conf_target();
5966 self.onchain_tx_handler.transaction_unconfirmed(
5967 txid, &broadcaster, conf_target, &self.destination_script, fee_estimator, logger
5968 );
5969
5970 if should_broadcast_commitment {
5973 self.queue_latest_holder_commitment_txn_for_broadcast(&broadcaster, fee_estimator, logger, true);
5974 }
5975 }
5976
5977 #[rustfmt::skip]
5980 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
5981 let mut matched_txn = new_hash_set();
5982 txdata.iter().filter(|&&(_, tx)| {
5983 let mut matches = self.spends_watched_output(tx);
5984 for input in tx.input.iter() {
5985 if matches { break; }
5986 if matched_txn.contains(&input.previous_output.txid) {
5987 matches = true;
5988 }
5989 }
5990 if matches {
5991 matched_txn.insert(tx.compute_txid());
5992 }
5993 matches
5994 }).map(|(_, tx)| *tx).collect()
5995 }
5996
5997 #[rustfmt::skip]
5999 fn spends_watched_output(&self, tx: &Transaction) -> bool {
6000 for input in tx.input.iter() {
6001 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
6002 for (idx, _script_pubkey) in outputs.iter() {
6003 if *idx == input.previous_output.vout {
6004 #[cfg(test)]
6005 {
6006 if _script_pubkey.is_p2wsh() {
6010 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
6011 return true;
6015 }
6016
6017 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
6018 } else if _script_pubkey.is_p2wpkh() {
6019 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
6020 } else if _script_pubkey == &chan_utils::shared_anchor_script_pubkey() {
6021 assert!(input.witness.is_empty());
6022 } else { panic!(); }
6023 }
6024 return true;
6025 }
6026 }
6027 }
6028 }
6029
6030 false
6031 }
6032
6033 #[rustfmt::skip]
6034 fn should_broadcast_holder_commitment_txn<L: Deref>(
6035 &self, logger: &WithChannelMonitor<L>
6036 ) -> Option<PaymentHash> where L::Target: Logger {
6037 if self.funding_spend_confirmed.is_some() ||
6040 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
6041 OnchainEvent::FundingSpendConfirmation { .. } => true,
6042 _ => false,
6043 }).is_some()
6044 {
6045 return None;
6046 }
6047 let height = self.best_block.height;
6058 const ASYNC_PAYMENT_GRACE_PERIOD_BLOCKS: u32 = 4032;
6061 macro_rules! scan_commitment {
6062 ($htlcs: expr, $holder_tx: expr) => {
6063 for (ref htlc, ref source) in $htlcs {
6064 let htlc_outbound = $holder_tx == htlc.offered;
6080 let async_payment = htlc_outbound && matches!(
6081 source.as_deref().expect("Every outbound HTLC should have a corresponding source"),
6082 HTLCSource::OutboundRoute {
6083 bolt12_invoice: Some(PaidBolt12Invoice::StaticInvoice(_)),
6084 ..
6085 }
6086 );
6087 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height && !async_payment) ||
6088 ( htlc_outbound && htlc.cltv_expiry + ASYNC_PAYMENT_GRACE_PERIOD_BLOCKS <= height && async_payment) ||
6089 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
6090 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);
6091 return Some(htlc.payment_hash);
6092 }
6093 }
6094 }
6095 }
6096
6097 scan_commitment!(holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES), true);
6098
6099 if let Some(ref txid) = self.funding.current_counterparty_commitment_txid {
6100 if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(txid) {
6101 scan_commitment!(htlc_outputs.iter(), false);
6102 }
6103 }
6104 if let Some(ref txid) = self.funding.prev_counterparty_commitment_txid {
6105 if let Some(ref htlc_outputs) = self.funding.counterparty_claimable_outpoints.get(txid) {
6106 scan_commitment!(htlc_outputs.iter(), false);
6107 }
6108 }
6109
6110 None
6111 }
6112
6113 #[rustfmt::skip]
6116 fn is_resolving_htlc_output<L: Deref>(
6117 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
6118 ) where L::Target: Logger {
6119 let funding_spent = get_confirmed_funding_scope!(self);
6120
6121 'outer_loop: for input in &tx.input {
6122 let mut payment_data = None;
6123 let htlc_claim = HTLCClaim::from_witness(&input.witness);
6124 let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
6125 let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
6126 #[cfg(not(fuzzing))]
6127 let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
6128 let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
6129 #[cfg(not(fuzzing))]
6130 let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
6131
6132 let mut payment_preimage = PaymentPreimage([0; 32]);
6133 if offered_preimage_claim || accepted_preimage_claim {
6134 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
6135 }
6136
6137 macro_rules! log_claim {
6138 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
6139 let outbound_htlc = $holder_tx == $htlc.offered;
6140 #[cfg(not(fuzzing))] debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
6144 #[cfg(not(fuzzing))] debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
6146 #[cfg(not(fuzzing))] debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
6150 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
6151 revocation_sig_claim as u8, 1);
6152 if ($holder_tx && revocation_sig_claim) ||
6153 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
6154 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
6155 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
6156 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
6157 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" });
6158 } else {
6159 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
6160 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
6161 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
6162 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
6163 }
6164 }
6165 }
6166
6167 macro_rules! check_htlc_valid_counterparty {
6168 ($htlc_output: expr, $per_commitment_data: expr) => {
6169 for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
6170 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
6171 if let &Some(ref source) = pending_source {
6172 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
6173 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
6174 break;
6175 }
6176 }
6177 }
6178 }
6179 }
6180
6181 macro_rules! scan_commitment {
6182 ($funding_spent: expr, $htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
6183 for (ref htlc_output, source_option) in $htlcs {
6184 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
6185 if let Some(ref source) = source_option {
6186 log_claim!($tx_info, $holder_tx, htlc_output, true);
6187 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
6193 } else if !$holder_tx {
6194 if let Some(current_counterparty_commitment_txid) = &$funding_spent.current_counterparty_commitment_txid {
6195 check_htlc_valid_counterparty!(htlc_output, $funding_spent.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
6196 }
6197 if payment_data.is_none() {
6198 if let Some(prev_counterparty_commitment_txid) = &$funding_spent.prev_counterparty_commitment_txid {
6199 check_htlc_valid_counterparty!(htlc_output, $funding_spent.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
6200 }
6201 }
6202 }
6203 if payment_data.is_none() {
6204 log_claim!($tx_info, $holder_tx, htlc_output, false);
6205 let outbound_htlc = $holder_tx == htlc_output.offered;
6206 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6207 txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
6208 event: OnchainEvent::HTLCSpendConfirmation {
6209 commitment_tx_output_idx: input.previous_output.vout,
6210 preimage: if accepted_preimage_claim || offered_preimage_claim {
6211 Some(payment_preimage) } else { None },
6212 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
6217 Some(self.on_holder_tx_csv) } else { None },
6218 },
6219 });
6220 continue 'outer_loop;
6221 }
6222 }
6223 }
6224 }
6225 }
6226
6227 if input.previous_output.txid == funding_spent.current_holder_commitment_tx.trust().txid() {
6228 scan_commitment!(
6229 funding_spent, holder_commitment_htlcs!(self, CURRENT_WITH_SOURCES),
6230 "our latest holder commitment tx", true
6231 );
6232 }
6233 if let Some(prev_holder_commitment_tx) = funding_spent.prev_holder_commitment_tx.as_ref() {
6234 if input.previous_output.txid == prev_holder_commitment_tx.trust().txid() {
6235 scan_commitment!(
6236 funding_spent, holder_commitment_htlcs!(self, PREV_WITH_SOURCES).unwrap(),
6237 "our previous holder commitment tx", true
6238 );
6239 }
6240 }
6241 if let Some(ref htlc_outputs) = funding_spent.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
6242 let htlcs = htlc_outputs.iter()
6243 .map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed)));
6244 scan_commitment!(funding_spent, htlcs, "counterparty commitment tx", false);
6245 }
6246
6247 if let Some((source, payment_hash, amount_msat)) = payment_data {
6250 if accepted_preimage_claim {
6251 if !self.pending_monitor_events.iter().any(
6252 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
6253 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6254 txid: tx.compute_txid(),
6255 height,
6256 block_hash: Some(*block_hash),
6257 transaction: Some(tx.clone()),
6258 event: OnchainEvent::HTLCSpendConfirmation {
6259 commitment_tx_output_idx: input.previous_output.vout,
6260 preimage: Some(payment_preimage),
6261 on_to_local_output_csv: None,
6262 },
6263 });
6264 self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
6265 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
6266 source,
6267 payment_preimage: Some(payment_preimage),
6268 payment_hash,
6269 htlc_value_satoshis: Some(amount_msat / 1000),
6270 }));
6271 }
6272 } else if offered_preimage_claim {
6273 if !self.pending_monitor_events.iter().any(
6274 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
6275 upd.source == source
6276 } else { false }) {
6277 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
6278 txid: tx.compute_txid(),
6279 transaction: Some(tx.clone()),
6280 height,
6281 block_hash: Some(*block_hash),
6282 event: OnchainEvent::HTLCSpendConfirmation {
6283 commitment_tx_output_idx: input.previous_output.vout,
6284 preimage: Some(payment_preimage),
6285 on_to_local_output_csv: None,
6286 },
6287 });
6288 self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
6289 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
6290 source,
6291 payment_preimage: Some(payment_preimage),
6292 payment_hash,
6293 htlc_value_satoshis: Some(amount_msat / 1000),
6294 }));
6295 }
6296 } else {
6297 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
6298 if entry.height != height { return true; }
6299 match entry.event {
6300 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
6301 *htlc_source != source
6302 },
6303 _ => true,
6304 }
6305 });
6306 let entry = OnchainEventEntry {
6307 txid: tx.compute_txid(),
6308 transaction: Some(tx.clone()),
6309 height,
6310 block_hash: Some(*block_hash),
6311 event: OnchainEvent::HTLCUpdate {
6312 source,
6313 payment_hash,
6314 htlc_value_satoshis: Some(amount_msat / 1000),
6315 commitment_tx_output_idx: Some(input.previous_output.vout),
6316 },
6317 };
6318 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
6319 self.onchain_events_awaiting_threshold_conf.push(entry);
6320 }
6321 }
6322 }
6323 }
6324
6325 #[rustfmt::skip]
6326 fn get_spendable_outputs(&self, funding_spent: &FundingScope, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
6327 let mut spendable_outputs = Vec::new();
6328 for (i, outp) in tx.output.iter().enumerate() {
6329 if outp.script_pubkey == self.destination_script {
6330 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
6331 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6332 output: outp.clone(),
6333 channel_keys_id: Some(self.channel_keys_id),
6334 });
6335 }
6336 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
6337 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
6338 spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
6339 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6340 per_commitment_point: broadcasted_holder_revokable_script.1,
6341 to_self_delay: self.on_holder_tx_csv,
6342 output: outp.clone(),
6343 revocation_pubkey: broadcasted_holder_revokable_script.2,
6344 channel_keys_id: self.channel_keys_id,
6345 channel_value_satoshis: funding_spent.channel_parameters.channel_value_satoshis,
6346 channel_transaction_parameters: Some(funding_spent.channel_parameters.clone()),
6347 }));
6348 }
6349 }
6350 if self.counterparty_payment_script == outp.script_pubkey {
6351 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
6352 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6353 output: outp.clone(),
6354 channel_keys_id: self.channel_keys_id,
6355 channel_value_satoshis: funding_spent.channel_parameters.channel_value_satoshis,
6356 channel_transaction_parameters: Some(funding_spent.channel_parameters.clone()),
6357 }));
6358 }
6359 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
6360 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
6361 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
6362 output: outp.clone(),
6363 channel_keys_id: Some(self.channel_keys_id),
6364 });
6365 }
6366 }
6367 spendable_outputs
6368 }
6369
6370 #[rustfmt::skip]
6373 fn check_tx_and_push_spendable_outputs<L: Deref>(
6374 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
6375 ) where L::Target: Logger {
6376 let funding_spent = get_confirmed_funding_scope!(self);
6377 for spendable_output in self.get_spendable_outputs(funding_spent, tx) {
6378 let entry = OnchainEventEntry {
6379 txid: tx.compute_txid(),
6380 transaction: Some(tx.clone()),
6381 height,
6382 block_hash: Some(*block_hash),
6383 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
6384 };
6385 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
6386 self.onchain_events_awaiting_threshold_conf.push(entry);
6387 }
6388 }
6389
6390 fn channel_type_features(&self) -> &ChannelTypeFeatures {
6391 &self.funding.channel_parameters.channel_type_features
6392 }
6393}
6394
6395impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen
6396 for (ChannelMonitor<Signer>, T, F, L)
6397where
6398 T::Target: BroadcasterInterface,
6399 F::Target: FeeEstimator,
6400 L::Target: Logger,
6401{
6402 fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
6403 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
6404 }
6405
6406 fn blocks_disconnected(&self, fork_point: BestBlock) {
6407 self.0.blocks_disconnected(fork_point, &*self.1, &*self.2, &self.3);
6408 }
6409}
6410
6411impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
6412where
6413 M: Deref<Target = ChannelMonitor<Signer>>,
6414 T::Target: BroadcasterInterface,
6415 F::Target: FeeEstimator,
6416 L::Target: Logger,
6417{
6418 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
6419 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
6420 }
6421
6422 fn transaction_unconfirmed(&self, txid: &Txid) {
6423 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
6424 }
6425
6426 fn best_block_updated(&self, header: &Header, height: u32) {
6427 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
6428 }
6429
6430 fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
6431 self.0.get_relevant_txids()
6432 }
6433}
6434
6435const MAX_ALLOC_SIZE: usize = 64 * 1024;
6436
6437impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
6438 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>)
6439{
6440 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
6441 match <Option<Self>>::read(reader, args) {
6442 Ok(Some(res)) => Ok(res),
6443 Ok(None) => Err(DecodeError::UnknownRequiredFeature),
6444 Err(e) => Err(e),
6445 }
6446 }
6447}
6448
6449impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
6450 for Option<(BlockHash, ChannelMonitor<SP::EcdsaSigner>)>
6451{
6452 #[rustfmt::skip]
6453 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
6454 macro_rules! unwrap_obj {
6455 ($key: expr) => {
6456 match $key {
6457 Ok(res) => res,
6458 Err(_) => return Err(DecodeError::InvalidValue),
6459 }
6460 }
6461 }
6462
6463 let (entropy_source, signer_provider) = args;
6464
6465 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
6466
6467 let latest_update_id: u64 = Readable::read(reader)?;
6468 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
6469
6470 let destination_script = Readable::read(reader)?;
6471 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
6472 0 => {
6473 let revokable_address = Readable::read(reader)?;
6474 let per_commitment_point = Readable::read(reader)?;
6475 let revokable_script = Readable::read(reader)?;
6476 Some((revokable_address, per_commitment_point, revokable_script))
6477 },
6478 1 => { None },
6479 _ => return Err(DecodeError::InvalidValue),
6480 };
6481 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
6482 let shutdown_script = {
6483 let script = <ScriptBuf as Readable>::read(reader)?;
6484 if script.is_empty() { None } else { Some(script) }
6485 };
6486
6487 let channel_keys_id = Readable::read(reader)?;
6488 let holder_revocation_basepoint = Readable::read(reader)?;
6489 let outpoint = OutPoint {
6492 txid: Readable::read(reader)?,
6493 index: Readable::read(reader)?,
6494 };
6495 let _funding_script: ScriptBuf = Readable::read(reader)?;
6496 let current_counterparty_commitment_txid = Readable::read(reader)?;
6497 let prev_counterparty_commitment_txid = Readable::read(reader)?;
6498
6499 let counterparty_commitment_params = Readable::read(reader)?;
6500 let _funding_redeemscript: ScriptBuf = Readable::read(reader)?;
6501 let channel_value_satoshis = Readable::read(reader)?;
6502
6503 let their_cur_per_commitment_points = {
6504 let first_idx = <U48 as Readable>::read(reader)?.0;
6505 if first_idx == 0 {
6506 None
6507 } else {
6508 let first_point = Readable::read(reader)?;
6509 let second_point_slice: [u8; 33] = Readable::read(reader)?;
6510 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
6511 Some((first_idx, first_point, None))
6512 } else {
6513 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
6514 }
6515 }
6516 };
6517
6518 let on_holder_tx_csv: u16 = Readable::read(reader)?;
6519
6520 let commitment_secrets = Readable::read(reader)?;
6521
6522 macro_rules! read_htlc_in_commitment {
6523 () => {
6524 {
6525 let offered: bool = Readable::read(reader)?;
6526 let amount_msat: u64 = Readable::read(reader)?;
6527 let cltv_expiry: u32 = Readable::read(reader)?;
6528 let payment_hash: PaymentHash = Readable::read(reader)?;
6529 let transaction_output_index: Option<u32> = Readable::read(reader)?;
6530
6531 HTLCOutputInCommitment {
6532 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
6533 }
6534 }
6535 }
6536 }
6537
6538 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
6539 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
6540 for _ in 0..counterparty_claimable_outpoints_len {
6541 let txid: Txid = Readable::read(reader)?;
6542 let htlcs_count: u64 = Readable::read(reader)?;
6543 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
6544 for _ in 0..htlcs_count {
6545 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
6546 }
6547 if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
6548 return Err(DecodeError::InvalidValue);
6549 }
6550 }
6551
6552 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
6553 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));
6554 for _ in 0..counterparty_commitment_txn_on_chain_len {
6555 let txid: Txid = Readable::read(reader)?;
6556 let commitment_number = <U48 as Readable>::read(reader)?.0;
6557 if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
6558 return Err(DecodeError::InvalidValue);
6559 }
6560 }
6561
6562 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
6563 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
6564 for _ in 0..counterparty_hash_commitment_number_len {
6565 let payment_hash: PaymentHash = Readable::read(reader)?;
6566 let commitment_number = <U48 as Readable>::read(reader)?.0;
6567 if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
6568 return Err(DecodeError::InvalidValue);
6569 }
6570 }
6571
6572 let prev_holder_signed_tx: Option<HolderSignedTx> =
6573 match <u8 as Readable>::read(reader)? {
6574 0 => None,
6575 1 => Some(Readable::read(reader)?),
6576 _ => return Err(DecodeError::InvalidValue),
6577 };
6578 let current_holder_signed_tx: HolderSignedTx = Readable::read(reader)?;
6579
6580 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
6581 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
6582
6583 let payment_preimages_len: u64 = Readable::read(reader)?;
6584 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
6585 for _ in 0..payment_preimages_len {
6586 let preimage: PaymentPreimage = Readable::read(reader)?;
6587 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
6588 if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
6589 return Err(DecodeError::InvalidValue);
6590 }
6591 }
6592
6593 let pending_monitor_events_len: u64 = Readable::read(reader)?;
6594 let mut pending_monitor_events = Some(
6595 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
6596 for _ in 0..pending_monitor_events_len {
6597 let ev = match <u8 as Readable>::read(reader)? {
6598 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
6599 1 => MonitorEvent::HolderForceClosed(outpoint),
6600 _ => return Err(DecodeError::InvalidValue)
6601 };
6602 pending_monitor_events.as_mut().unwrap().push(ev);
6603 }
6604
6605 let pending_events_len: u64 = Readable::read(reader)?;
6606 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
6607 for _ in 0..pending_events_len {
6608 if let Some(event) = MaybeReadable::read(reader)? {
6609 pending_events.push(event);
6610 }
6611 }
6612
6613 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
6614
6615 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
6616 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
6617 for _ in 0..waiting_threshold_conf_len {
6618 if let Some(val) = MaybeReadable::read(reader)? {
6619 onchain_events_awaiting_threshold_conf.push(val);
6620 }
6621 }
6622
6623 let outputs_to_watch_len: u64 = Readable::read(reader)?;
6624 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>>())));
6625 for _ in 0..outputs_to_watch_len {
6626 let txid = Readable::read(reader)?;
6627 let outputs_len: u64 = Readable::read(reader)?;
6628 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
6629 for _ in 0..outputs_len {
6630 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
6631 }
6632 if outputs_to_watch.insert(txid, outputs).is_some() {
6633 return Err(DecodeError::InvalidValue);
6634 }
6635 }
6636 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
6637 reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
6638 )?;
6639
6640 let lockdown_from_offchain = Readable::read(reader)?;
6641 let holder_tx_signed = Readable::read(reader)?;
6642
6643 let mut funding_spend_confirmed = None;
6644 let mut htlcs_resolved_on_chain = Some(Vec::new());
6645 let mut htlcs_resolved_to_user = Some(new_hash_set());
6646 let mut funding_spend_seen = Some(false);
6647 let mut counterparty_node_id = None;
6648 let mut confirmed_commitment_tx_counterparty_output = None;
6649 let mut spendable_txids_confirmed = Some(Vec::new());
6650 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
6651 let mut initial_counterparty_commitment_info = None;
6652 let mut initial_counterparty_commitment_tx = None;
6653 let mut balances_empty_height = None;
6654 let mut channel_id = None;
6655 let mut holder_pays_commitment_tx_fee = None;
6656 let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
6657 let mut first_negotiated_funding_txo = RequiredWrapper(None);
6658 let mut channel_parameters = None;
6659 let mut pending_funding = None;
6660 let mut alternative_funding_confirmed = None;
6661 let mut is_manual_broadcast = RequiredWrapper(None);
6662 let mut funding_seen_onchain = RequiredWrapper(None);
6663 read_tlv_fields!(reader, {
6664 (1, funding_spend_confirmed, option),
6665 (3, htlcs_resolved_on_chain, optional_vec),
6666 (5, pending_monitor_events, optional_vec),
6667 (7, funding_spend_seen, option),
6668 (9, counterparty_node_id, option),
6669 (11, confirmed_commitment_tx_counterparty_output, option),
6670 (13, spendable_txids_confirmed, optional_vec),
6671 (15, counterparty_fulfilled_htlcs, option),
6672 (17, initial_counterparty_commitment_info, option),
6673 (19, channel_id, option),
6674 (21, balances_empty_height, option),
6675 (23, holder_pays_commitment_tx_fee, option),
6676 (25, payment_preimages_with_info, option),
6677 (27, first_negotiated_funding_txo, (default_value, outpoint)),
6678 (29, initial_counterparty_commitment_tx, option),
6679 (31, channel_parameters, (option: ReadableArgs, None)),
6680 (32, pending_funding, optional_vec),
6681 (33, htlcs_resolved_to_user, option),
6682 (34, alternative_funding_confirmed, option),
6683 (35, is_manual_broadcast, (default_value, false)),
6684 (37, funding_seen_onchain, (default_value, true)),
6685 });
6686 let written_by_0_1_or_later = payment_preimages_with_info.is_some();
6689 if let Some(payment_preimages_with_info) = payment_preimages_with_info {
6690 if payment_preimages_with_info.len() != payment_preimages.len() {
6691 return Err(DecodeError::InvalidValue);
6692 }
6693 for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
6694 let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
6699 if new_preimage != Some(payment_preimage) {
6700 return Err(DecodeError::InvalidValue);
6701 }
6702 }
6703 payment_preimages = payment_preimages_with_info;
6704 }
6705
6706 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
6709 if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
6710 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
6711 {
6712 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
6713 }
6714 }
6715
6716 let channel_parameters = channel_parameters.unwrap_or_else(|| {
6717 onchain_tx_handler.channel_parameters().clone()
6718 });
6719
6720 if channel_parameters.channel_type_features.supports_anchors_zero_fee_htlc_tx() &&
6724 counterparty_payment_script.is_p2wpkh()
6725 {
6726 let payment_point = channel_parameters.holder_pubkeys.payment_point;
6727 counterparty_payment_script =
6728 chan_utils::get_to_countersigner_keyed_anchor_redeemscript(&payment_point).to_p2wsh();
6729 }
6730
6731 let channel_id = channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint));
6732
6733 let (current_holder_commitment_tx, current_holder_htlc_data) = {
6734 let holder_commitment_tx = onchain_tx_handler.current_holder_commitment_tx();
6735
6736 #[cfg(debug_assertions)]
6737 let holder_signed_tx_copy = current_holder_signed_tx.clone();
6738
6739 let holder_commitment_htlc_data = CommitmentHTLCData::try_from(current_holder_signed_tx)
6740 .map_err(|_| DecodeError::InvalidValue)?;
6741
6742 #[cfg(debug_assertions)] {
6743 let mut stream = crate::util::ser::VecWriter(Vec::new());
6744 write_legacy_holder_commitment_data(
6745 &mut stream, &holder_commitment_tx, &holder_commitment_htlc_data
6746 ).map_err(|_| DecodeError::InvalidValue)?;
6747 let mut cursor = crate::io::Cursor::new(stream.0);
6748 if holder_signed_tx_copy != <HolderSignedTx as Readable>::read(&mut cursor)? {
6749 return Err(DecodeError::InvalidValue);
6750 }
6751 }
6752
6753 (holder_commitment_tx.clone(), holder_commitment_htlc_data)
6754 };
6755
6756 let (prev_holder_commitment_tx, prev_holder_htlc_data) =
6757 if let Some(prev_holder_signed_tx) = prev_holder_signed_tx {
6758 let holder_commitment_tx = onchain_tx_handler.prev_holder_commitment_tx();
6759 if holder_commitment_tx.is_none() {
6760 return Err(DecodeError::InvalidValue);
6761 }
6762
6763 #[cfg(debug_assertions)]
6764 let holder_signed_tx_copy = prev_holder_signed_tx.clone();
6765
6766 let holder_commitment_htlc_data = CommitmentHTLCData::try_from(prev_holder_signed_tx)
6767 .map_err(|_| DecodeError::InvalidValue)?;
6768
6769 #[cfg(debug_assertions)] {
6770 let mut stream = crate::util::ser::VecWriter(Vec::new());
6771 write_legacy_holder_commitment_data(
6772 &mut stream, &holder_commitment_tx.unwrap(), &holder_commitment_htlc_data
6773 ).map_err(|_| DecodeError::InvalidValue)?;
6774 let mut cursor = crate::io::Cursor::new(stream.0);
6775 if holder_signed_tx_copy != <HolderSignedTx as Readable>::read(&mut cursor)? {
6776 return Err(DecodeError::InvalidValue);
6777 }
6778 }
6779
6780 (holder_commitment_tx.cloned(), Some(holder_commitment_htlc_data))
6781 } else {
6782 (None, None)
6783 };
6784
6785 let dummy_node_id = PublicKey::from_slice(&[2; 33]).unwrap();
6786 let monitor = ChannelMonitor::from_impl(ChannelMonitorImpl {
6787 funding: FundingScope {
6788 channel_parameters,
6789
6790 current_counterparty_commitment_txid,
6791 prev_counterparty_commitment_txid,
6792 counterparty_claimable_outpoints,
6793
6794 current_holder_commitment_tx,
6795 prev_holder_commitment_tx,
6796 },
6797 pending_funding: pending_funding.unwrap_or(vec![]),
6798 is_manual_broadcast: is_manual_broadcast.0.unwrap(),
6799 funding_seen_onchain: funding_seen_onchain.0.unwrap(),
6802
6803 latest_update_id,
6804 commitment_transaction_number_obscure_factor,
6805
6806 destination_script,
6807 broadcasted_holder_revokable_script,
6808 counterparty_payment_script,
6809 shutdown_script,
6810
6811 channel_keys_id,
6812 holder_revocation_basepoint,
6813 channel_id,
6814 first_negotiated_funding_txo: first_negotiated_funding_txo.0.unwrap(),
6815
6816 counterparty_commitment_params,
6817 their_cur_per_commitment_points,
6818
6819 on_holder_tx_csv,
6820
6821 commitment_secrets,
6822 counterparty_commitment_txn_on_chain,
6823 counterparty_hash_commitment_number,
6824 counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
6825
6826 current_counterparty_commitment_number,
6827 current_holder_commitment_number,
6828
6829 payment_preimages,
6830 pending_monitor_events: pending_monitor_events.unwrap(),
6831 pending_events,
6832 is_processing_pending_events: false,
6833
6834 onchain_events_awaiting_threshold_conf,
6835 outputs_to_watch,
6836
6837 onchain_tx_handler,
6838
6839 lockdown_from_offchain,
6840 holder_tx_signed,
6841 holder_pays_commitment_tx_fee,
6842 funding_spend_seen: funding_spend_seen.unwrap(),
6843 funding_spend_confirmed,
6844 confirmed_commitment_tx_counterparty_output,
6845 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
6846 htlcs_resolved_to_user: htlcs_resolved_to_user.unwrap(),
6847 spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
6848
6849 best_block,
6850 counterparty_node_id: counterparty_node_id.unwrap_or(dummy_node_id),
6851 initial_counterparty_commitment_info,
6852 initial_counterparty_commitment_tx,
6853 balances_empty_height,
6854 failed_back_htlc_ids: new_hash_set(),
6855
6856 current_holder_htlc_data,
6857 prev_holder_htlc_data,
6858
6859 alternative_funding_confirmed,
6860
6861 written_by_0_1_or_later,
6862 });
6863
6864 if counterparty_node_id.is_none() {
6865 if (holder_tx_signed || lockdown_from_offchain) && monitor.get_claimable_balances().is_empty() {
6866 return Ok(None);
6869 } else {
6870 panic!("Found monitor for channel {channel_id} with no updates since v0.0.118. \
6871 These monitors are no longer supported. \
6872 To continue, run a v0.1 release, send/route a payment over the channel or close it.");
6873 }
6874 }
6875 Ok(Some((best_block.block_hash, monitor)))
6876 }
6877}
6878
6879#[cfg(test)]
6880mod tests {
6881 use bitcoin::amount::Amount;
6882 use bitcoin::hash_types::{BlockHash, Txid};
6883 use bitcoin::hashes::sha256::Hash as Sha256;
6884 use bitcoin::hashes::Hash;
6885 use bitcoin::hex::FromHex;
6886 use bitcoin::locktime::absolute::LockTime;
6887 use bitcoin::network::Network;
6888 use bitcoin::opcodes;
6889 use bitcoin::script::{Builder, ScriptBuf};
6890 use bitcoin::secp256k1::Secp256k1;
6891 use bitcoin::secp256k1::{PublicKey, SecretKey};
6892 use bitcoin::sighash;
6893 use bitcoin::sighash::EcdsaSighashType;
6894 use bitcoin::transaction::OutPoint as BitcoinOutPoint;
6895 use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
6896 use bitcoin::{Sequence, Witness};
6897
6898 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
6899 use crate::events::ClosureReason;
6900
6901 use super::ChannelMonitorUpdateStep;
6902 use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
6903 use crate::chain::package::{
6904 weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc,
6905 weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT,
6906 };
6907 use crate::chain::transaction::OutPoint;
6908 use crate::chain::{BestBlock, Confirm};
6909 use crate::io;
6910 use crate::ln::chan_utils::{
6911 self, ChannelPublicKeys, ChannelTransactionParameters,
6912 CounterpartyChannelTransactionParameters, HTLCOutputInCommitment,
6913 HolderCommitmentTransaction,
6914 };
6915 use crate::ln::channel_keys::{
6916 DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint,
6917 RevocationKey,
6918 };
6919 use crate::ln::channelmanager::{HTLCSource, PaymentId, RecipientOnionFields};
6920 use crate::ln::functional_test_utils::*;
6921 use crate::ln::script::ShutdownScript;
6922 use crate::ln::types::ChannelId;
6923 use crate::sign::{ChannelSigner, InMemorySigner};
6924 use crate::sync::Arc;
6925 use crate::types::features::ChannelTypeFeatures;
6926 use crate::types::payment::{PaymentHash, PaymentPreimage};
6927 use crate::util::logger::Logger;
6928 use crate::util::ser::{ReadableArgs, Writeable};
6929 use crate::util::test_utils::{TestBroadcaster, TestFeeEstimator, TestLogger};
6930 use crate::{
6931 check_added_monitors, check_spends, get_local_commitment_txn, get_monitor,
6932 get_route_and_payment_hash,
6933 };
6934
6935 #[allow(unused_imports)]
6936 use crate::prelude::*;
6937
6938 use std::str::FromStr;
6939
6940 #[rustfmt::skip]
6941 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
6942 let chanmon_cfgs = create_chanmon_cfgs(3);
6954 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6955 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6956 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6957 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
6958 create_announced_chan_between_nodes(&nodes, 1, 2);
6959
6960 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
6962
6963 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
6965 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
6966
6967 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
6968 assert_eq!(local_txn.len(), 1);
6969 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
6970 assert_eq!(remote_txn.len(), 3); check_spends!(remote_txn[1], remote_txn[0]);
6972 check_spends!(remote_txn[2], remote_txn[0]);
6973 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
6974
6975 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
6978 let conf_height = nodes[0].best_block_info().1 + 1;
6979 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
6980 &[(0, broadcast_tx)], conf_height);
6981
6982 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<_>)>::read(
6983 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
6984 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
6985
6986 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
6989 nodes[1].node.send_payment_with_route(route, payment_hash,
6990 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
6991 ).unwrap();
6992 check_added_monitors!(nodes[1], 1);
6993
6994 let replay_update = {
6998 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
6999 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().next_back().unwrap().clone();
7000 assert_eq!(replay_update.updates.len(), 1);
7001 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
7002 } else { panic!(); }
7003 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
7004 payment_preimage: payment_preimage_1, payment_info: None,
7005 });
7006 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
7007 payment_preimage: payment_preimage_2, payment_info: None,
7008 });
7009 replay_update
7010 };
7011
7012 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
7013 assert!(
7014 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
7015 .is_err());
7016
7017 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7020 assert!(txn_broadcasted.len() >= 2);
7021 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
7022 assert_eq!(tx.input.len(), 1);
7023 tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
7024 }).collect::<Vec<_>>();
7025 assert_eq!(htlc_txn.len(), 2);
7026 check_spends!(htlc_txn[0], broadcast_tx);
7027 check_spends!(htlc_txn[1], broadcast_tx);
7028
7029 check_closed_broadcast(&nodes[1], 1, true);
7030 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false, &[nodes[0].node.get_our_node_id()], 100000);
7031 check_added_monitors(&nodes[1], 1);
7032 }
7033
7034 #[test]
7035 fn test_funding_spend_refuses_updates() {
7036 do_test_funding_spend_refuses_updates(true);
7037 do_test_funding_spend_refuses_updates(false);
7038 }
7039
7040 #[test]
7041 #[rustfmt::skip]
7042 fn test_prune_preimages() {
7043 let secp_ctx = Secp256k1::new();
7044 let logger = Arc::new(TestLogger::new());
7045 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
7046 let fee_estimator = TestFeeEstimator::new(253);
7047
7048 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7049
7050 let mut preimages = Vec::new();
7051 {
7052 for i in 0..20 {
7053 let preimage = PaymentPreimage([i; 32]);
7054 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
7055 preimages.push((preimage, hash));
7056 }
7057 }
7058
7059 let dummy_source = HTLCSource::dummy();
7060
7061 macro_rules! preimages_slice_to_htlcs {
7062 ($preimages_slice: expr) => {
7063 {
7064 let mut res = Vec::new();
7065 for (idx, preimage) in $preimages_slice.iter().enumerate() {
7066 res.push(HTLCOutputInCommitment {
7067 offered: true,
7068 amount_msat: 0,
7069 cltv_expiry: 0,
7070 payment_hash: preimage.1.clone(),
7071 transaction_output_index: Some(idx as u32),
7072 });
7073 }
7074 res
7075 }
7076 }
7077 }
7078 macro_rules! preimages_slice_to_htlc_outputs {
7079 ($preimages_slice: expr) => {
7080 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|htlc| (htlc, None)).collect()
7081 }
7082 }
7083 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
7084 &bitcoin::secp256k1::Message::from_digest([42; 32]),
7085 &SecretKey::from_slice(&[42; 32]).unwrap());
7086
7087 macro_rules! test_preimages_exist {
7088 ($preimages_slice: expr, $monitor: expr) => {
7089 for preimage in $preimages_slice {
7090 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
7091 }
7092 }
7093 }
7094
7095 let keys = InMemorySigner::new(
7096 SecretKey::from_slice(&[41; 32]).unwrap(),
7097 SecretKey::from_slice(&[41; 32]).unwrap(),
7098 SecretKey::from_slice(&[41; 32]).unwrap(),
7099 SecretKey::from_slice(&[41; 32]).unwrap(),
7100 true,
7101 SecretKey::from_slice(&[41; 32]).unwrap(),
7102 SecretKey::from_slice(&[41; 32]).unwrap(),
7103 [41; 32],
7104 [0; 32],
7105 [0; 32],
7106 );
7107
7108 let counterparty_pubkeys = ChannelPublicKeys {
7109 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
7110 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
7111 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
7112 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
7113 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
7114 };
7115 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7116 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
7117 let channel_parameters = ChannelTransactionParameters {
7118 holder_pubkeys: keys.pubkeys(&secp_ctx),
7119 holder_selected_contest_delay: 66,
7120 is_outbound_from_holder: true,
7121 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
7122 pubkeys: counterparty_pubkeys,
7123 selected_contest_delay: 67,
7124 }),
7125 funding_outpoint: Some(funding_outpoint),
7126 splice_parent_funding_txid: None,
7127 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
7128 channel_value_satoshis: 0,
7129 };
7130 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7133 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey);
7134 let best_block = BestBlock::from_network(Network::Testnet);
7135 let monitor = ChannelMonitor::new(
7136 Secp256k1::new(), keys, Some(shutdown_script.into_inner()), 0, &ScriptBuf::new(),
7137 &channel_parameters, true, 0, HolderCommitmentTransaction::dummy(0, funding_outpoint, Vec::new()),
7138 best_block, dummy_key, channel_id, false,
7139 );
7140
7141 let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
7142 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7143 let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7145
7146 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7147 &nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7148 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
7149 preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key);
7150 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
7151 preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key);
7152 for &(ref preimage, ref hash) in preimages.iter() {
7153 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
7154 monitor.provide_payment_preimage_unsafe_legacy(
7155 hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
7156 );
7157 }
7158
7159 let mut secret = [0; 32];
7161 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
7162 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
7163 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
7164 test_preimages_exist!(&preimages[0..10], monitor);
7165 test_preimages_exist!(&preimages[15..20], monitor);
7166
7167 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
7168 preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key);
7169
7170 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
7172 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
7173 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
7174 test_preimages_exist!(&preimages[0..10], monitor);
7175 test_preimages_exist!(&preimages[17..20], monitor);
7176
7177 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
7178 preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key);
7179
7180 let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
7183 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7184 let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7186 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7187 &nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7188 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
7189 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
7190 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
7191 test_preimages_exist!(&preimages[0..10], monitor);
7192 test_preimages_exist!(&preimages[18..20], monitor);
7193
7194 let nondust_htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
7196 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(0, funding_outpoint, nondust_htlcs);
7197 let nondust_htlcs = dummy_commitment_tx.nondust_htlcs();
7199 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
7200 &nondust_htlcs.iter().map(|htlc| (htlc.clone(), Some(dummy_sig), Some(dummy_source.clone()))).collect::<Vec<_>>());
7201 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
7202 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
7203 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
7204 test_preimages_exist!(&preimages[0..5], monitor);
7205 }
7206
7207 #[test]
7208 #[rustfmt::skip]
7209 fn test_claim_txn_weight_computation() {
7210 let secp_ctx = Secp256k1::new();
7214 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
7215 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
7216
7217 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
7218 macro_rules! sign_input {
7219 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
7220 let htlc = HTLCOutputInCommitment {
7221 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
7222 amount_msat: 0,
7223 cltv_expiry: 2 << 16,
7224 payment_hash: PaymentHash([1; 32]),
7225 transaction_output_index: Some($idx as u32),
7226 };
7227 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)) };
7228 let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
7229 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
7230 let mut ser_sig = sig.serialize_der().to_vec();
7231 ser_sig.push(EcdsaSighashType::All as u8);
7232 $sum_actual_sigs += ser_sig.len() as u64;
7233 let witness = $sighash_parts.witness_mut($idx).unwrap();
7234 witness.push(ser_sig);
7235 if *$weight == WEIGHT_REVOKED_OUTPUT {
7236 witness.push(vec!(1));
7237 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
7238 witness.push(pubkey.clone().serialize().to_vec());
7239 } else if *$weight == weight_received_htlc($opt_anchors) {
7240 witness.push(vec![0]);
7241 } else {
7242 witness.push(PaymentPreimage([1; 32]).0.to_vec());
7243 }
7244 witness.push(redeem_script.into_bytes());
7245 let witness = witness.to_vec();
7246 println!("witness[0] {}", witness[0].len());
7247 println!("witness[1] {}", witness[1].len());
7248 println!("witness[2] {}", witness[2].len());
7249 }
7250 }
7251
7252 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
7253 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
7254
7255 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7257 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7258 let mut sum_actual_sigs = 0;
7259 for i in 0..4 {
7260 claim_tx.input.push(TxIn {
7261 previous_output: BitcoinOutPoint {
7262 txid,
7263 vout: i,
7264 },
7265 script_sig: ScriptBuf::new(),
7266 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7267 witness: Witness::new(),
7268 });
7269 }
7270 claim_tx.output.push(TxOut {
7271 script_pubkey: script_pubkey.clone(),
7272 value: Amount::ZERO,
7273 });
7274 let base_weight = claim_tx.weight().to_wu();
7275 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)];
7276 let mut inputs_total_weight = 2; {
7278 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7279 for (idx, inp) in inputs_weight.iter().enumerate() {
7280 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7281 inputs_total_weight += inp;
7282 }
7283 }
7284 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7285 }
7286
7287 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7289 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7290 let mut sum_actual_sigs = 0;
7291 for i in 0..4 {
7292 claim_tx.input.push(TxIn {
7293 previous_output: BitcoinOutPoint {
7294 txid,
7295 vout: i,
7296 },
7297 script_sig: ScriptBuf::new(),
7298 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7299 witness: Witness::new(),
7300 });
7301 }
7302 claim_tx.output.push(TxOut {
7303 script_pubkey: script_pubkey.clone(),
7304 value: Amount::ZERO,
7305 });
7306 let base_weight = claim_tx.weight().to_wu();
7307 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)];
7308 let mut inputs_total_weight = 2; {
7310 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7311 for (idx, inp) in inputs_weight.iter().enumerate() {
7312 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7313 inputs_total_weight += inp;
7314 }
7315 }
7316 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7317 }
7318
7319 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
7321 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
7322 let mut sum_actual_sigs = 0;
7323 claim_tx.input.push(TxIn {
7324 previous_output: BitcoinOutPoint {
7325 txid,
7326 vout: 0,
7327 },
7328 script_sig: ScriptBuf::new(),
7329 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
7330 witness: Witness::new(),
7331 });
7332 claim_tx.output.push(TxOut {
7333 script_pubkey: script_pubkey.clone(),
7334 value: Amount::ZERO,
7335 });
7336 let base_weight = claim_tx.weight().to_wu();
7337 let inputs_weight = [WEIGHT_REVOKED_OUTPUT];
7338 let mut inputs_total_weight = 2; {
7340 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
7341 for (idx, inp) in inputs_weight.iter().enumerate() {
7342 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
7343 inputs_total_weight += inp;
7344 }
7345 }
7346 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
7347 }
7348 }
7349
7350 #[test]
7351 #[rustfmt::skip]
7352 fn test_with_channel_monitor_impl_logger() {
7353 let secp_ctx = Secp256k1::new();
7354 let logger = Arc::new(TestLogger::new());
7355
7356 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7357
7358 let keys = InMemorySigner::new(
7359 SecretKey::from_slice(&[41; 32]).unwrap(),
7360 SecretKey::from_slice(&[41; 32]).unwrap(),
7361 SecretKey::from_slice(&[41; 32]).unwrap(),
7362 SecretKey::from_slice(&[41; 32]).unwrap(),
7363 true,
7364 SecretKey::from_slice(&[41; 32]).unwrap(),
7365 SecretKey::from_slice(&[41; 32]).unwrap(),
7366 [41; 32],
7367 [0; 32],
7368 [0; 32],
7369 );
7370
7371 let counterparty_pubkeys = ChannelPublicKeys {
7372 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
7373 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
7374 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
7375 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
7376 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
7377 };
7378 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
7379 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
7380 let channel_parameters = ChannelTransactionParameters {
7381 holder_pubkeys: keys.pubkeys(&secp_ctx),
7382 holder_selected_contest_delay: 66,
7383 is_outbound_from_holder: true,
7384 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
7385 pubkeys: counterparty_pubkeys,
7386 selected_contest_delay: 67,
7387 }),
7388 funding_outpoint: Some(funding_outpoint),
7389 splice_parent_funding_txid: None,
7390 channel_type_features: ChannelTypeFeatures::only_static_remote_key(),
7391 channel_value_satoshis: 0,
7392 };
7393 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
7394 let shutdown_script = ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey);
7395 let best_block = BestBlock::from_network(Network::Testnet);
7396 let monitor = ChannelMonitor::new(
7397 Secp256k1::new(), keys, Some(shutdown_script.into_inner()), 0, &ScriptBuf::new(),
7398 &channel_parameters, true, 0, HolderCommitmentTransaction::dummy(0, funding_outpoint, Vec::new()),
7399 best_block, dummy_key, channel_id, false,
7400 );
7401
7402 let chan_id = monitor.inner.lock().unwrap().channel_id();
7403 let payment_hash = PaymentHash([1; 32]);
7404 let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
7405 log_error!(context_logger, "This is an error");
7406 log_warn!(context_logger, "This is an error");
7407 log_debug!(context_logger, "This is an error");
7408 log_trace!(context_logger, "This is an error");
7409 log_gossip!(context_logger, "This is an error");
7410 log_info!(context_logger, "This is an error");
7411 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
7412 }
7413 }