1use bitcoin::amount::Amount;
24use bitcoin::block::Header;
25use bitcoin::transaction::{OutPoint as BitcoinOutPoint, TxOut, Transaction};
26use bitcoin::script::{Script, ScriptBuf};
27
28use bitcoin::hashes::Hash;
29use bitcoin::hashes::sha256::Hash as Sha256;
30use bitcoin::hash_types::{Txid, BlockHash};
31
32use bitcoin::ecdsa::Signature as BitcoinSignature;
33use bitcoin::secp256k1::{self, SecretKey, PublicKey, Secp256k1, ecdsa::Signature};
34
35use crate::ln::channel::INITIAL_COMMITMENT_NUMBER;
36use crate::ln::types::ChannelId;
37use crate::types::payment::{PaymentHash, PaymentPreimage};
38use crate::ln::msgs::DecodeError;
39use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint};
40use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys};
41use crate::ln::channelmanager::{HTLCSource, SentHTLCId, PaymentClaimDetails};
42use crate::chain;
43use crate::chain::{BestBlock, WatchedOutput};
44use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
45use crate::chain::transaction::{OutPoint, TransactionData};
46use crate::sign::{ChannelDerivationParameters, HTLCDescriptor, SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, ecdsa::EcdsaChannelSigner, SignerProvider, EntropySource};
47use crate::chain::onchaintx::{ClaimEvent, FeerateStrategy, OnchainTxHandler};
48use crate::chain::package::{CounterpartyOfferedHTLCOutput, CounterpartyReceivedHTLCOutput, HolderFundingOutput, HolderHTLCOutput, PackageSolvingData, PackageTemplate, RevokedOutput, RevokedHTLCOutput};
49use crate::chain::Filter;
50use crate::util::logger::{Logger, Record};
51use crate::util::ser::{Readable, ReadableArgs, RequiredWrapper, MaybeReadable, UpgradableRequired, Writer, Writeable, U48};
52use crate::util::byte_utils;
53use crate::events::{ClosureReason, Event, EventHandler, ReplayEvent};
54use crate::events::bump_transaction::{AnchorDescriptor, BumpTransactionEvent};
55
56#[allow(unused_imports)]
57use crate::prelude::*;
58
59use core::{cmp, mem};
60use crate::io::{self, Error};
61use core::ops::Deref;
62use crate::sync::Mutex;
63
64#[derive(Clone, Debug, PartialEq, Eq)]
72#[must_use]
73pub struct ChannelMonitorUpdate {
74 pub(crate) updates: Vec<ChannelMonitorUpdateStep>,
75 pub(crate) counterparty_node_id: Option<PublicKey>,
84 pub update_id: u64,
98 pub channel_id: Option<ChannelId>,
103}
104
105const LEGACY_CLOSED_CHANNEL_UPDATE_ID: u64 = u64::MAX;
108
109impl Writeable for ChannelMonitorUpdate {
110 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
111 write_ver_prefix!(w, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
112 self.update_id.write(w)?;
113 (self.updates.len() as u64).write(w)?;
114 for update_step in self.updates.iter() {
115 update_step.write(w)?;
116 }
117 write_tlv_fields!(w, {
118 (1, self.counterparty_node_id, option),
119 (3, self.channel_id, option),
120 });
121 Ok(())
122 }
123}
124impl Readable for ChannelMonitorUpdate {
125 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
126 let _ver = read_ver_prefix!(r, SERIALIZATION_VERSION);
127 let update_id: u64 = Readable::read(r)?;
128 let len: u64 = Readable::read(r)?;
129 let mut updates = Vec::with_capacity(cmp::min(len as usize, MAX_ALLOC_SIZE / ::core::mem::size_of::<ChannelMonitorUpdateStep>()));
130 for _ in 0..len {
131 if let Some(upd) = MaybeReadable::read(r)? {
132 updates.push(upd);
133 }
134 }
135 let mut counterparty_node_id = None;
136 let mut channel_id = None;
137 read_tlv_fields!(r, {
138 (1, counterparty_node_id, option),
139 (3, channel_id, option),
140 });
141 Ok(Self { update_id, counterparty_node_id, updates, channel_id })
142 }
143}
144
145#[derive(Clone, PartialEq, Eq)]
147pub enum MonitorEvent {
148 HTLCEvent(HTLCUpdate),
150
151 HolderForceClosedWithInfo {
154 reason: ClosureReason,
156 outpoint: OutPoint,
158 channel_id: ChannelId,
160 },
161
162 HolderForceClosed(OutPoint),
165
166 Completed {
171 funding_txo: OutPoint,
173 channel_id: ChannelId,
175 monitor_update_id: u64,
181 },
182}
183impl_writeable_tlv_based_enum_upgradable_legacy!(MonitorEvent,
184 (0, Completed) => {
187 (0, funding_txo, required),
188 (2, monitor_update_id, required),
189 (4, channel_id, required),
190 },
191 (5, HolderForceClosedWithInfo) => {
192 (0, reason, upgradable_required),
193 (2, outpoint, required),
194 (4, channel_id, required),
195 },
196;
197 (2, HTLCEvent),
198 (4, HolderForceClosed),
199 );
201
202#[derive(Clone, PartialEq, Eq)]
206pub struct HTLCUpdate {
207 pub(crate) payment_hash: PaymentHash,
208 pub(crate) payment_preimage: Option<PaymentPreimage>,
209 pub(crate) source: HTLCSource,
210 pub(crate) htlc_value_satoshis: Option<u64>,
211}
212impl_writeable_tlv_based!(HTLCUpdate, {
213 (0, payment_hash, required),
214 (1, htlc_value_satoshis, option),
215 (2, source, required),
216 (4, payment_preimage, option),
217});
218
219pub(crate) const COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE: u32 = 12;
223
224const _: () = assert!(CLTV_CLAIM_BUFFER > COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE);
228
229pub(crate) const CLTV_CLAIM_BUFFER: u32 = 18;
234pub(crate) const LATENCY_GRACE_PERIOD_BLOCKS: u32 = 3;
247pub const ANTI_REORG_DELAY: u32 = 6;
259pub const ARCHIVAL_DELAY_BLOCKS: u32 = 4032;
263pub(crate) const HTLC_FAIL_BACK_BUFFER: u32 = CLTV_CLAIM_BUFFER + LATENCY_GRACE_PERIOD_BLOCKS;
280
281#[derive(Clone, PartialEq, Eq)]
283struct HolderSignedTx {
284 txid: Txid,
286 revocation_key: RevocationKey,
287 a_htlc_key: HtlcKey,
288 b_htlc_key: HtlcKey,
289 delayed_payment_key: DelayedPaymentKey,
290 per_commitment_point: PublicKey,
291 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
292 to_self_value_sat: u64,
293 feerate_per_kw: u32,
294}
295impl_writeable_tlv_based!(HolderSignedTx, {
296 (0, txid, required),
297 (1, to_self_value_sat, (default_value, u64::MAX)),
300 (2, revocation_key, required),
301 (4, a_htlc_key, required),
302 (6, b_htlc_key, required),
303 (8, delayed_payment_key, required),
304 (10, per_commitment_point, required),
305 (12, feerate_per_kw, required),
306 (14, htlc_outputs, required_vec)
307});
308
309impl HolderSignedTx {
310 fn non_dust_htlcs(&self) -> Vec<HTLCOutputInCommitment> {
311 self.htlc_outputs.iter().filter_map(|(htlc, _, _)| {
312 if htlc.transaction_output_index.is_some() {
313 Some(htlc.clone())
314 } else {
315 None
316 }
317 })
318 .collect()
319 }
320}
321
322#[derive(Clone, PartialEq, Eq)]
325struct CounterpartyCommitmentParameters {
326 counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
327 counterparty_htlc_base_key: HtlcBasepoint,
328 on_counterparty_tx_csv: u16,
329}
330
331impl Writeable for CounterpartyCommitmentParameters {
332 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
333 w.write_all(&0u64.to_be_bytes())?;
334 write_tlv_fields!(w, {
335 (0, self.counterparty_delayed_payment_base_key, required),
336 (2, self.counterparty_htlc_base_key, required),
337 (4, self.on_counterparty_tx_csv, required),
338 });
339 Ok(())
340 }
341}
342impl Readable for CounterpartyCommitmentParameters {
343 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
344 let counterparty_commitment_transaction = {
345 let per_htlc_len: u64 = Readable::read(r)?;
348 for _ in 0..per_htlc_len {
349 let _txid: Txid = Readable::read(r)?;
350 let htlcs_count: u64 = Readable::read(r)?;
351 for _ in 0..htlcs_count {
352 let _htlc: HTLCOutputInCommitment = Readable::read(r)?;
353 }
354 }
355
356 let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
357 let mut counterparty_htlc_base_key = RequiredWrapper(None);
358 let mut on_counterparty_tx_csv: u16 = 0;
359 read_tlv_fields!(r, {
360 (0, counterparty_delayed_payment_base_key, required),
361 (2, counterparty_htlc_base_key, required),
362 (4, on_counterparty_tx_csv, required),
363 });
364 CounterpartyCommitmentParameters {
365 counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
366 counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
367 on_counterparty_tx_csv,
368 }
369 };
370 Ok(counterparty_commitment_transaction)
371 }
372}
373
374#[derive(Clone, PartialEq, Eq)]
379struct OnchainEventEntry {
380 txid: Txid,
381 height: u32,
382 block_hash: Option<BlockHash>, event: OnchainEvent,
384 transaction: Option<Transaction>, }
386
387impl OnchainEventEntry {
388 fn confirmation_threshold(&self) -> u32 {
389 let mut conf_threshold = self.height + ANTI_REORG_DELAY - 1;
390 match self.event {
391 OnchainEvent::MaturingOutput {
392 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor)
393 } => {
394 conf_threshold = cmp::max(conf_threshold, self.height + descriptor.to_self_delay as u32 - 1);
397 },
398 OnchainEvent::FundingSpendConfirmation { on_local_output_csv: Some(csv), .. } |
399 OnchainEvent::HTLCSpendConfirmation { on_to_local_output_csv: Some(csv), .. } => {
400 conf_threshold = cmp::max(conf_threshold, self.height + csv as u32 - 1);
403 },
404 _ => {},
405 }
406 conf_threshold
407 }
408
409 fn has_reached_confirmation_threshold(&self, best_block: &BestBlock) -> bool {
410 best_block.height >= self.confirmation_threshold()
411 }
412}
413
414type CommitmentTxCounterpartyOutputInfo = Option<(u32, Amount)>;
418
419#[derive(Clone, PartialEq, Eq)]
422enum OnchainEvent {
423 HTLCUpdate {
430 source: HTLCSource,
431 payment_hash: PaymentHash,
432 htlc_value_satoshis: Option<u64>,
433 commitment_tx_output_idx: Option<u32>,
436 },
437 MaturingOutput {
440 descriptor: SpendableOutputDescriptor,
441 },
442 FundingSpendConfirmation {
445 on_local_output_csv: Option<u16>,
448 commitment_tx_to_counterparty_output: CommitmentTxCounterpartyOutputInfo,
454 },
455 HTLCSpendConfirmation {
467 commitment_tx_output_idx: u32,
468 preimage: Option<PaymentPreimage>,
470 on_to_local_output_csv: Option<u16>,
474 },
475}
476
477impl Writeable for OnchainEventEntry {
478 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
479 write_tlv_fields!(writer, {
480 (0, self.txid, required),
481 (1, self.transaction, option),
482 (2, self.height, required),
483 (3, self.block_hash, option),
484 (4, self.event, required),
485 });
486 Ok(())
487 }
488}
489
490impl MaybeReadable for OnchainEventEntry {
491 fn read<R: io::Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
492 let mut txid = Txid::all_zeros();
493 let mut transaction = None;
494 let mut block_hash = None;
495 let mut height = 0;
496 let mut event = UpgradableRequired(None);
497 read_tlv_fields!(reader, {
498 (0, txid, required),
499 (1, transaction, option),
500 (2, height, required),
501 (3, block_hash, option),
502 (4, event, upgradable_required),
503 });
504 Ok(Some(Self { txid, transaction, height, block_hash, event: _init_tlv_based_struct_field!(event, upgradable_required) }))
505 }
506}
507
508impl_writeable_tlv_based_enum_upgradable!(OnchainEvent,
509 (0, HTLCUpdate) => {
510 (0, source, required),
511 (1, htlc_value_satoshis, option),
512 (2, payment_hash, required),
513 (3, commitment_tx_output_idx, option),
514 },
515 (1, MaturingOutput) => {
516 (0, descriptor, required),
517 },
518 (3, FundingSpendConfirmation) => {
519 (0, on_local_output_csv, option),
520 (1, commitment_tx_to_counterparty_output, option),
521 },
522 (5, HTLCSpendConfirmation) => {
523 (0, commitment_tx_output_idx, required),
524 (2, preimage, option),
525 (4, on_to_local_output_csv, option),
526 },
527
528);
529
530#[derive(Clone, Debug, PartialEq, Eq)]
531pub(crate) enum ChannelMonitorUpdateStep {
532 LatestHolderCommitmentTXInfo {
533 commitment_tx: HolderCommitmentTransaction,
534 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
538 claimed_htlcs: Vec<(SentHTLCId, PaymentPreimage)>,
539 nondust_htlc_sources: Vec<HTLCSource>,
540 },
541 LatestCounterpartyCommitmentTXInfo {
542 commitment_txid: Txid,
543 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
544 commitment_number: u64,
545 their_per_commitment_point: PublicKey,
546 feerate_per_kw: Option<u32>,
547 to_broadcaster_value_sat: Option<u64>,
548 to_countersignatory_value_sat: Option<u64>,
549 },
550 PaymentPreimage {
551 payment_preimage: PaymentPreimage,
552 payment_info: Option<PaymentClaimDetails>,
555 },
556 CommitmentSecret {
557 idx: u64,
558 secret: [u8; 32],
559 },
560 ChannelForceClosed {
563 should_broadcast: bool,
566 },
567 ShutdownScript {
568 scriptpubkey: ScriptBuf,
569 },
570 ReleasePaymentComplete {
582 htlc: SentHTLCId,
583 },
584}
585
586impl ChannelMonitorUpdateStep {
587 fn variant_name(&self) -> &'static str {
588 match self {
589 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
590 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
591 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
592 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
593 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
594 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
595 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => "ReleasePaymentComplete",
596 }
597 }
598}
599
600impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
601 (0, LatestHolderCommitmentTXInfo) => {
602 (0, commitment_tx, required),
603 (1, claimed_htlcs, optional_vec),
604 (2, htlc_outputs, required_vec),
605 (4, nondust_htlc_sources, optional_vec),
606 },
607 (1, LatestCounterpartyCommitmentTXInfo) => {
608 (0, commitment_txid, required),
609 (1, feerate_per_kw, option),
610 (2, commitment_number, required),
611 (3, to_broadcaster_value_sat, option),
612 (4, their_per_commitment_point, required),
613 (5, to_countersignatory_value_sat, option),
614 (6, htlc_outputs, required_vec),
615 },
616 (2, PaymentPreimage) => {
617 (0, payment_preimage, required),
618 (1, payment_info, option),
619 },
620 (3, CommitmentSecret) => {
621 (0, idx, required),
622 (2, secret, required),
623 },
624 (4, ChannelForceClosed) => {
625 (0, should_broadcast, required),
626 },
627 (5, ShutdownScript) => {
628 (0, scriptpubkey, required),
629 },
630 (7, ReleasePaymentComplete) => {
631 (1, htlc, required),
632 },
633);
634
635#[derive(Clone, Debug, PartialEq, Eq)]
638#[cfg_attr(test, derive(PartialOrd, Ord))]
639pub enum BalanceSource {
640 HolderForceClosed,
642 CounterpartyForceClosed,
644 CoopClose,
646 Htlc,
648}
649
650#[derive(Clone, Debug, PartialEq, Eq)]
655#[cfg_attr(test, derive(PartialOrd, Ord))]
656pub enum Balance {
657 ClaimableOnChannelClose {
661 amount_satoshis: u64,
664 transaction_fee_satoshis: u64,
671 outbound_payment_htlc_rounded_msat: u64,
680 outbound_forwarded_htlc_rounded_msat: u64,
688 inbound_claiming_htlc_rounded_msat: u64,
698 inbound_htlc_rounded_msat: u64,
707 },
708 ClaimableAwaitingConfirmations {
711 amount_satoshis: u64,
714 confirmation_height: u32,
717 source: BalanceSource,
719 },
720 ContentiousClaimable {
728 amount_satoshis: u64,
731 timeout_height: u32,
734 payment_hash: PaymentHash,
736 payment_preimage: PaymentPreimage,
738 },
739 MaybeTimeoutClaimableHTLC {
743 amount_satoshis: u64,
746 claimable_height: u32,
749 payment_hash: PaymentHash,
751 outbound_payment: bool,
755 },
756 MaybePreimageClaimableHTLC {
760 amount_satoshis: u64,
763 expiry_height: u32,
766 payment_hash: PaymentHash,
768 },
769 CounterpartyRevokedOutputClaimable {
775 amount_satoshis: u64,
780 },
781}
782
783impl Balance {
784 pub fn claimable_amount_satoshis(&self) -> u64 {
797 match self {
798 Balance::ClaimableOnChannelClose { amount_satoshis, .. }|
799 Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
800 Balance::ContentiousClaimable { amount_satoshis, .. }|
801 Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
802 => *amount_satoshis,
803 Balance::MaybeTimeoutClaimableHTLC { amount_satoshis, outbound_payment, .. }
804 => if *outbound_payment { 0 } else { *amount_satoshis },
805 Balance::MaybePreimageClaimableHTLC { .. } => 0,
806 }
807 }
808}
809
810#[derive(Clone, PartialEq, Eq)]
812struct IrrevocablyResolvedHTLC {
813 commitment_tx_output_idx: Option<u32>,
814 resolving_txid: Option<Txid>, resolving_tx: Option<Transaction>,
819 payment_preimage: Option<PaymentPreimage>,
821}
822
823impl Writeable for IrrevocablyResolvedHTLC {
828 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
829 let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::MAX);
830 write_tlv_fields!(writer, {
831 (0, mapped_commitment_tx_output_idx, required),
832 (1, self.resolving_txid, option),
833 (2, self.payment_preimage, option),
834 (3, self.resolving_tx, option),
835 });
836 Ok(())
837 }
838}
839
840impl Readable for IrrevocablyResolvedHTLC {
841 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
842 let mut mapped_commitment_tx_output_idx = 0;
843 let mut resolving_txid = None;
844 let mut payment_preimage = None;
845 let mut resolving_tx = None;
846 read_tlv_fields!(reader, {
847 (0, mapped_commitment_tx_output_idx, required),
848 (1, resolving_txid, option),
849 (2, payment_preimage, option),
850 (3, resolving_tx, option),
851 });
852 Ok(Self {
853 commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::MAX { None } else { Some(mapped_commitment_tx_output_idx) },
854 resolving_txid,
855 payment_preimage,
856 resolving_tx,
857 })
858 }
859}
860
861pub struct ChannelMonitor<Signer: EcdsaChannelSigner> {
873 #[cfg(test)]
874 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
875 #[cfg(not(test))]
876 pub(super) inner: Mutex<ChannelMonitorImpl<Signer>>,
877}
878
879impl<Signer: EcdsaChannelSigner> Clone for ChannelMonitor<Signer> where Signer: Clone {
880 fn clone(&self) -> Self {
881 let inner = self.inner.lock().unwrap().clone();
882 ChannelMonitor::from_impl(inner)
883 }
884}
885
886#[derive(Clone, PartialEq)]
887pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
888 latest_update_id: u64,
889 commitment_transaction_number_obscure_factor: u64,
890
891 destination_script: ScriptBuf,
892 broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>,
893 counterparty_payment_script: ScriptBuf,
894 shutdown_script: Option<ScriptBuf>,
895
896 channel_keys_id: [u8; 32],
897 holder_revocation_basepoint: RevocationBasepoint,
898 channel_id: ChannelId,
899 funding_info: (OutPoint, ScriptBuf),
900 current_counterparty_commitment_txid: Option<Txid>,
901 prev_counterparty_commitment_txid: Option<Txid>,
902
903 counterparty_commitment_params: CounterpartyCommitmentParameters,
904 funding_redeemscript: ScriptBuf,
905 channel_value_satoshis: u64,
906 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
908
909 on_holder_tx_csv: u16,
910
911 commitment_secrets: CounterpartyCommitmentSecrets,
912 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
916 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
922 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
927
928 counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
929
930 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
935 current_holder_commitment_tx: HolderSignedTx,
936
937 current_counterparty_commitment_number: u64,
940 current_holder_commitment_number: u64,
943
944 payment_preimages: HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)>,
957
958 pending_monitor_events: Vec<MonitorEvent>,
968
969 pub(super) pending_events: Vec<Event>,
970 pub(super) is_processing_pending_events: bool,
971
972 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
976
977 outputs_to_watch: HashMap<Txid, Vec<(u32, ScriptBuf)>>,
982
983 #[cfg(test)]
984 pub onchain_tx_handler: OnchainTxHandler<Signer>,
985 #[cfg(not(test))]
986 onchain_tx_handler: OnchainTxHandler<Signer>,
987
988 lockdown_from_offchain: bool,
992
993 holder_tx_signed: bool,
1001
1002 funding_spend_seen: bool,
1006
1007 holder_pays_commitment_tx_fee: Option<bool>,
1010
1011 funding_spend_confirmed: Option<Txid>,
1014
1015 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
1016 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
1020
1021 htlcs_resolved_to_user: HashSet<SentHTLCId>,
1028
1029 spendable_txids_confirmed: Vec<Txid>,
1035
1036 best_block: BestBlock,
1042
1043 counterparty_node_id: Option<PublicKey>,
1045
1046 initial_counterparty_commitment_info: Option<(PublicKey, u32, u64, u64)>,
1053
1054 balances_empty_height: Option<u32>,
1056
1057 failed_back_htlc_ids: HashSet<SentHTLCId>,
1062}
1063
1064pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
1066
1067impl<Signer: EcdsaChannelSigner> PartialEq for ChannelMonitor<Signer> where Signer: PartialEq {
1068 fn eq(&self, other: &Self) -> bool {
1069 use crate::sync::LockTestExt;
1070 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1074 let a = if ord {
1075 self.inner.unsafe_well_ordered_double_lock_self()
1076 } else {
1077 other.inner.unsafe_well_ordered_double_lock_self()
1078 };
1079 let b = if ord {
1080 other.inner.unsafe_well_ordered_double_lock_self()
1081 } else {
1082 self.inner.unsafe_well_ordered_double_lock_self()
1083 };
1084 a.eq(&b)
1085 }
1086}
1087
1088impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
1089 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1090 self.inner.lock().unwrap().write(writer)
1091 }
1092}
1093
1094const SERIALIZATION_VERSION: u8 = 1;
1096const MIN_SERIALIZATION_VERSION: u8 = 1;
1097
1098impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
1099 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1100 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1101
1102 self.latest_update_id.write(writer)?;
1103
1104 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
1106
1107 self.destination_script.write(writer)?;
1108 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
1109 writer.write_all(&[0; 1])?;
1110 broadcasted_holder_revokable_script.0.write(writer)?;
1111 broadcasted_holder_revokable_script.1.write(writer)?;
1112 broadcasted_holder_revokable_script.2.write(writer)?;
1113 } else {
1114 writer.write_all(&[1; 1])?;
1115 }
1116
1117 self.counterparty_payment_script.write(writer)?;
1118 match &self.shutdown_script {
1119 Some(script) => script.write(writer)?,
1120 None => ScriptBuf::new().write(writer)?,
1121 }
1122
1123 self.channel_keys_id.write(writer)?;
1124 self.holder_revocation_basepoint.write(writer)?;
1125 writer.write_all(&self.funding_info.0.txid[..])?;
1126 writer.write_all(&self.funding_info.0.index.to_be_bytes())?;
1127 self.funding_info.1.write(writer)?;
1128 self.current_counterparty_commitment_txid.write(writer)?;
1129 self.prev_counterparty_commitment_txid.write(writer)?;
1130
1131 self.counterparty_commitment_params.write(writer)?;
1132 self.funding_redeemscript.write(writer)?;
1133 self.channel_value_satoshis.write(writer)?;
1134
1135 match self.their_cur_per_commitment_points {
1136 Some((idx, pubkey, second_option)) => {
1137 writer.write_all(&byte_utils::be48_to_array(idx))?;
1138 writer.write_all(&pubkey.serialize())?;
1139 match second_option {
1140 Some(second_pubkey) => {
1141 writer.write_all(&second_pubkey.serialize())?;
1142 },
1143 None => {
1144 writer.write_all(&[0; 33])?;
1145 },
1146 }
1147 },
1148 None => {
1149 writer.write_all(&byte_utils::be48_to_array(0))?;
1150 },
1151 }
1152
1153 writer.write_all(&self.on_holder_tx_csv.to_be_bytes())?;
1154
1155 self.commitment_secrets.write(writer)?;
1156
1157 macro_rules! serialize_htlc_in_commitment {
1158 ($htlc_output: expr) => {
1159 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1160 writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
1161 writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
1162 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1163 $htlc_output.transaction_output_index.write(writer)?;
1164 }
1165 }
1166
1167 writer.write_all(&(self.counterparty_claimable_outpoints.len() as u64).to_be_bytes())?;
1168 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
1169 writer.write_all(&txid[..])?;
1170 writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
1171 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1172 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
1173 || Some(**txid) == self.prev_counterparty_commitment_txid,
1174 "HTLC Sources for all revoked commitment transactions should be none!");
1175 serialize_htlc_in_commitment!(htlc_output);
1176 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1177 }
1178 }
1179
1180 writer.write_all(&(self.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes())?;
1181 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
1182 writer.write_all(&txid[..])?;
1183 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1184 }
1185
1186 writer.write_all(&(self.counterparty_hash_commitment_number.len() as u64).to_be_bytes())?;
1187 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
1188 writer.write_all(&payment_hash.0[..])?;
1189 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1190 }
1191
1192 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
1193 writer.write_all(&[1; 1])?;
1194 prev_holder_tx.write(writer)?;
1195 } else {
1196 writer.write_all(&[0; 1])?;
1197 }
1198
1199 self.current_holder_commitment_tx.write(writer)?;
1200
1201 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
1202 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
1203
1204 writer.write_all(&(self.payment_preimages.len() as u64).to_be_bytes())?;
1205 for (payment_preimage, _) in self.payment_preimages.values() {
1206 writer.write_all(&payment_preimage.0[..])?;
1207 }
1208
1209 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
1210 MonitorEvent::HTLCEvent(_) => true,
1211 MonitorEvent::HolderForceClosed(_) => true,
1212 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1213 _ => false,
1214 }).count() as u64).to_be_bytes())?;
1215 for event in self.pending_monitor_events.iter() {
1216 match event {
1217 MonitorEvent::HTLCEvent(upd) => {
1218 0u8.write(writer)?;
1219 upd.write(writer)?;
1220 },
1221 MonitorEvent::HolderForceClosed(_) => 1u8.write(writer)?,
1222 MonitorEvent::HolderForceClosedWithInfo { .. } => 1u8.write(writer)?,
1226 _ => {}, }
1228 }
1229
1230 writer.write_all(&(self.pending_events.len() as u64).to_be_bytes())?;
1231 for event in self.pending_events.iter() {
1232 event.write(writer)?;
1233 }
1234
1235 self.best_block.block_hash.write(writer)?;
1236 writer.write_all(&self.best_block.height.to_be_bytes())?;
1237
1238 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
1239 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
1240 entry.write(writer)?;
1241 }
1242
1243 (self.outputs_to_watch.len() as u64).write(writer)?;
1244 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
1245 txid.write(writer)?;
1246 (idx_scripts.len() as u64).write(writer)?;
1247 for (idx, script) in idx_scripts.iter() {
1248 idx.write(writer)?;
1249 script.write(writer)?;
1250 }
1251 }
1252 self.onchain_tx_handler.write(writer)?;
1253
1254 self.lockdown_from_offchain.write(writer)?;
1255 self.holder_tx_signed.write(writer)?;
1256
1257 let pending_monitor_events = match self.pending_monitor_events.iter().find(|ev| match ev {
1259 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1260 _ => false,
1261 }) {
1262 Some(MonitorEvent::HolderForceClosedWithInfo { outpoint, .. }) => {
1263 let mut pending_monitor_events = self.pending_monitor_events.clone();
1264 pending_monitor_events.push(MonitorEvent::HolderForceClosed(*outpoint));
1265 pending_monitor_events
1266 }
1267 _ => self.pending_monitor_events.clone(),
1268 };
1269
1270 write_tlv_fields!(writer, {
1271 (1, self.funding_spend_confirmed, option),
1272 (3, self.htlcs_resolved_on_chain, required_vec),
1273 (5, pending_monitor_events, required_vec),
1274 (7, self.funding_spend_seen, required),
1275 (9, self.counterparty_node_id, option),
1276 (11, self.confirmed_commitment_tx_counterparty_output, option),
1277 (13, self.spendable_txids_confirmed, required_vec),
1278 (15, self.counterparty_fulfilled_htlcs, required),
1279 (17, self.initial_counterparty_commitment_info, option),
1280 (19, self.channel_id, required),
1281 (21, self.balances_empty_height, option),
1282 (23, self.holder_pays_commitment_tx_fee, option),
1283 (25, self.payment_preimages, required),
1284 (33, self.htlcs_resolved_to_user, required),
1285 });
1286
1287 Ok(())
1288 }
1289}
1290
1291macro_rules! _process_events_body {
1292 ($self_opt: expr, $logger: expr, $event_to_handle: expr, $handle_event: expr) => {
1293 loop {
1294 let mut handling_res = Ok(());
1295 let (pending_events, repeated_events);
1296 if let Some(us) = $self_opt {
1297 let mut inner = us.inner.lock().unwrap();
1298 if inner.is_processing_pending_events {
1299 break handling_res;
1300 }
1301 inner.is_processing_pending_events = true;
1302
1303 pending_events = inner.pending_events.clone();
1304 repeated_events = inner.get_repeated_events();
1305 } else { break handling_res; }
1306
1307 let mut num_handled_events = 0;
1308 for event in pending_events {
1309 log_trace!($logger, "Handling event {:?}...", event);
1310 $event_to_handle = event;
1311 let event_handling_result = $handle_event;
1312 log_trace!($logger, "Done handling event, result: {:?}", event_handling_result);
1313 match event_handling_result {
1314 Ok(()) => num_handled_events += 1,
1315 Err(e) => {
1316 handling_res = Err(e);
1319 break;
1320 }
1321 }
1322 }
1323
1324 if handling_res.is_ok() {
1325 for event in repeated_events {
1326 $event_to_handle = event;
1329 let _ = $handle_event;
1330 }
1331 }
1332
1333 if let Some(us) = $self_opt {
1334 let mut inner = us.inner.lock().unwrap();
1335 inner.pending_events.drain(..num_handled_events);
1336 inner.is_processing_pending_events = false;
1337 if handling_res.is_ok() && !inner.pending_events.is_empty() {
1338 continue;
1341 }
1342 }
1343 break handling_res;
1344 }
1345 }
1346}
1347pub(super) use _process_events_body as process_events_body;
1348
1349pub(crate) struct WithChannelMonitor<'a, L: Deref> where L::Target: Logger {
1350 logger: &'a L,
1351 peer_id: Option<PublicKey>,
1352 channel_id: Option<ChannelId>,
1353 payment_hash: Option<PaymentHash>,
1354}
1355
1356impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger {
1357 fn log(&self, mut record: Record) {
1358 record.peer_id = self.peer_id;
1359 record.channel_id = self.channel_id;
1360 record.payment_hash = self.payment_hash;
1361 self.logger.log(record)
1362 }
1363}
1364
1365impl<'a, L: Deref> WithChannelMonitor<'a, L> where L::Target: Logger {
1366 pub(crate) fn from<S: EcdsaChannelSigner>(logger: &'a L, monitor: &ChannelMonitor<S>, payment_hash: Option<PaymentHash>) -> Self {
1367 Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash)
1368 }
1369
1370 pub(crate) fn from_impl<S: EcdsaChannelSigner>(logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>, payment_hash: Option<PaymentHash>) -> Self {
1371 let peer_id = monitor_impl.counterparty_node_id;
1372 let channel_id = Some(monitor_impl.channel_id());
1373 WithChannelMonitor {
1374 logger, peer_id, channel_id, payment_hash,
1375 }
1376 }
1377}
1378
1379impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
1380 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1384 ChannelMonitor { inner: Mutex::new(imp) }
1385 }
1386
1387 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1388 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, ScriptBuf),
1389 channel_parameters: &ChannelTransactionParameters, holder_pays_commitment_tx_fee: bool,
1390 funding_redeemscript: ScriptBuf, channel_value_satoshis: u64,
1391 commitment_transaction_number_obscure_factor: u64,
1392 initial_holder_commitment_tx: HolderCommitmentTransaction,
1393 best_block: BestBlock, counterparty_node_id: PublicKey, channel_id: ChannelId,
1394 ) -> ChannelMonitor<Signer> {
1395
1396 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1397 let counterparty_payment_script = chan_utils::get_counterparty_payment_script(
1398 &channel_parameters.channel_type_features, &keys.pubkeys().payment_point
1399 );
1400
1401 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1402 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1403 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1404 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1405
1406 let channel_keys_id = keys.channel_keys_id();
1407 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1408
1409 let (holder_commitment_tx, current_holder_commitment_number) = {
1411 let trusted_tx = initial_holder_commitment_tx.trust();
1412 let txid = trusted_tx.txid();
1413
1414 let tx_keys = trusted_tx.keys();
1415 let holder_commitment_tx = HolderSignedTx {
1416 txid,
1417 revocation_key: tx_keys.revocation_key,
1418 a_htlc_key: tx_keys.broadcaster_htlc_key,
1419 b_htlc_key: tx_keys.countersignatory_htlc_key,
1420 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1421 per_commitment_point: tx_keys.per_commitment_point,
1422 htlc_outputs: Vec::new(), to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1424 feerate_per_kw: trusted_tx.feerate_per_kw(),
1425 };
1426 (holder_commitment_tx, trusted_tx.commitment_number())
1427 };
1428
1429 let onchain_tx_handler = OnchainTxHandler::new(
1430 channel_value_satoshis, channel_keys_id, destination_script.into(), keys,
1431 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx
1432 );
1433
1434 let mut outputs_to_watch = new_hash_map();
1435 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1436
1437 Self::from_impl(ChannelMonitorImpl {
1438 latest_update_id: 0,
1439 commitment_transaction_number_obscure_factor,
1440
1441 destination_script: destination_script.into(),
1442 broadcasted_holder_revokable_script: None,
1443 counterparty_payment_script,
1444 shutdown_script,
1445
1446 channel_keys_id,
1447 holder_revocation_basepoint,
1448 channel_id,
1449 funding_info,
1450 current_counterparty_commitment_txid: None,
1451 prev_counterparty_commitment_txid: None,
1452
1453 counterparty_commitment_params,
1454 funding_redeemscript,
1455 channel_value_satoshis,
1456 their_cur_per_commitment_points: None,
1457
1458 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1459
1460 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1461 counterparty_claimable_outpoints: new_hash_map(),
1462 counterparty_commitment_txn_on_chain: new_hash_map(),
1463 counterparty_hash_commitment_number: new_hash_map(),
1464 counterparty_fulfilled_htlcs: new_hash_map(),
1465
1466 prev_holder_signed_commitment_tx: None,
1467 current_holder_commitment_tx: holder_commitment_tx,
1468 current_counterparty_commitment_number: 1 << 48,
1469 current_holder_commitment_number,
1470
1471 payment_preimages: new_hash_map(),
1472 pending_monitor_events: Vec::new(),
1473 pending_events: Vec::new(),
1474 is_processing_pending_events: false,
1475
1476 onchain_events_awaiting_threshold_conf: Vec::new(),
1477 outputs_to_watch,
1478
1479 onchain_tx_handler,
1480
1481 holder_pays_commitment_tx_fee: Some(holder_pays_commitment_tx_fee),
1482 lockdown_from_offchain: false,
1483 holder_tx_signed: false,
1484 funding_spend_seen: false,
1485 funding_spend_confirmed: None,
1486 confirmed_commitment_tx_counterparty_output: None,
1487 htlcs_resolved_on_chain: Vec::new(),
1488 htlcs_resolved_to_user: new_hash_set(),
1489 spendable_txids_confirmed: Vec::new(),
1490
1491 best_block,
1492 counterparty_node_id: Some(counterparty_node_id),
1493 initial_counterparty_commitment_info: None,
1494 balances_empty_height: None,
1495
1496 failed_back_htlc_ids: new_hash_set(),
1497 })
1498 }
1499
1500 #[cfg(test)]
1501 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1502 self.inner.lock().unwrap().provide_secret(idx, secret)
1503 }
1504
1505 pub(crate) fn provide_initial_counterparty_commitment_tx<L: Deref>(
1513 &self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1514 commitment_number: u64, their_cur_per_commitment_point: PublicKey, feerate_per_kw: u32,
1515 to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, logger: &L,
1516 )
1517 where L::Target: Logger
1518 {
1519 let mut inner = self.inner.lock().unwrap();
1520 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1521 inner.provide_initial_counterparty_commitment_tx(txid,
1522 htlc_outputs, commitment_number, their_cur_per_commitment_point, feerate_per_kw,
1523 to_broadcaster_value_sat, to_countersignatory_value_sat, &logger);
1524 }
1525
1526 #[cfg(test)]
1531 fn provide_latest_counterparty_commitment_tx<L: Deref>(
1532 &self,
1533 txid: Txid,
1534 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1535 commitment_number: u64,
1536 their_per_commitment_point: PublicKey,
1537 logger: &L,
1538 ) where L::Target: Logger {
1539 let mut inner = self.inner.lock().unwrap();
1540 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1541 inner.provide_latest_counterparty_commitment_tx(
1542 txid, htlc_outputs, commitment_number, their_per_commitment_point, &logger)
1543 }
1544
1545 #[cfg(test)]
1546 fn provide_latest_holder_commitment_tx(
1547 &self, holder_commitment_tx: HolderCommitmentTransaction,
1548 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1549 ) {
1550 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new())
1551 }
1552
1553 pub(crate) fn provide_payment_preimage_unsafe_legacy<B: Deref, F: Deref, L: Deref>(
1564 &self,
1565 payment_hash: &PaymentHash,
1566 payment_preimage: &PaymentPreimage,
1567 broadcaster: &B,
1568 fee_estimator: &LowerBoundedFeeEstimator<F>,
1569 logger: &L,
1570 ) where
1571 B::Target: BroadcasterInterface,
1572 F::Target: FeeEstimator,
1573 L::Target: Logger,
1574 {
1575 let mut inner = self.inner.lock().unwrap();
1576 let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash));
1577 inner.provide_payment_preimage(
1581 payment_hash, payment_preimage, &None, broadcaster, fee_estimator, &logger)
1582 }
1583
1584 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1589 &self,
1590 updates: &ChannelMonitorUpdate,
1591 broadcaster: &B,
1592 fee_estimator: &F,
1593 logger: &L,
1594 ) -> Result<(), ()>
1595 where
1596 B::Target: BroadcasterInterface,
1597 F::Target: FeeEstimator,
1598 L::Target: Logger,
1599 {
1600 let mut inner = self.inner.lock().unwrap();
1601 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1602 inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
1603 }
1604
1605 pub fn get_latest_update_id(&self) -> u64 {
1610 self.inner.lock().unwrap().get_latest_update_id()
1611 }
1612
1613 pub fn get_funding_txo(&self) -> (OutPoint, ScriptBuf) {
1615 self.inner.lock().unwrap().get_funding_txo().clone()
1616 }
1617
1618 pub fn channel_id(&self) -> ChannelId {
1620 self.inner.lock().unwrap().channel_id()
1621 }
1622
1623 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
1626 self.inner.lock().unwrap().get_outputs_to_watch()
1627 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1628 }
1629
1630 pub fn load_outputs_to_watch<F: Deref, L: Deref>(&self, filter: &F, logger: &L)
1634 where
1635 F::Target: chain::Filter, L::Target: Logger,
1636 {
1637 let lock = self.inner.lock().unwrap();
1638 let logger = WithChannelMonitor::from_impl(logger, &*lock, None);
1639 log_trace!(&logger, "Registering funding outpoint {}", &lock.get_funding_txo().0);
1640 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1641 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1642 for (index, script_pubkey) in outputs.iter() {
1643 assert!(*index <= u16::MAX as u32);
1644 let outpoint = OutPoint { txid: *txid, index: *index as u16 };
1645 log_trace!(logger, "Registering outpoint {} with the filter for monitoring spends", outpoint);
1646 filter.register_output(WatchedOutput {
1647 block_hash: None,
1648 outpoint,
1649 script_pubkey: script_pubkey.clone(),
1650 });
1651 }
1652 }
1653 }
1654
1655 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1658 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1659 }
1660
1661 pub fn process_pending_events<H: Deref, L: Deref>(&self, handler: &H, logger: &L)
1677 -> Result<(), ReplayEvent> where H::Target: EventHandler, L::Target: Logger {
1678 let mut ev;
1679 process_events_body!(Some(self), logger, ev, handler.handle_event(ev))
1680 }
1681
1682 pub async fn process_pending_events_async<
1686 Future: core::future::Future<Output = Result<(), ReplayEvent>>, H: Fn(Event) -> Future,
1687 L: Deref,
1688 >(
1689 &self, handler: &H, logger: &L,
1690 ) -> Result<(), ReplayEvent> where L::Target: Logger {
1691 let mut ev;
1692 process_events_body!(Some(self), logger, ev, { handler(ev).await })
1693 }
1694
1695 #[cfg(test)]
1696 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1697 let mut ret = Vec::new();
1698 let mut lck = self.inner.lock().unwrap();
1699 mem::swap(&mut ret, &mut lck.pending_events);
1700 ret.append(&mut lck.get_repeated_events());
1701 ret
1702 }
1703
1704 pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
1717 self.inner.lock().unwrap().initial_counterparty_commitment_tx()
1718 }
1719
1720 pub fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
1741 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
1742 }
1743
1744 pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
1762 self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
1763 }
1764
1765 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1766 self.inner.lock().unwrap().get_min_seen_secret()
1767 }
1768
1769 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1770 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1771 }
1772
1773 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1774 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1775 }
1776
1777 pub(crate) fn no_further_updates_allowed(&self) -> bool {
1784 self.inner.lock().unwrap().no_further_updates_allowed()
1785 }
1786
1787 pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1792 self.inner.lock().unwrap().counterparty_node_id
1793 }
1794
1795 pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
1805 &self, broadcaster: &B, fee_estimator: &F, logger: &L
1806 )
1807 where
1808 B::Target: BroadcasterInterface,
1809 F::Target: FeeEstimator,
1810 L::Target: Logger
1811 {
1812 let mut inner = self.inner.lock().unwrap();
1813 let fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
1814 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1815 inner.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &fee_estimator, &logger);
1816 }
1817
1818 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1822 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1823 where L::Target: Logger {
1824 let mut inner = self.inner.lock().unwrap();
1825 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1826 inner.unsafe_get_latest_holder_commitment_txn(&logger)
1827 }
1828
1829 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1841 &self,
1842 header: &Header,
1843 txdata: &TransactionData,
1844 height: u32,
1845 broadcaster: B,
1846 fee_estimator: F,
1847 logger: &L,
1848 ) -> Vec<TransactionOutputs>
1849 where
1850 B::Target: BroadcasterInterface,
1851 F::Target: FeeEstimator,
1852 L::Target: Logger,
1853 {
1854 let mut inner = self.inner.lock().unwrap();
1855 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1856 inner.block_connected(
1857 header, txdata, height, broadcaster, fee_estimator, &logger)
1858 }
1859
1860 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1863 &self,
1864 header: &Header,
1865 height: u32,
1866 broadcaster: B,
1867 fee_estimator: F,
1868 logger: &L,
1869 ) where
1870 B::Target: BroadcasterInterface,
1871 F::Target: FeeEstimator,
1872 L::Target: Logger,
1873 {
1874 let mut inner = self.inner.lock().unwrap();
1875 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1876 inner.block_disconnected(
1877 header, height, broadcaster, fee_estimator, &logger)
1878 }
1879
1880 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1888 &self,
1889 header: &Header,
1890 txdata: &TransactionData,
1891 height: u32,
1892 broadcaster: B,
1893 fee_estimator: F,
1894 logger: &L,
1895 ) -> Vec<TransactionOutputs>
1896 where
1897 B::Target: BroadcasterInterface,
1898 F::Target: FeeEstimator,
1899 L::Target: Logger,
1900 {
1901 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1902 let mut inner = self.inner.lock().unwrap();
1903 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1904 inner.transactions_confirmed(
1905 header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
1906 }
1907
1908 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1915 &self,
1916 txid: &Txid,
1917 broadcaster: B,
1918 fee_estimator: F,
1919 logger: &L,
1920 ) where
1921 B::Target: BroadcasterInterface,
1922 F::Target: FeeEstimator,
1923 L::Target: Logger,
1924 {
1925 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1926 let mut inner = self.inner.lock().unwrap();
1927 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1928 inner.transaction_unconfirmed(
1929 txid, broadcaster, &bounded_fee_estimator, &logger
1930 );
1931 }
1932
1933 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1941 &self,
1942 header: &Header,
1943 height: u32,
1944 broadcaster: B,
1945 fee_estimator: F,
1946 logger: &L,
1947 ) -> Vec<TransactionOutputs>
1948 where
1949 B::Target: BroadcasterInterface,
1950 F::Target: FeeEstimator,
1951 L::Target: Logger,
1952 {
1953 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1954 let mut inner = self.inner.lock().unwrap();
1955 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1956 inner.best_block_updated(
1957 header, height, broadcaster, &bounded_fee_estimator, &logger
1958 )
1959 }
1960
1961 pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
1963 let inner = self.inner.lock().unwrap();
1964 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
1965 .iter()
1966 .map(|entry| (entry.txid, entry.height, entry.block_hash))
1967 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1968 .collect();
1969 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
1970 txids.dedup_by_key(|(txid, _, _)| *txid);
1971 txids
1972 }
1973
1974 pub fn current_best_block(&self) -> BestBlock {
1977 self.inner.lock().unwrap().best_block.clone()
1978 }
1979
1980 pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
1986 &self, broadcaster: B, fee_estimator: F, logger: &L,
1987 )
1988 where
1989 B::Target: BroadcasterInterface,
1990 F::Target: FeeEstimator,
1991 L::Target: Logger,
1992 {
1993 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1994 let mut inner = self.inner.lock().unwrap();
1995 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1996 let current_height = inner.best_block.height;
1997 let conf_target = inner.closure_conf_target();
1998 inner.onchain_tx_handler.rebroadcast_pending_claims(
1999 current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, conf_target, &fee_estimator, &logger,
2000 );
2001 }
2002
2003 pub fn has_pending_claims(&self) -> bool
2005 {
2006 self.inner.lock().unwrap().onchain_tx_handler.has_pending_claims()
2007 }
2008
2009 pub fn signer_unblocked<B: Deref, F: Deref, L: Deref>(
2012 &self, broadcaster: B, fee_estimator: F, logger: &L,
2013 )
2014 where
2015 B::Target: BroadcasterInterface,
2016 F::Target: FeeEstimator,
2017 L::Target: Logger,
2018 {
2019 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
2020 let mut inner = self.inner.lock().unwrap();
2021 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
2022 let current_height = inner.best_block.height;
2023 let conf_target = inner.closure_conf_target();
2024 inner.onchain_tx_handler.rebroadcast_pending_claims(
2025 current_height, FeerateStrategy::RetryPrevious, &broadcaster, conf_target, &fee_estimator, &logger,
2026 );
2027 }
2028
2029 pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
2048 let inner = self.inner.lock().unwrap();
2049 let current_height = inner.best_block.height;
2050 let mut spendable_outputs = inner.get_spendable_outputs(tx);
2051 spendable_outputs.retain(|descriptor| {
2052 let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
2053 if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
2054 conf_threshold = cmp::min(conf_threshold,
2055 current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
2056 }
2057 conf_threshold >= confirmation_height
2058 });
2059 spendable_outputs
2060 }
2061
2062 pub fn check_and_update_full_resolution_status<L: Logger>(&self, logger: &L) -> (bool, bool) {
2077 let mut is_all_funds_claimed = self.get_claimable_balances().is_empty();
2078 let current_height = self.current_best_block().height;
2079 let mut inner = self.inner.lock().unwrap();
2080
2081 if inner.is_closed_without_updates()
2082 && is_all_funds_claimed
2083 && !inner.funding_spend_seen
2084 {
2085 return (true, false);
2089 }
2090
2091 if is_all_funds_claimed && !inner.funding_spend_seen {
2092 debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2093 is_all_funds_claimed = false;
2094 }
2095
2096 let preimages_not_needed_elsewhere = inner.pending_monitor_events.is_empty();
2100
2101 match (inner.balances_empty_height, is_all_funds_claimed, preimages_not_needed_elsewhere) {
2102 (Some(balances_empty_height), true, true) => {
2103 (current_height >= balances_empty_height + ARCHIVAL_DELAY_BLOCKS, false)
2105 },
2106 (Some(_), false, _)|(Some(_), _, false) => {
2107 debug_assert!(false,
2112 "Thought we were done claiming funds, but claimable_balances now has entries");
2113 log_error!(logger,
2114 "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",
2115 inner.get_funding_txo().0);
2116 inner.balances_empty_height = None;
2117 (false, true)
2118 },
2119 (None, true, true) => {
2120 log_debug!(logger,
2123 "ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
2124 inner.get_funding_txo().0, ARCHIVAL_DELAY_BLOCKS);
2125 inner.balances_empty_height = Some(current_height);
2126 (false, true)
2127 },
2128 (None, false, _)|(None, _, false) => {
2129 (false, false)
2131 },
2132 }
2133 }
2134
2135 #[cfg(test)]
2136 pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
2137 self.inner.lock().unwrap().counterparty_payment_script.clone()
2138 }
2139
2140 #[cfg(test)]
2141 pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
2142 self.inner.lock().unwrap().counterparty_payment_script = script;
2143 }
2144
2145 #[cfg(test)]
2146 pub fn do_mut_signer_call<F: FnMut(&mut Signer) -> ()>(&self, mut f: F) {
2147 let mut inner = self.inner.lock().unwrap();
2148 f(&mut inner.onchain_tx_handler.signer);
2149 }
2150}
2151
2152impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2153 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, source: Option<&HTLCSource>,
2156 holder_commitment: bool, counterparty_revoked_commitment: bool,
2157 confirmed_txid: Option<Txid>
2158 ) -> Option<Balance> {
2159 let htlc_commitment_tx_output_idx = htlc.transaction_output_index?;
2160
2161 let mut htlc_spend_txid_opt = None;
2162 let mut htlc_spend_tx_opt = None;
2163 let mut holder_timeout_spend_pending = None;
2164 let mut htlc_spend_pending = None;
2165 let mut holder_delayed_output_pending = None;
2166 for event in self.onchain_events_awaiting_threshold_conf.iter() {
2167 match event.event {
2168 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
2169 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
2170 debug_assert!(htlc_spend_txid_opt.is_none());
2171 htlc_spend_txid_opt = Some(&event.txid);
2172 debug_assert!(htlc_spend_tx_opt.is_none());
2173 htlc_spend_tx_opt = event.transaction.as_ref();
2174 debug_assert!(holder_timeout_spend_pending.is_none());
2175 debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
2176 holder_timeout_spend_pending = Some(event.confirmation_threshold());
2177 },
2178 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
2179 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
2180 debug_assert!(htlc_spend_txid_opt.is_none());
2181 htlc_spend_txid_opt = Some(&event.txid);
2182 debug_assert!(htlc_spend_tx_opt.is_none());
2183 htlc_spend_tx_opt = event.transaction.as_ref();
2184 debug_assert!(htlc_spend_pending.is_none());
2185 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
2186 },
2187 OnchainEvent::MaturingOutput {
2188 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
2189 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
2190 .any(|(input_idx, inp)|
2191 Some(inp.previous_output.txid) == confirmed_txid &&
2192 inp.previous_output.vout == htlc_commitment_tx_output_idx &&
2193 descriptor.outpoint.index as usize == input_idx
2199 ))
2200 .unwrap_or(false)
2201 => {
2202 debug_assert!(holder_delayed_output_pending.is_none());
2203 holder_delayed_output_pending = Some(event.confirmation_threshold());
2204 },
2205 _ => {},
2206 }
2207 }
2208 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
2209 .any(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
2210 debug_assert!(htlc_spend_txid_opt.is_none());
2211 htlc_spend_txid_opt = v.resolving_txid.as_ref();
2212 debug_assert!(htlc_spend_tx_opt.is_none());
2213 htlc_spend_tx_opt = v.resolving_tx.as_ref();
2214 true
2215 } else { false });
2216 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved as u8 <= 1);
2217
2218 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
2219 let htlc_output_to_spend =
2220 if let Some(txid) = htlc_spend_txid_opt {
2221 if let Some(ref tx) = htlc_spend_tx_opt {
2226 let htlc_input_idx_opt = tx.input.iter().enumerate()
2227 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2228 .map(|(idx, _)| idx as u32);
2229 debug_assert!(htlc_input_idx_opt.is_some());
2230 BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2231 } else {
2232 debug_assert!(!self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2233 BitcoinOutPoint::new(*txid, 0)
2234 }
2235 } else {
2236 htlc_commitment_outpoint
2237 };
2238 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2239
2240 if let Some(conf_thresh) = holder_delayed_output_pending {
2241 debug_assert!(holder_commitment);
2242 return Some(Balance::ClaimableAwaitingConfirmations {
2243 amount_satoshis: htlc.amount_msat / 1000,
2244 confirmation_height: conf_thresh,
2245 source: BalanceSource::Htlc,
2246 });
2247 } else if htlc_resolved && !htlc_output_spend_pending {
2248 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2254 } else if counterparty_revoked_commitment {
2255 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2256 if let OnchainEvent::MaturingOutput {
2257 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2258 } = &event.event {
2259 event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2260 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2261 tx.compute_txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2262 } else {
2263 Some(inp.previous_output.txid) == confirmed_txid &&
2264 inp.previous_output.vout == htlc_commitment_tx_output_idx
2265 }
2266 })).unwrap_or(false)
2267 } else {
2268 false
2269 }
2270 });
2271 if htlc_output_claim_pending {
2272 } else {
2277 debug_assert!(holder_timeout_spend_pending.is_none(),
2278 "HTLCUpdate OnchainEvents should never appear for preimage claims");
2279 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2280 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2281 return Some(Balance::CounterpartyRevokedOutputClaimable {
2282 amount_satoshis: htlc.amount_msat / 1000,
2283 });
2284 }
2285 } else if htlc.offered == holder_commitment {
2286 if let Some(conf_thresh) = holder_timeout_spend_pending {
2290 return Some(Balance::ClaimableAwaitingConfirmations {
2291 amount_satoshis: htlc.amount_msat / 1000,
2292 confirmation_height: conf_thresh,
2293 source: BalanceSource::Htlc,
2294 });
2295 } else {
2296 let outbound_payment = match source {
2297 None => {
2298 debug_assert!(false, "Outbound HTLCs should have a source");
2299 true
2300 },
2301 Some(&HTLCSource::PreviousHopData(_)) => false,
2302 Some(&HTLCSource::OutboundRoute { .. }) => true,
2303 };
2304 return Some(Balance::MaybeTimeoutClaimableHTLC {
2305 amount_satoshis: htlc.amount_msat / 1000,
2306 claimable_height: htlc.cltv_expiry,
2307 payment_hash: htlc.payment_hash,
2308 outbound_payment,
2309 });
2310 }
2311 } else if let Some((payment_preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
2312 debug_assert!(holder_timeout_spend_pending.is_none());
2318 if let Some((conf_thresh, true)) = htlc_spend_pending {
2319 return Some(Balance::ClaimableAwaitingConfirmations {
2320 amount_satoshis: htlc.amount_msat / 1000,
2321 confirmation_height: conf_thresh,
2322 source: BalanceSource::Htlc,
2323 });
2324 } else {
2325 return Some(Balance::ContentiousClaimable {
2326 amount_satoshis: htlc.amount_msat / 1000,
2327 timeout_height: htlc.cltv_expiry,
2328 payment_hash: htlc.payment_hash,
2329 payment_preimage: *payment_preimage,
2330 });
2331 }
2332 } else if !htlc_resolved {
2333 return Some(Balance::MaybePreimageClaimableHTLC {
2334 amount_satoshis: htlc.amount_msat / 1000,
2335 expiry_height: htlc.cltv_expiry,
2336 payment_hash: htlc.payment_hash,
2337 });
2338 }
2339 None
2340 }
2341}
2342
2343impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
2344 pub fn get_claimable_balances(&self) -> Vec<Balance> {
2359 let mut res = Vec::new();
2360 let us = self.inner.lock().unwrap();
2361
2362 let mut confirmed_txid = us.funding_spend_confirmed;
2363 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
2364 let mut pending_commitment_tx_conf_thresh = None;
2365 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2366 if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
2367 event.event
2368 {
2369 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2370 Some((event.txid, event.confirmation_threshold()))
2371 } else { None }
2372 });
2373 if let Some((txid, conf_thresh)) = funding_spend_pending {
2374 debug_assert!(us.funding_spend_confirmed.is_none(),
2375 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2376 confirmed_txid = Some(txid);
2377 pending_commitment_tx_conf_thresh = Some(conf_thresh);
2378 }
2379
2380 macro_rules! walk_htlcs {
2381 ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2382 for (htlc, source) in $htlc_iter {
2383 if htlc.transaction_output_index.is_some() {
2384
2385 if let Some(bal) = us.get_htlc_balance(
2386 htlc, source, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid
2387 ) {
2388 res.push(bal);
2389 }
2390 }
2391 }
2392 }
2393 }
2394
2395 if let Some(txid) = confirmed_txid {
2396 let mut found_commitment_tx = false;
2397 if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
2398 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2400 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2401 if let OnchainEvent::MaturingOutput {
2402 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2403 } = &event.event {
2404 Some(descriptor.output.value)
2405 } else { None }
2406 }) {
2407 res.push(Balance::ClaimableAwaitingConfirmations {
2408 amount_satoshis: value.to_sat(),
2409 confirmation_height: conf_thresh,
2410 source: BalanceSource::CounterpartyForceClosed,
2411 });
2412 } else {
2413 }
2417 }
2418 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2419 walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2420 } else {
2421 walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2422 let mut spent_counterparty_output = false;
2427 for event in us.onchain_events_awaiting_threshold_conf.iter() {
2428 if let OnchainEvent::MaturingOutput {
2429 descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
2430 } = &event.event {
2431 res.push(Balance::ClaimableAwaitingConfirmations {
2432 amount_satoshis: output.value.to_sat(),
2433 confirmation_height: event.confirmation_threshold(),
2434 source: BalanceSource::CounterpartyForceClosed,
2435 });
2436 if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
2437 if event.transaction.as_ref().map(|tx|
2438 tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
2439 ).unwrap_or(false) {
2440 spent_counterparty_output = true;
2441 }
2442 }
2443 }
2444 }
2445
2446 if spent_counterparty_output {
2447 } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
2448 let output_spendable = us.onchain_tx_handler
2449 .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
2450 if output_spendable {
2451 res.push(Balance::CounterpartyRevokedOutputClaimable {
2452 amount_satoshis: amt.to_sat(),
2453 });
2454 }
2455 } else {
2456 }
2459 }
2460 found_commitment_tx = true;
2461 } else if txid == us.current_holder_commitment_tx.txid {
2462 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())));
2463 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2464 res.push(Balance::ClaimableAwaitingConfirmations {
2465 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2466 confirmation_height: conf_thresh,
2467 source: BalanceSource::HolderForceClosed,
2468 });
2469 }
2470 found_commitment_tx = true;
2471 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2472 if txid == prev_commitment.txid {
2473 walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())));
2474 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2475 res.push(Balance::ClaimableAwaitingConfirmations {
2476 amount_satoshis: prev_commitment.to_self_value_sat,
2477 confirmation_height: conf_thresh,
2478 source: BalanceSource::HolderForceClosed,
2479 });
2480 }
2481 found_commitment_tx = true;
2482 }
2483 }
2484 if !found_commitment_tx {
2485 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2486 res.push(Balance::ClaimableAwaitingConfirmations {
2490 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2491 confirmation_height: conf_thresh,
2492 source: BalanceSource::CoopClose,
2493 });
2494 }
2495 }
2496 } else {
2497 let mut claimable_inbound_htlc_value_sat = 0;
2498 let mut nondust_htlc_count = 0;
2499 let mut outbound_payment_htlc_rounded_msat = 0;
2500 let mut outbound_forwarded_htlc_rounded_msat = 0;
2501 let mut inbound_claiming_htlc_rounded_msat = 0;
2502 let mut inbound_htlc_rounded_msat = 0;
2503 for (htlc, _, source) in us.current_holder_commitment_tx.htlc_outputs.iter() {
2504 if htlc.transaction_output_index.is_some() {
2505 nondust_htlc_count += 1;
2506 }
2507 let rounded_value_msat = if htlc.transaction_output_index.is_none() {
2508 htlc.amount_msat
2509 } else { htlc.amount_msat % 1000 };
2510 if htlc.offered {
2511 let outbound_payment = match source {
2512 None => {
2513 debug_assert!(false, "Outbound HTLCs should have a source");
2514 true
2515 },
2516 Some(HTLCSource::PreviousHopData(_)) => false,
2517 Some(HTLCSource::OutboundRoute { .. }) => true,
2518 };
2519 if outbound_payment {
2520 outbound_payment_htlc_rounded_msat += rounded_value_msat;
2521 } else {
2522 outbound_forwarded_htlc_rounded_msat += rounded_value_msat;
2523 }
2524 if htlc.transaction_output_index.is_some() {
2525 res.push(Balance::MaybeTimeoutClaimableHTLC {
2526 amount_satoshis: htlc.amount_msat / 1000,
2527 claimable_height: htlc.cltv_expiry,
2528 payment_hash: htlc.payment_hash,
2529 outbound_payment,
2530 });
2531 }
2532 } else if us.payment_preimages.contains_key(&htlc.payment_hash) {
2533 inbound_claiming_htlc_rounded_msat += rounded_value_msat;
2534 if htlc.transaction_output_index.is_some() {
2535 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
2536 }
2537 } else {
2538 inbound_htlc_rounded_msat += rounded_value_msat;
2539 if htlc.transaction_output_index.is_some() {
2540 res.push(Balance::MaybePreimageClaimableHTLC {
2543 amount_satoshis: htlc.amount_msat / 1000,
2544 expiry_height: htlc.cltv_expiry,
2545 payment_hash: htlc.payment_hash,
2546 });
2547 }
2548 }
2549 }
2550 let amount_satoshis =
2557 us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat;
2558 if !us.is_closed_without_updates() || amount_satoshis != 0 {
2559 res.push(Balance::ClaimableOnChannelClose {
2560 amount_satoshis,
2561 transaction_fee_satoshis: if us.holder_pays_commitment_tx_fee.unwrap_or(true) {
2562 chan_utils::commit_tx_fee_sat(
2563 us.current_holder_commitment_tx.feerate_per_kw, nondust_htlc_count,
2564 us.onchain_tx_handler.channel_type_features())
2565 } else { 0 },
2566 outbound_payment_htlc_rounded_msat,
2567 outbound_forwarded_htlc_rounded_msat,
2568 inbound_claiming_htlc_rounded_msat,
2569 inbound_htlc_rounded_msat,
2570 });
2571 }
2572 }
2573
2574 res
2575 }
2576
2577 pub(crate) fn get_all_current_outbound_htlcs(
2581 &self,
2582 ) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2583 let mut res = new_hash_map();
2584 let us = self.inner.lock().unwrap();
2587 let mut walk_counterparty_commitment = |txid| {
2588 if let Some(latest_outpoints) = us.counterparty_claimable_outpoints.get(txid) {
2589 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2590 if let &Some(ref source) = source_option {
2591 let htlc_id = SentHTLCId::from_source(source);
2592 if !us.htlcs_resolved_to_user.contains(&htlc_id) {
2593 let preimage_opt =
2594 us.counterparty_fulfilled_htlcs.get(&htlc_id).cloned();
2595 res.insert((**source).clone(), (htlc.clone(), preimage_opt));
2596 }
2597 }
2598 }
2599 }
2600 };
2601 if let Some(ref txid) = us.current_counterparty_commitment_txid {
2602 walk_counterparty_commitment(txid);
2603 }
2604 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
2605 walk_counterparty_commitment(txid);
2606 }
2607 res
2608 }
2609
2610 pub(crate) fn get_onchain_failed_outbound_htlcs(&self) -> HashMap<HTLCSource, PaymentHash> {
2614 let mut res = new_hash_map();
2615 let us = self.inner.lock().unwrap();
2616
2617 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
2621 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2622 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
2623 if event.height + ANTI_REORG_DELAY - 1 <= us.best_block.height {
2624 Some(event.txid)
2625 } else {
2626 None
2627 }
2628 } else {
2629 None
2630 }
2631 })
2632 });
2633
2634 let confirmed_txid = if let Some(txid) = confirmed_txid {
2635 txid
2636 } else {
2637 return res;
2638 };
2639
2640 macro_rules! walk_htlcs {
2641 ($htlc_iter: expr) => {
2642 let mut walk_candidate_htlcs = |htlcs| {
2643 for &(ref candidate_htlc, ref candidate_source) in htlcs {
2644 let candidate_htlc: &HTLCOutputInCommitment = &candidate_htlc;
2645 let candidate_source: &Option<Box<HTLCSource>> = &candidate_source;
2646
2647 let source: &HTLCSource = if let Some(source) = candidate_source {
2648 source
2649 } else {
2650 continue;
2651 };
2652 let htlc_id = SentHTLCId::from_source(source);
2653 if us.htlcs_resolved_to_user.contains(&htlc_id) {
2654 continue;
2655 }
2656
2657 let confirmed = $htlc_iter.find(|(_, conf_src)| Some(source) == *conf_src);
2658 if let Some((confirmed_htlc, _)) = confirmed {
2659 let filter = |v: &&IrrevocablyResolvedHTLC| {
2660 v.commitment_tx_output_idx
2661 == confirmed_htlc.transaction_output_index
2662 };
2663
2664 if confirmed_htlc.transaction_output_index.is_none() {
2667 res.insert(source.clone(), confirmed_htlc.payment_hash);
2670 } else if let Some(state) =
2671 us.htlcs_resolved_on_chain.iter().filter(filter).next()
2672 {
2673 if state.payment_preimage.is_none() {
2674 res.insert(source.clone(), confirmed_htlc.payment_hash);
2675 }
2676 }
2677 } else {
2678 res.insert(source.clone(), candidate_htlc.payment_hash);
2682 }
2683 }
2684 };
2685
2686 if let Some(ref txid) = us.current_counterparty_commitment_txid {
2689 let htlcs = us.counterparty_claimable_outpoints.get(txid);
2690 walk_candidate_htlcs(htlcs.expect("Missing tx info for latest tx"));
2691 }
2692 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
2693 let htlcs = us.counterparty_claimable_outpoints.get(txid);
2694 walk_candidate_htlcs(htlcs.expect("Missing tx info for previous tx"));
2695 }
2696 };
2697 }
2698
2699 if Some(confirmed_txid) == us.current_counterparty_commitment_txid
2700 || Some(confirmed_txid) == us.prev_counterparty_commitment_txid
2701 {
2702 let htlcs = us.counterparty_claimable_outpoints.get(&confirmed_txid).unwrap();
2703 walk_htlcs!(htlcs.iter().filter_map(|(a, b)| {
2704 if let &Some(ref source) = b {
2705 Some((a, Some(&**source)))
2706 } else {
2707 None
2708 }
2709 }));
2710 } else if confirmed_txid == us.current_holder_commitment_tx.txid {
2711 let mut htlcs =
2712 us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref()));
2713 walk_htlcs!(htlcs);
2714 } else if let Some(prev_commitment_tx) = &us.prev_holder_signed_commitment_tx {
2715 if confirmed_txid == prev_commitment_tx.txid {
2716 let mut htlcs =
2717 prev_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref()));
2718 walk_htlcs!(htlcs);
2719 } else {
2720 let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
2721 walk_htlcs!(htlcs_confirmed.iter());
2722 }
2723 } else {
2724 let htlcs_confirmed: &[(&HTLCOutputInCommitment, _)] = &[];
2725 walk_htlcs!(htlcs_confirmed.iter());
2726 }
2727
2728 res
2729 }
2730
2731 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)> {
2732 self.inner.lock().unwrap().payment_preimages.clone()
2733 }
2734}
2735
2736macro_rules! fail_unbroadcast_htlcs {
2752 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
2753 $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
2754 debug_assert_eq!($commitment_tx_confirmed.compute_txid(), $commitment_txid_confirmed);
2755
2756 macro_rules! check_htlc_fails {
2757 ($txid: expr, $commitment_tx: expr, $per_commitment_outpoints: expr) => {
2758 if let Some(ref latest_outpoints) = $per_commitment_outpoints {
2759 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2760 if let &Some(ref source) = source_option {
2761 let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
2771
2772 let mut matched_htlc = false;
2773 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
2774 if broadcast_htlc.transaction_output_index.is_some() &&
2775 (Some(&**source) == *broadcast_source ||
2776 (broadcast_source.is_none() &&
2777 broadcast_htlc.payment_hash == htlc.payment_hash &&
2778 broadcast_htlc.amount_msat == htlc.amount_msat)) {
2779 matched_htlc = true;
2780 break;
2781 }
2782 }
2783 if matched_htlc { continue; }
2784 if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
2785 continue;
2786 }
2787 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2788 if entry.height != $commitment_tx_conf_height { return true; }
2789 match entry.event {
2790 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
2791 *update_source != **source
2792 },
2793 _ => true,
2794 }
2795 });
2796 let entry = OnchainEventEntry {
2797 txid: $commitment_txid_confirmed,
2798 transaction: Some($commitment_tx_confirmed.clone()),
2799 height: $commitment_tx_conf_height,
2800 block_hash: Some(*$commitment_tx_conf_hash),
2801 event: OnchainEvent::HTLCUpdate {
2802 source: (**source).clone(),
2803 payment_hash: htlc.payment_hash.clone(),
2804 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
2805 commitment_tx_output_idx: None,
2806 },
2807 };
2808 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
2809 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
2810 $commitment_txid_confirmed, entry.confirmation_threshold());
2811 $self.onchain_events_awaiting_threshold_conf.push(entry);
2812 }
2813 }
2814 }
2815 }
2816 }
2817 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
2818 check_htlc_fails!(txid, "current", $self.counterparty_claimable_outpoints.get(txid));
2819 }
2820 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
2821 check_htlc_fails!(txid, "previous", $self.counterparty_claimable_outpoints.get(txid));
2822 }
2823 } }
2824}
2825
2826#[cfg(test)]
2831pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
2832 use bitcoin::opcodes;
2833 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
2834 ret[131] = opcodes::all::OP_DROP.to_u8();
2835 ret[132] = opcodes::all::OP_DROP.to_u8();
2836 ret[133] = opcodes::all::OP_DROP.to_u8();
2837 ret[134] = opcodes::all::OP_DROP.to_u8();
2838 ret[135] = opcodes::OP_TRUE.to_u8();
2839 Vec::from(&ret[..])
2840}
2841
2842#[cfg(test)]
2843pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
2844 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
2845}
2846
2847impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2848 fn closure_conf_target(&self) -> ConfirmationTarget {
2851 if !self.current_holder_commitment_tx.htlc_outputs.is_empty() {
2854 return ConfirmationTarget::UrgentOnChainSweep;
2855 }
2856 if self.prev_holder_signed_commitment_tx.as_ref().map(|t| !t.htlc_outputs.is_empty()).unwrap_or(false) {
2857 return ConfirmationTarget::UrgentOnChainSweep;
2858 }
2859 if let Some(txid) = self.current_counterparty_commitment_txid {
2860 if !self.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
2861 return ConfirmationTarget::UrgentOnChainSweep;
2862 }
2863 }
2864 if let Some(txid) = self.prev_counterparty_commitment_txid {
2865 if !self.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
2866 return ConfirmationTarget::UrgentOnChainSweep;
2867 }
2868 }
2869 ConfirmationTarget::OutputSpendingFee
2870 }
2871
2872 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2876 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
2877 return Err("Previous secret did not match new one");
2878 }
2879
2880 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
2883 if self.current_counterparty_commitment_txid.unwrap() != txid {
2884 let cur_claimables = self.counterparty_claimable_outpoints.get(
2885 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2886 for (_, ref source_opt) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2887 if let Some(source) = source_opt {
2888 if !cur_claimables.iter()
2889 .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
2890 {
2891 self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
2892 }
2893 }
2894 }
2895 for &mut (_, ref mut source_opt) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
2896 *source_opt = None;
2897 }
2898 } else {
2899 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
2900 }
2901 }
2902
2903 if !self.payment_preimages.is_empty() {
2904 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
2905 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
2906 let min_idx = self.get_min_seen_secret();
2907 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
2908
2909 self.payment_preimages.retain(|&k, _| {
2910 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
2911 if k == htlc.payment_hash {
2912 return true
2913 }
2914 }
2915 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2916 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2917 if k == htlc.payment_hash {
2918 return true
2919 }
2920 }
2921 }
2922 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2923 if *cn < min_idx {
2924 return true
2925 }
2926 true
2927 } else { false };
2928 if contains {
2929 counterparty_hash_commitment_number.remove(&k);
2930 }
2931 false
2932 });
2933 }
2934
2935 Ok(())
2936 }
2937
2938 fn provide_initial_counterparty_commitment_tx<L: Deref>(
2939 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2940 commitment_number: u64, their_per_commitment_point: PublicKey, feerate_per_kw: u32,
2941 to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &WithChannelMonitor<L>,
2942 ) where L::Target: Logger {
2943 self.initial_counterparty_commitment_info = Some((their_per_commitment_point.clone(),
2944 feerate_per_kw, to_broadcaster_value, to_countersignatory_value));
2945
2946 #[cfg(debug_assertions)] {
2947 let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
2948 debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), txid);
2949 }
2950
2951 self.provide_latest_counterparty_commitment_tx(txid, htlc_outputs, commitment_number,
2952 their_per_commitment_point, logger);
2953 }
2954
2955 fn provide_latest_counterparty_commitment_tx<L: Deref>(
2956 &mut self, txid: Txid,
2957 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2958 commitment_number: u64, their_per_commitment_point: PublicKey, logger: &WithChannelMonitor<L>,
2959 ) where L::Target: Logger {
2960 for &(ref htlc, _) in &htlc_outputs {
2965 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2966 }
2967
2968 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2969 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2970 self.current_counterparty_commitment_txid = Some(txid);
2971 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2972 self.current_counterparty_commitment_number = commitment_number;
2973 match self.their_cur_per_commitment_points {
2975 Some(old_points) => {
2976 if old_points.0 == commitment_number + 1 {
2977 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2978 } else if old_points.0 == commitment_number + 2 {
2979 if let Some(old_second_point) = old_points.2 {
2980 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2981 } else {
2982 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2983 }
2984 } else {
2985 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2986 }
2987 },
2988 None => {
2989 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2990 }
2991 }
2992 }
2993
2994 fn provide_latest_holder_commitment_tx(&mut self, holder_commitment_tx: HolderCommitmentTransaction, mut htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>, claimed_htlcs: &[(SentHTLCId, PaymentPreimage)], nondust_htlc_sources: Vec<HTLCSource>) {
3000 if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
3001 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().htlcs().len());
3005 for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().htlcs().iter()) {
3006 debug_assert_eq!(a, b);
3007 }
3008 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
3009 for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
3010 debug_assert_eq!(a, b);
3011 }
3012 debug_assert!(nondust_htlc_sources.is_empty());
3013 } else {
3014 #[cfg(debug_assertions)] {
3018 let mut prev = -1;
3019 for htlc in holder_commitment_tx.trust().htlcs().iter() {
3020 assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
3021 prev = htlc.transaction_output_index.unwrap() as i32;
3022 }
3023 }
3024 debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
3025 debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
3026 debug_assert_eq!(holder_commitment_tx.trust().htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
3027
3028 let mut sources_iter = nondust_htlc_sources.into_iter();
3029
3030 for (htlc, counterparty_sig) in holder_commitment_tx.trust().htlcs().iter()
3031 .zip(holder_commitment_tx.counterparty_htlc_sigs.iter())
3032 {
3033 if htlc.offered {
3034 let source = sources_iter.next().expect("Non-dust HTLC sources didn't match commitment tx");
3035 #[cfg(debug_assertions)] {
3036 assert!(source.possibly_matches_output(htlc));
3037 }
3038 htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), Some(source)));
3039 } else {
3040 htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), None));
3041 }
3042 }
3043 debug_assert!(sources_iter.next().is_none());
3044 }
3045
3046 let trusted_tx = holder_commitment_tx.trust();
3047 let txid = trusted_tx.txid();
3048 let tx_keys = trusted_tx.keys();
3049 self.current_holder_commitment_number = trusted_tx.commitment_number();
3050 let mut new_holder_commitment_tx = HolderSignedTx {
3051 txid,
3052 revocation_key: tx_keys.revocation_key,
3053 a_htlc_key: tx_keys.broadcaster_htlc_key,
3054 b_htlc_key: tx_keys.countersignatory_htlc_key,
3055 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
3056 per_commitment_point: tx_keys.per_commitment_point,
3057 htlc_outputs,
3058 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
3059 feerate_per_kw: trusted_tx.feerate_per_kw(),
3060 };
3061 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
3062 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
3063 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
3064 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
3065 #[cfg(debug_assertions)] {
3066 let cur_counterparty_htlcs = self.counterparty_claimable_outpoints.get(
3067 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
3068 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
3069 if let Some(source) = source_opt {
3070 SentHTLCId::from_source(source) == *claimed_htlc_id
3071 } else { false }
3072 }));
3073 }
3074 self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
3075 }
3076 }
3077
3078 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
3083 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage,
3084 payment_info: &Option<PaymentClaimDetails>, broadcaster: &B,
3085 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
3086 where B::Target: BroadcasterInterface,
3087 F::Target: FeeEstimator,
3088 L::Target: Logger,
3089 {
3090 self.payment_preimages.entry(payment_hash.clone())
3091 .and_modify(|(_, payment_infos)| {
3092 if let Some(payment_info) = payment_info {
3093 if !payment_infos.contains(&payment_info) {
3094 payment_infos.push(payment_info.clone());
3095 }
3096 }
3097 })
3098 .or_insert_with(|| {
3099 (payment_preimage.clone(), payment_info.clone().into_iter().collect())
3100 });
3101
3102 let confirmed_spend_info = self.funding_spend_confirmed
3103 .map(|txid| (txid, None))
3104 .or_else(|| {
3105 self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3106 OnchainEvent::FundingSpendConfirmation { .. } => Some((event.txid, Some(event.height))),
3107 _ => None,
3108 })
3109 });
3110 let (confirmed_spend_txid, confirmed_spend_height) =
3111 if let Some((txid, height)) = confirmed_spend_info {
3112 (txid, height)
3113 } else {
3114 return;
3115 };
3116
3117 macro_rules! claim_htlcs {
3120 ($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3121 let htlc_claim_reqs = self.get_counterparty_output_claims_for_preimage(*payment_preimage, $commitment_number, $txid, $htlcs, confirmed_spend_height);
3122 let conf_target = self.closure_conf_target();
3123 self.onchain_tx_handler.update_claims_view_from_requests(htlc_claim_reqs, self.best_block.height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
3124 }
3125 }
3126 if let Some(txid) = self.current_counterparty_commitment_txid {
3127 if txid == confirmed_spend_txid {
3128 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3129 claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3130 } else {
3131 debug_assert!(false);
3132 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3133 }
3134 return;
3135 }
3136 }
3137 if let Some(txid) = self.prev_counterparty_commitment_txid {
3138 if txid == confirmed_spend_txid {
3139 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3140 claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3141 } else {
3142 debug_assert!(false);
3143 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3144 }
3145 return;
3146 }
3147 }
3148
3149 if self.broadcasted_holder_revokable_script.is_some() {
3155 let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
3156 Some(&self.current_holder_commitment_tx)
3157 } else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3158 if prev_holder_commitment_tx.txid == confirmed_spend_txid {
3159 Some(prev_holder_commitment_tx)
3160 } else {
3161 None
3162 }
3163 } else {
3164 None
3165 };
3166 if let Some(holder_commitment_tx) = holder_commitment_tx {
3167 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
3171 let conf_target = self.closure_conf_target();
3172 self.onchain_tx_handler.update_claims_view_from_requests(claim_reqs, self.best_block.height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
3173 }
3174 }
3175 }
3176
3177 fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3178 let funding_outp = HolderFundingOutput::build(
3179 self.funding_redeemscript.clone(),
3180 self.channel_value_satoshis,
3181 self.onchain_tx_handler.channel_type_features().clone()
3182 );
3183 let commitment_package = PackageTemplate::build_package(
3184 self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
3185 PackageSolvingData::HolderFundingOutput(funding_outp),
3186 self.best_block.height,
3187 );
3188 let mut claimable_outpoints = vec![commitment_package];
3189 let event = MonitorEvent::HolderForceClosedWithInfo {
3190 reason,
3191 outpoint: self.funding_info.0,
3192 channel_id: self.channel_id,
3193 };
3194 self.pending_monitor_events.push(event);
3195
3196 self.holder_tx_signed = true;
3200 let mut watch_outputs = Vec::new();
3201 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3205 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3209 &self.current_holder_commitment_tx, self.best_block.height,
3210 );
3211 let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
3212 let new_outputs = self.get_broadcasted_holder_watch_outputs(
3213 &self.current_holder_commitment_tx, &unsigned_commitment_tx
3214 );
3215 if !new_outputs.is_empty() {
3216 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
3217 }
3218 claimable_outpoints.append(&mut new_outpoints);
3219 }
3220 (claimable_outpoints, watch_outputs)
3221 }
3222
3223 pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
3224 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
3225 )
3226 where
3227 B::Target: BroadcasterInterface,
3228 F::Target: FeeEstimator,
3229 L::Target: Logger,
3230 {
3231 let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) });
3232 let conf_target = self.closure_conf_target();
3233 self.onchain_tx_handler.update_claims_view_from_requests(
3234 claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
3235 conf_target, fee_estimator, logger,
3236 );
3237 }
3238
3239 fn update_monitor<B: Deref, F: Deref, L: Deref>(
3240 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
3241 ) -> Result<(), ()>
3242 where B::Target: BroadcasterInterface,
3243 F::Target: FeeEstimator,
3244 L::Target: Logger,
3245 {
3246 if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3247 log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
3248 log_funding_info!(self), updates.updates.len());
3249 } else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3250 log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
3251 log_funding_info!(self), updates.updates.len());
3252 } else {
3253 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
3254 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
3255 }
3256
3257 if updates.counterparty_node_id.is_some() {
3258 if self.counterparty_node_id.is_none() {
3259 self.counterparty_node_id = updates.counterparty_node_id;
3260 } else {
3261 debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
3262 }
3263 }
3264
3265 if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
3274 assert_eq!(updates.updates.len(), 1);
3275 match updates.updates[0] {
3276 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
3277 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3278 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
3281 debug_assert!(self.lockdown_from_offchain),
3282 _ => {
3283 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
3284 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
3285 },
3286 }
3287 }
3288 if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3289 if self.latest_update_id + 1 != updates.update_id {
3290 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
3291 }
3292 }
3293 let mut ret = Ok(());
3294 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
3295 for update in updates.updates.iter() {
3296 match update {
3297 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
3298 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
3299 if self.lockdown_from_offchain { panic!(); }
3300 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone());
3301 }
3302 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
3303 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
3304 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
3305 },
3306 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
3307 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
3308 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
3309 },
3310 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
3311 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
3312 if let Err(e) = self.provide_secret(*idx, *secret) {
3313 debug_assert!(false, "Latest counterparty commitment secret was invalid");
3314 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
3315 log_error!(logger, " {}", e);
3316 ret = Err(());
3317 }
3318 },
3319 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
3320 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
3321 self.lockdown_from_offchain = true;
3322 if *should_broadcast {
3323 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
3327 self.onchain_events_awaiting_threshold_conf.iter().any(
3328 |event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
3329 if detected_funding_spend {
3330 log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
3331 continue;
3332 }
3333 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
3334 } else if !self.holder_tx_signed {
3335 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
3336 log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
3337 log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
3338 } else {
3339 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
3343 }
3344 },
3345 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
3346 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
3347 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
3348 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
3349 }
3350 },
3351 ChannelMonitorUpdateStep::ReleasePaymentComplete { htlc } => {
3352 log_trace!(logger, "HTLC {htlc:?} permanently and fully resolved");
3353 self.htlcs_resolved_to_user.insert(*htlc);
3354 },
3355 }
3356 }
3357
3358 #[cfg(debug_assertions)] {
3359 self.counterparty_commitment_txs_from_update(updates);
3360 }
3361
3362 self.latest_update_id = updates.update_id;
3363
3364 let mut is_pre_close_update = false;
3368 for update in updates.updates.iter() {
3369 match update {
3370 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
3371 |ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
3372 |ChannelMonitorUpdateStep::ShutdownScript { .. }
3373 |ChannelMonitorUpdateStep::CommitmentSecret { .. } =>
3374 is_pre_close_update = true,
3375 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
3381 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3382 ChannelMonitorUpdateStep::ReleasePaymentComplete { .. } => {},
3383 }
3384 }
3385
3386 if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
3387 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
3388 Err(())
3389 } else { ret }
3390 }
3391
3392 fn is_closed_without_updates(&self) -> bool {
3395 let mut commitment_not_advanced =
3396 self.current_counterparty_commitment_number == INITIAL_COMMITMENT_NUMBER;
3397 commitment_not_advanced &=
3398 self.current_holder_commitment_number == INITIAL_COMMITMENT_NUMBER;
3399 (self.holder_tx_signed || self.lockdown_from_offchain) && commitment_not_advanced
3400 }
3401
3402 fn no_further_updates_allowed(&self) -> bool {
3403 self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
3404 }
3405
3406 fn get_latest_update_id(&self) -> u64 {
3407 self.latest_update_id
3408 }
3409
3410 fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
3411 &self.funding_info
3412 }
3413
3414 pub fn channel_id(&self) -> ChannelId {
3415 self.channel_id
3416 }
3417
3418 fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
3419 for txid in self.counterparty_commitment_txn_on_chain.keys() {
3423 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
3424 }
3425 &self.outputs_to_watch
3426 }
3427
3428 fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
3429 let mut ret = Vec::new();
3430 mem::swap(&mut ret, &mut self.pending_monitor_events);
3431 ret
3432 }
3433
3434 pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
3438 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
3439 let mut ret = Vec::with_capacity(pending_claim_events.len());
3440 for (claim_id, claim_event) in pending_claim_events {
3441 match claim_event {
3442 ClaimEvent::BumpCommitment {
3443 package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
3444 } => {
3445 let channel_id = self.channel_id;
3446 let counterparty_node_id = self.counterparty_node_id.unwrap();
3450 let commitment_txid = commitment_tx.compute_txid();
3451 debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
3452 let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
3453 let commitment_tx_fee_satoshis = self.channel_value_satoshis -
3454 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value.to_sat());
3455 ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
3456 channel_id,
3457 counterparty_node_id,
3458 claim_id,
3459 package_target_feerate_sat_per_1000_weight,
3460 commitment_tx,
3461 commitment_tx_fee_satoshis,
3462 anchor_descriptor: AnchorDescriptor {
3463 channel_derivation_parameters: ChannelDerivationParameters {
3464 keys_id: self.channel_keys_id,
3465 value_satoshis: self.channel_value_satoshis,
3466 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3467 },
3468 outpoint: BitcoinOutPoint {
3469 txid: commitment_txid,
3470 vout: anchor_output_idx,
3471 },
3472 },
3473 pending_htlcs,
3474 }));
3475 },
3476 ClaimEvent::BumpHTLC {
3477 target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
3478 } => {
3479 let channel_id = self.channel_id;
3480 let counterparty_node_id = self.counterparty_node_id.unwrap();
3484 let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
3485 for htlc in htlcs {
3486 htlc_descriptors.push(HTLCDescriptor {
3487 channel_derivation_parameters: ChannelDerivationParameters {
3488 keys_id: self.channel_keys_id,
3489 value_satoshis: self.channel_value_satoshis,
3490 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3491 },
3492 commitment_txid: htlc.commitment_txid,
3493 per_commitment_number: htlc.per_commitment_number,
3494 per_commitment_point: htlc.per_commitment_point,
3495 feerate_per_kw: 0,
3496 htlc: htlc.htlc,
3497 preimage: htlc.preimage,
3498 counterparty_sig: htlc.counterparty_sig,
3499 });
3500 }
3501 ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
3502 channel_id,
3503 counterparty_node_id,
3504 claim_id,
3505 target_feerate_sat_per_1000_weight,
3506 htlc_descriptors,
3507 tx_lock_time,
3508 }));
3509 }
3510 }
3511 }
3512 ret
3513 }
3514
3515 fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
3516 let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value,
3517 to_countersignatory_value) = self.initial_counterparty_commitment_info?;
3518 let htlc_outputs = vec![];
3519
3520 let commitment_tx = self.build_counterparty_commitment_tx(INITIAL_COMMITMENT_NUMBER,
3521 &their_per_commitment_point, to_broadcaster_value, to_countersignatory_value,
3522 feerate_per_kw, htlc_outputs);
3523 Some(commitment_tx)
3524 }
3525
3526 fn build_counterparty_commitment_tx(
3527 &self, commitment_number: u64, their_per_commitment_point: &PublicKey,
3528 to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
3529 mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
3530 ) -> CommitmentTransaction {
3531 let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
3532 .counterparty_parameters.as_ref().unwrap().pubkeys;
3533 let countersignatory_keys =
3534 &self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
3535
3536 let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
3537 let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
3538 let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
3539 &broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
3540 let channel_parameters =
3541 &self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
3542
3543 CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
3544 to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
3545 countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
3546 channel_parameters)
3547 }
3548
3549 fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
3550 update.updates.iter().filter_map(|update| {
3551 match update {
3552 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
3553 ref htlc_outputs, commitment_number, their_per_commitment_point,
3554 feerate_per_kw: Some(feerate_per_kw),
3555 to_broadcaster_value_sat: Some(to_broadcaster_value),
3556 to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
3557
3558 let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
3559 htlc.transaction_output_index.map(|_| (htlc.clone(), None))
3560 }).collect::<Vec<_>>();
3561
3562 let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
3563 &their_per_commitment_point, to_broadcaster_value,
3564 to_countersignatory_value, feerate_per_kw, nondust_htlcs);
3565
3566 debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
3567
3568 Some(commitment_tx)
3569 },
3570 _ => None,
3571 }
3572 }).collect()
3573 }
3574
3575 fn sign_to_local_justice_tx(
3576 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
3577 ) -> Result<Transaction, ()> {
3578 let secret = self.get_secret(commitment_number).ok_or(())?;
3579 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
3580 let their_per_commitment_point = PublicKey::from_secret_key(
3581 &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3582
3583 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3584 &self.holder_revocation_basepoint, &their_per_commitment_point);
3585 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3586 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
3587 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3588 self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3589
3590 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
3591 &justice_tx, input_idx, value, &per_commitment_key, &self.onchain_tx_handler.secp_ctx)?;
3592 justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
3593 justice_tx.input[input_idx].witness.push(&[1u8]);
3594 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
3595 Ok(justice_tx)
3596 }
3597
3598 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
3600 self.commitment_secrets.get_secret(idx)
3601 }
3602
3603 fn get_min_seen_secret(&self) -> u64 {
3604 self.commitment_secrets.get_min_seen_secret()
3605 }
3606
3607 fn get_cur_counterparty_commitment_number(&self) -> u64 {
3608 self.current_counterparty_commitment_number
3609 }
3610
3611 fn get_cur_holder_commitment_number(&self) -> u64 {
3612 self.current_holder_commitment_number
3613 }
3614
3615 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
3623 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
3624 where L::Target: Logger {
3625 let mut claimable_outpoints = Vec::new();
3628 let mut to_counterparty_output_info = None;
3629
3630 let commitment_txid = tx.compute_txid(); let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
3632
3633 macro_rules! ignore_error {
3634 ( $thing : expr ) => {
3635 match $thing {
3636 Ok(a) => a,
3637 Err(_) => return (claimable_outpoints, to_counterparty_output_info)
3638 }
3639 };
3640 }
3641
3642 let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence.0 as u64 & 0xffffff) << 3*8) | (tx.lock_time.to_consensus_u32() as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
3643 if commitment_number >= self.get_min_seen_secret() {
3644 let secret = self.get_secret(commitment_number).unwrap();
3645 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
3646 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3647 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point,);
3648 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));
3649
3650 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3651 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
3652
3653 for (idx, outp) in tx.output.iter().enumerate() {
3655 if outp.script_pubkey == revokeable_p2wsh {
3656 let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, outp.value, self.counterparty_commitment_params.on_counterparty_tx_csv, self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx(), height);
3657 let justice_package = PackageTemplate::build_package(
3658 commitment_txid, idx as u32,
3659 PackageSolvingData::RevokedOutput(revk_outp),
3660 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3661 );
3662 claimable_outpoints.push(justice_package);
3663 to_counterparty_output_info =
3664 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
3665 }
3666 }
3667
3668 if let Some(per_commitment_claimable_data) = per_commitment_option {
3670 for (htlc, _) in per_commitment_claimable_data {
3671 if let Some(transaction_output_index) = htlc.transaction_output_index {
3672 if transaction_output_index as usize >= tx.output.len() ||
3673 tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3674 return (claimable_outpoints, to_counterparty_output_info);
3676 }
3677 let revk_htlc_outp = RevokedHTLCOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, htlc.amount_msat / 1000, htlc.clone(), &self.onchain_tx_handler.channel_transaction_parameters.channel_type_features, height);
3678 let counterparty_spendable_height = if htlc.offered {
3679 htlc.cltv_expiry
3680 } else {
3681 height
3682 };
3683 let justice_package = PackageTemplate::build_package(
3684 commitment_txid,
3685 transaction_output_index,
3686 PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
3687 counterparty_spendable_height,
3688 );
3689 claimable_outpoints.push(justice_package);
3690 }
3691 }
3692 }
3693
3694 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());
3698 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3699
3700 if let Some(per_commitment_claimable_data) = per_commitment_option {
3701 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
3702 block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3703 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3704 ), logger);
3705 } else {
3706 debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
3711 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
3712 block_hash, [].iter().map(|reference| *reference), logger);
3713 }
3714 }
3715 } else if let Some(per_commitment_claimable_data) = per_commitment_option {
3716 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3724
3725 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
3726 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
3727 per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3728 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3729 ), logger);
3730 let (htlc_claim_reqs, counterparty_output_info) =
3731 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, tx, per_commitment_claimable_data, Some(height));
3732 to_counterparty_output_info = counterparty_output_info;
3733 for req in htlc_claim_reqs {
3734 claimable_outpoints.push(req);
3735 }
3736
3737 }
3738 (claimable_outpoints, to_counterparty_output_info)
3739 }
3740
3741 fn get_point_for_commitment_number(&self, commitment_number: u64) -> Option<PublicKey> {
3742 let per_commitment_points = &self.their_cur_per_commitment_points?;
3743
3744 if per_commitment_points.0 == commitment_number {
3747 Some(per_commitment_points.1)
3748 } else if let Some(point) = per_commitment_points.2.as_ref() {
3749 if per_commitment_points.0 == commitment_number + 1 {
3753 Some(*point)
3754 } else {
3755 None
3756 }
3757 } else {
3758 None
3759 }
3760 }
3761
3762 fn get_counterparty_output_claims_for_preimage(
3763 &self, preimage: PaymentPreimage, commitment_number: u64,
3764 commitment_txid: Txid,
3765 per_commitment_option: Option<&Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
3766 confirmation_height: Option<u32>,
3767 ) -> Vec<PackageTemplate> {
3768 let per_commitment_claimable_data = match per_commitment_option {
3769 Some(outputs) => outputs,
3770 None => return Vec::new(),
3771 };
3772 let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
3773 Some(point) => point,
3774 None => return Vec::new(),
3775 };
3776
3777 let matching_payment_hash = PaymentHash::from(preimage);
3778 per_commitment_claimable_data
3779 .iter()
3780 .filter_map(|(htlc, _)| {
3781 if let Some(transaction_output_index) = htlc.transaction_output_index {
3782 if htlc.offered && htlc.payment_hash == matching_payment_hash {
3783 let htlc_data = PackageSolvingData::CounterpartyOfferedHTLCOutput(
3784 CounterpartyOfferedHTLCOutput::build(
3785 per_commitment_point,
3786 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3787 self.counterparty_commitment_params.counterparty_htlc_base_key,
3788 preimage,
3789 htlc.clone(),
3790 self.onchain_tx_handler.channel_type_features().clone(),
3791 confirmation_height,
3792 ),
3793 );
3794 Some(PackageTemplate::build_package(
3795 commitment_txid,
3796 transaction_output_index,
3797 htlc_data,
3798 htlc.cltv_expiry,
3799 ))
3800 } else {
3801 None
3802 }
3803 } else {
3804 None
3805 }
3806 })
3807 .collect()
3808 }
3809
3810 fn get_counterparty_output_claim_info(
3812 &self, commitment_number: u64, commitment_txid: Txid,
3813 tx: &Transaction,
3814 per_commitment_claimable_data: &[(HTLCOutputInCommitment, Option<Box<HTLCSource>>)],
3815 confirmation_height: Option<u32>,
3816 ) -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
3817 let mut claimable_outpoints = Vec::new();
3818 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
3819
3820 let per_commitment_point = match self.get_point_for_commitment_number(commitment_number) {
3821 Some(point) => point,
3822 None => return (claimable_outpoints, to_counterparty_output_info),
3823 };
3824
3825 let revocation_pubkey = RevocationKey::from_basepoint(
3826 &self.onchain_tx_handler.secp_ctx,
3827 &self.holder_revocation_basepoint,
3828 &per_commitment_point,
3829 );
3830 let delayed_key = DelayedPaymentKey::from_basepoint(
3831 &self.onchain_tx_handler.secp_ctx,
3832 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3833 &per_commitment_point,
3834 );
3835 let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(
3836 &revocation_pubkey,
3837 self.counterparty_commitment_params.on_counterparty_tx_csv,
3838 &delayed_key,
3839 )
3840 .to_p2wsh();
3841 for (idx, outp) in tx.output.iter().enumerate() {
3842 if outp.script_pubkey == revokeable_p2wsh {
3843 to_counterparty_output_info =
3844 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
3845 }
3846 }
3847
3848 for &(ref htlc, _) in per_commitment_claimable_data.iter() {
3849 if let Some(transaction_output_index) = htlc.transaction_output_index {
3850 if transaction_output_index as usize >= tx.output.len()
3851 || tx.output[transaction_output_index as usize].value
3852 != htlc.to_bitcoin_amount()
3853 {
3854 return (claimable_outpoints, to_counterparty_output_info);
3856 }
3857 let preimage = if htlc.offered {
3858 if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) {
3859 Some(*p)
3860 } else {
3861 None
3862 }
3863 } else {
3864 None
3865 };
3866 if preimage.is_some() || !htlc.offered {
3867 let counterparty_htlc_outp = if htlc.offered {
3868 PackageSolvingData::CounterpartyOfferedHTLCOutput(
3869 CounterpartyOfferedHTLCOutput::build(
3870 per_commitment_point,
3871 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3872 self.counterparty_commitment_params.counterparty_htlc_base_key,
3873 preimage.unwrap(),
3874 htlc.clone(),
3875 self.onchain_tx_handler.channel_type_features().clone(),
3876 confirmation_height,
3877 ),
3878 )
3879 } else {
3880 PackageSolvingData::CounterpartyReceivedHTLCOutput(
3881 CounterpartyReceivedHTLCOutput::build(
3882 per_commitment_point,
3883 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3884 self.counterparty_commitment_params.counterparty_htlc_base_key,
3885 htlc.clone(),
3886 self.onchain_tx_handler.channel_type_features().clone(),
3887 confirmation_height,
3888 ),
3889 )
3890 };
3891 let counterparty_package = PackageTemplate::build_package(
3892 commitment_txid,
3893 transaction_output_index,
3894 counterparty_htlc_outp,
3895 htlc.cltv_expiry,
3896 );
3897 claimable_outpoints.push(counterparty_package);
3898 }
3899 }
3900 }
3901
3902 (claimable_outpoints, to_counterparty_output_info)
3903 }
3904
3905 fn check_spend_counterparty_htlc<L: Deref>(
3907 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
3908 ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
3909 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
3910 let per_commitment_key = match SecretKey::from_slice(&secret) {
3911 Ok(key) => key,
3912 Err(_) => return (Vec::new(), None)
3913 };
3914 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3915
3916 let htlc_txid = tx.compute_txid();
3917 let mut claimable_outpoints = vec![];
3918 let mut outputs_to_watch = None;
3919 for (idx, input) in tx.input.iter().enumerate() {
3930 if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
3931 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
3932 let revk_outp = RevokedOutput::build(
3933 per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3934 self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
3935 tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
3936 false, height,
3937 );
3938 let justice_package = PackageTemplate::build_package(
3939 htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
3940 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3941 );
3942 claimable_outpoints.push(justice_package);
3943 if outputs_to_watch.is_none() {
3944 outputs_to_watch = Some((htlc_txid, vec![]));
3945 }
3946 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
3947 }
3948 }
3949 (claimable_outpoints, outputs_to_watch)
3950 }
3951
3952 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
3956 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3957
3958 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3959 let broadcasted_holder_revokable_script = Some((redeemscript.to_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3960
3961 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3962 if let Some(transaction_output_index) = htlc.transaction_output_index {
3963 let (htlc_output, counterparty_spendable_height) = if htlc.offered {
3964 let htlc_output = HolderHTLCOutput::build_offered(
3965 htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone(), conf_height
3966 );
3967 (htlc_output, conf_height)
3968 } else {
3969 let payment_preimage = if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
3970 preimage.clone()
3971 } else {
3972 continue;
3974 };
3975 let htlc_output = HolderHTLCOutput::build_accepted(
3976 payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone(), conf_height
3977 );
3978 (htlc_output, htlc.cltv_expiry)
3979 };
3980 let htlc_package = PackageTemplate::build_package(
3981 holder_tx.txid, transaction_output_index,
3982 PackageSolvingData::HolderHTLCOutput(htlc_output),
3983 counterparty_spendable_height,
3984 );
3985 claim_requests.push(htlc_package);
3986 }
3987 }
3988
3989 (claim_requests, broadcasted_holder_revokable_script)
3990 }
3991
3992 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3994 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3995 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3996 if let Some(transaction_output_index) = htlc.transaction_output_index {
3997 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3998 }
3999 }
4000 watch_outputs
4001 }
4002
4003 fn check_spend_holder_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L) -> Option<(Vec<PackageTemplate>, TransactionOutputs)> where L::Target: Logger {
4008 let commitment_txid = tx.compute_txid();
4009 let mut claim_requests = Vec::new();
4010 let mut watch_outputs = Vec::new();
4011
4012 macro_rules! append_onchain_update {
4013 ($updates: expr, $to_watch: expr) => {
4014 claim_requests = $updates.0;
4015 self.broadcasted_holder_revokable_script = $updates.1;
4016 watch_outputs.append(&mut $to_watch);
4017 }
4018 }
4019
4020 let mut is_holder_tx = false;
4022
4023 if self.current_holder_commitment_tx.txid == commitment_txid {
4024 is_holder_tx = true;
4025 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
4026 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
4027 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
4028 append_onchain_update!(res, to_watch);
4029 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
4030 block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
4031 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
4032 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
4033 if holder_tx.txid == commitment_txid {
4034 is_holder_tx = true;
4035 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
4036 let res = self.get_broadcasted_holder_claims(holder_tx, height);
4037 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
4038 append_onchain_update!(res, to_watch);
4039 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
4040 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
4041 logger);
4042 }
4043 }
4044
4045 if is_holder_tx {
4046 Some((claim_requests, (commitment_txid, watch_outputs)))
4047 } else {
4048 None
4049 }
4050 }
4051
4052 pub fn cancel_prev_commitment_claims<L: Deref>(
4055 &mut self, logger: &L, confirmed_commitment_txid: &Txid
4056 ) where L::Target: Logger {
4057 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
4058 if counterparty_commitment_txid == confirmed_commitment_txid {
4060 continue;
4061 }
4062 for (htlc, _) in self.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
4065 log_trace!(logger, "Canceling claims for previously confirmed counterparty commitment {}",
4066 counterparty_commitment_txid);
4067 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
4068 if let Some(vout) = htlc.transaction_output_index {
4069 outpoint.vout = vout;
4070 self.onchain_tx_handler.abandon_claim(&outpoint);
4071 }
4072 }
4073 }
4074 if self.current_holder_commitment_tx.txid != *confirmed_commitment_txid {
4078 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
4079 self.current_holder_commitment_tx.txid);
4080 let mut outpoint = BitcoinOutPoint { txid: self.current_holder_commitment_tx.txid, vout: 0 };
4081 for (htlc, _, _) in &self.current_holder_commitment_tx.htlc_outputs {
4082 if let Some(vout) = htlc.transaction_output_index {
4083 outpoint.vout = vout;
4084 self.onchain_tx_handler.abandon_claim(&outpoint);
4085 }
4086 }
4087 }
4088 if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
4089 if prev_holder_commitment_tx.txid != *confirmed_commitment_txid {
4090 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
4091 prev_holder_commitment_tx.txid);
4092 let mut outpoint = BitcoinOutPoint { txid: prev_holder_commitment_tx.txid, vout: 0 };
4093 for (htlc, _, _) in &prev_holder_commitment_tx.htlc_outputs {
4094 if let Some(vout) = htlc.transaction_output_index {
4095 outpoint.vout = vout;
4096 self.onchain_tx_handler.abandon_claim(&outpoint);
4097 }
4098 }
4099 }
4100 }
4101 }
4102
4103 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
4104 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
4106 &mut self, logger: &WithChannelMonitor<L>
4107 ) -> Vec<Transaction> where L::Target: Logger {
4108 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
4109 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
4110 let txid = commitment_tx.compute_txid();
4111 let mut holder_transactions = vec![commitment_tx];
4112 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
4115 return holder_transactions;
4116 }
4117 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
4118 if let Some(vout) = htlc.0.transaction_output_index {
4119 let preimage = if !htlc.0.offered {
4120 if let Some((preimage, _)) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
4121 continue;
4123 }
4124 } else { None };
4125 if let Some(htlc_tx) = self.onchain_tx_handler.get_maybe_signed_htlc_tx(
4126 &::bitcoin::OutPoint { txid, vout }, &preimage
4127 ) {
4128 if htlc_tx.is_fully_signed() {
4129 holder_transactions.push(htlc_tx.0);
4130 }
4131 }
4132 }
4133 }
4134 holder_transactions
4135 }
4136
4137 fn block_connected<B: Deref, F: Deref, L: Deref>(
4138 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
4139 fee_estimator: F, logger: &WithChannelMonitor<L>,
4140 ) -> Vec<TransactionOutputs>
4141 where B::Target: BroadcasterInterface,
4142 F::Target: FeeEstimator,
4143 L::Target: Logger,
4144 {
4145 let block_hash = header.block_hash();
4146 self.best_block = BestBlock::new(block_hash, height);
4147
4148 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4149 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
4150 }
4151
4152 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
4153 &mut self,
4154 header: &Header,
4155 height: u32,
4156 broadcaster: B,
4157 fee_estimator: &LowerBoundedFeeEstimator<F>,
4158 logger: &WithChannelMonitor<L>,
4159 ) -> Vec<TransactionOutputs>
4160 where
4161 B::Target: BroadcasterInterface,
4162 F::Target: FeeEstimator,
4163 L::Target: Logger,
4164 {
4165 let block_hash = header.block_hash();
4166
4167 if height > self.best_block.height {
4168 self.best_block = BestBlock::new(block_hash, height);
4169 log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
4170 self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
4171 } else if block_hash != self.best_block.block_hash {
4172 self.best_block = BestBlock::new(block_hash, height);
4173 log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
4174 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
4175 let conf_target = self.closure_conf_target();
4176 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, conf_target, fee_estimator, logger);
4177 Vec::new()
4178 } else { Vec::new() }
4179 }
4180
4181 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
4182 &mut self,
4183 header: &Header,
4184 txdata: &TransactionData,
4185 height: u32,
4186 broadcaster: B,
4187 fee_estimator: &LowerBoundedFeeEstimator<F>,
4188 logger: &WithChannelMonitor<L>,
4189 ) -> Vec<TransactionOutputs>
4190 where
4191 B::Target: BroadcasterInterface,
4192 F::Target: FeeEstimator,
4193 L::Target: Logger,
4194 {
4195 let txn_matched = self.filter_block(txdata);
4196 for tx in &txn_matched {
4197 let mut output_val = Amount::ZERO;
4198 for out in tx.output.iter() {
4199 if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4200 output_val += out.value;
4201 if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4202 }
4203 }
4204
4205 let block_hash = header.block_hash();
4206
4207 let mut watch_outputs = Vec::new();
4208 let mut claimable_outpoints = Vec::new();
4209 'tx_iter: for tx in &txn_matched {
4210 let txid = tx.compute_txid();
4211 log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
4212 if Some(txid) == self.funding_spend_confirmed {
4214 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
4215 continue 'tx_iter;
4216 }
4217 for ev in self.onchain_events_awaiting_threshold_conf.iter() {
4218 if ev.txid == txid {
4219 if let Some(conf_hash) = ev.block_hash {
4220 assert_eq!(header.block_hash(), conf_hash,
4221 "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
4222 This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
4223 }
4224 log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
4225 continue 'tx_iter;
4226 }
4227 }
4228 for htlc in self.htlcs_resolved_on_chain.iter() {
4229 if Some(txid) == htlc.resolving_txid {
4230 log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
4231 continue 'tx_iter;
4232 }
4233 }
4234 for spendable_txid in self.spendable_txids_confirmed.iter() {
4235 if txid == *spendable_txid {
4236 log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
4237 continue 'tx_iter;
4238 }
4239 }
4240
4241 if tx.input.len() == 1 {
4242 let prevout = &tx.input[0].previous_output;
4247 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
4248 let mut balance_spendable_csv = None;
4249 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
4250 &self.channel_id(), txid);
4251 self.funding_spend_seen = true;
4252 let mut commitment_tx_to_counterparty_output = None;
4253 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
4254 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
4255 if !new_outputs.1.is_empty() {
4256 watch_outputs.push(new_outputs);
4257 }
4258
4259 claimable_outpoints.append(&mut new_outpoints);
4260 balance_spendable_csv = Some(self.on_holder_tx_csv);
4261 } else {
4262 let mut new_watch_outputs = Vec::new();
4263 for (idx, outp) in tx.output.iter().enumerate() {
4264 new_watch_outputs.push((idx as u32, outp.clone()));
4265 }
4266 watch_outputs.push((txid, new_watch_outputs));
4267
4268 let (mut new_outpoints, counterparty_output_idx_sats) =
4269 self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
4270 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
4271
4272 claimable_outpoints.append(&mut new_outpoints);
4273 }
4274 }
4275 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4276 txid,
4277 transaction: Some((*tx).clone()),
4278 height,
4279 block_hash: Some(block_hash),
4280 event: OnchainEvent::FundingSpendConfirmation {
4281 on_local_output_csv: balance_spendable_csv,
4282 commitment_tx_to_counterparty_output,
4283 },
4284 });
4285 self.cancel_prev_commitment_claims(&logger, &txid);
4289 }
4290 }
4291 if tx.input.len() >= 1 {
4292 for tx_input in &tx.input {
4296 let commitment_txid = tx_input.previous_output.txid;
4297 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
4298 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
4299 &tx, commitment_number, &commitment_txid, height, &logger
4300 );
4301 claimable_outpoints.append(&mut new_outpoints);
4302 if let Some(new_outputs) = new_outputs_option {
4303 watch_outputs.push(new_outputs);
4304 }
4305 break;
4310 }
4311 }
4312 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
4313
4314 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
4315 }
4316 }
4317
4318 if height > self.best_block.height {
4319 self.best_block = BestBlock::new(block_hash, height);
4320 }
4321
4322 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
4323 }
4324
4325 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
4334 &mut self,
4335 conf_height: u32,
4336 conf_hash: BlockHash,
4337 txn_matched: Vec<&Transaction>,
4338 mut watch_outputs: Vec<TransactionOutputs>,
4339 mut claimable_outpoints: Vec<PackageTemplate>,
4340 broadcaster: &B,
4341 fee_estimator: &LowerBoundedFeeEstimator<F>,
4342 logger: &WithChannelMonitor<L>,
4343 ) -> Vec<TransactionOutputs>
4344 where
4345 B::Target: BroadcasterInterface,
4346 F::Target: FeeEstimator,
4347 L::Target: Logger,
4348 {
4349 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
4350 debug_assert!(self.best_block.height >= conf_height);
4351
4352 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
4353 if should_broadcast {
4354 let (mut new_outpoints, mut new_outputs) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HTLCsTimedOut);
4355 claimable_outpoints.append(&mut new_outpoints);
4356 watch_outputs.append(&mut new_outputs);
4357 }
4358
4359 let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
4361 self.onchain_events_awaiting_threshold_conf.drain(..).partition(
4362 |entry| entry.has_reached_confirmation_threshold(&self.best_block));
4363 self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
4364
4365 #[cfg(debug_assertions)]
4367 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
4368 .iter()
4369 .filter_map(|entry| match &entry.event {
4370 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
4371 _ => None,
4372 })
4373 .collect();
4374 #[cfg(debug_assertions)]
4375 let mut matured_htlcs = Vec::new();
4376
4377 for entry in onchain_events_reaching_threshold_conf {
4379 match entry.event {
4380 OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
4381 #[cfg(debug_assertions)]
4383 {
4384 debug_assert!(
4385 !unmatured_htlcs.contains(&&source),
4386 "An unmature HTLC transaction conflicts with a maturing one; failed to \
4387 call either transaction_unconfirmed for the conflicting transaction \
4388 or block_disconnected for a block containing it.");
4389 debug_assert!(
4390 !matured_htlcs.contains(&source),
4391 "A matured HTLC transaction conflicts with a maturing one; failed to \
4392 call either transaction_unconfirmed for the conflicting transaction \
4393 or block_disconnected for a block containing it.");
4394 matured_htlcs.push(source.clone());
4395 }
4396
4397 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
4398 &payment_hash, entry.txid);
4399 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4400 payment_hash,
4401 payment_preimage: None,
4402 source,
4403 htlc_value_satoshis,
4404 }));
4405 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4406 commitment_tx_output_idx,
4407 resolving_txid: Some(entry.txid),
4408 resolving_tx: entry.transaction,
4409 payment_preimage: None,
4410 });
4411 },
4412 OnchainEvent::MaturingOutput { descriptor } => {
4413 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
4414 self.pending_events.push(Event::SpendableOutputs {
4415 outputs: vec![descriptor],
4416 channel_id: Some(self.channel_id()),
4417 });
4418 self.spendable_txids_confirmed.push(entry.txid);
4419 },
4420 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
4421 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4422 commitment_tx_output_idx: Some(commitment_tx_output_idx),
4423 resolving_txid: Some(entry.txid),
4424 resolving_tx: entry.transaction,
4425 payment_preimage: preimage,
4426 });
4427 },
4428 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
4429 self.funding_spend_confirmed = Some(entry.txid);
4430 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
4431 },
4432 }
4433 }
4434
4435 if self.no_further_updates_allowed() {
4436 let current_holder_htlcs = self.current_holder_commitment_tx.htlc_outputs.iter()
4443 .map(|&(ref a, _, ref b)| (a, b.as_ref()));
4444
4445 let current_counterparty_htlcs = if let Some(txid) = self.current_counterparty_commitment_txid {
4446 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4447 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4448 } else { None }
4449 } else { None }.into_iter().flatten();
4450
4451 let prev_counterparty_htlcs = if let Some(txid) = self.prev_counterparty_commitment_txid {
4452 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4453 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4454 } else { None }
4455 } else { None }.into_iter().flatten();
4456
4457 let htlcs = current_holder_htlcs
4458 .chain(current_counterparty_htlcs)
4459 .chain(prev_counterparty_htlcs);
4460
4461 let height = self.best_block.height;
4462 for (htlc, source_opt) in htlcs {
4463 let source = match source_opt {
4465 Some(source) => source,
4466 None => continue,
4467 };
4468 let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
4469 Some(cltv_expiry) => cltv_expiry,
4470 None => continue,
4471 };
4472 let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
4473 if inbound_htlc_expiry > max_expiry_height {
4474 continue;
4475 }
4476 let duplicate_event = self.pending_monitor_events.iter().any(
4477 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4478 upd.source == *source
4479 } else { false });
4480 if duplicate_event {
4481 continue;
4482 }
4483 if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
4484 continue;
4485 }
4486 if !duplicate_event {
4487 log_error!(logger, "Failing back HTLC {} upstream to preserve the \
4488 channel as the forward HTLC hasn't resolved and our backward HTLC \
4489 expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
4490 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4491 source: source.clone(),
4492 payment_preimage: None,
4493 payment_hash: htlc.payment_hash,
4494 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
4495 }));
4496 }
4497 }
4498 }
4499
4500 let conf_target = self.closure_conf_target();
4501 self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
4502 self.onchain_tx_handler.update_claims_view_from_matched_txn(&txn_matched, conf_height, conf_hash, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
4503
4504 watch_outputs.retain(|&(ref txid, ref txouts)| {
4507 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
4508 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
4509 });
4510 #[cfg(test)]
4511 {
4512 for tx in &txn_matched {
4516 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
4517 for idx_and_script in outputs.iter() {
4518 assert!((idx_and_script.0 as usize) < tx.output.len());
4519 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
4520 }
4521 }
4522 }
4523 }
4524 watch_outputs
4525 }
4526
4527 fn block_disconnected<B: Deref, F: Deref, L: Deref>(
4528 &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
4529 ) where B::Target: BroadcasterInterface,
4530 F::Target: FeeEstimator,
4531 L::Target: Logger,
4532 {
4533 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
4534
4535 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
4539
4540 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4541 let conf_target = self.closure_conf_target();
4542 self.onchain_tx_handler.block_disconnected(height, broadcaster, conf_target, &bounded_fee_estimator, logger);
4543
4544 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
4545 }
4546
4547 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
4548 &mut self,
4549 txid: &Txid,
4550 broadcaster: B,
4551 fee_estimator: &LowerBoundedFeeEstimator<F>,
4552 logger: &WithChannelMonitor<L>,
4553 ) where
4554 B::Target: BroadcasterInterface,
4555 F::Target: FeeEstimator,
4556 L::Target: Logger,
4557 {
4558 let mut removed_height = None;
4559 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
4560 if entry.txid == *txid {
4561 removed_height = Some(entry.height);
4562 break;
4563 }
4564 }
4565
4566 if let Some(removed_height) = removed_height {
4567 log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
4568 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
4569 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
4570 false
4571 } else { true });
4572 }
4573
4574 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
4575
4576 let conf_target = self.closure_conf_target();
4577 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, conf_target, fee_estimator, logger);
4578 }
4579
4580 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
4583 let mut matched_txn = new_hash_set();
4584 txdata.iter().filter(|&&(_, tx)| {
4585 let mut matches = self.spends_watched_output(tx);
4586 for input in tx.input.iter() {
4587 if matches { break; }
4588 if matched_txn.contains(&input.previous_output.txid) {
4589 matches = true;
4590 }
4591 }
4592 if matches {
4593 matched_txn.insert(tx.compute_txid());
4594 }
4595 matches
4596 }).map(|(_, tx)| *tx).collect()
4597 }
4598
4599 fn spends_watched_output(&self, tx: &Transaction) -> bool {
4601 for input in tx.input.iter() {
4602 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
4603 for (idx, _script_pubkey) in outputs.iter() {
4604 if *idx == input.previous_output.vout {
4605 #[cfg(test)]
4606 {
4607 if _script_pubkey.is_p2wsh() {
4611 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
4612 return true;
4616 }
4617
4618 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4619 } else if _script_pubkey.is_p2wpkh() {
4620 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4621 } else { panic!(); }
4622 }
4623 return true;
4624 }
4625 }
4626 }
4627 }
4628
4629 false
4630 }
4631
4632 fn should_broadcast_holder_commitment_txn<L: Deref>(
4633 &self, logger: &WithChannelMonitor<L>
4634 ) -> bool where L::Target: Logger {
4635 if self.funding_spend_confirmed.is_some() ||
4638 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
4639 OnchainEvent::FundingSpendConfirmation { .. } => true,
4640 _ => false,
4641 }).is_some()
4642 {
4643 return false;
4644 }
4645 let height = self.best_block.height;
4656 macro_rules! scan_commitment {
4657 ($htlcs: expr, $holder_tx: expr) => {
4658 for ref htlc in $htlcs {
4659 let htlc_outbound = $holder_tx == htlc.offered;
4683 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
4684 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
4685 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
4686 return true;
4687 }
4688 }
4689 }
4690 }
4691
4692 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
4693
4694 if let Some(ref txid) = self.current_counterparty_commitment_txid {
4695 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4696 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4697 }
4698 }
4699 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
4700 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4701 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4702 }
4703 }
4704
4705 false
4706 }
4707
4708 fn is_resolving_htlc_output<L: Deref>(
4711 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4712 ) where L::Target: Logger {
4713 'outer_loop: for input in &tx.input {
4714 let mut payment_data = None;
4715 let htlc_claim = HTLCClaim::from_witness(&input.witness);
4716 let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
4717 let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
4718 #[cfg(not(fuzzing))]
4719 let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
4720 let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
4721 #[cfg(not(fuzzing))]
4722 let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
4723
4724 let mut payment_preimage = PaymentPreimage([0; 32]);
4725 if offered_preimage_claim || accepted_preimage_claim {
4726 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
4727 }
4728
4729 macro_rules! log_claim {
4730 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
4731 let outbound_htlc = $holder_tx == $htlc.offered;
4732 #[cfg(not(fuzzing))] debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
4736 #[cfg(not(fuzzing))] debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
4738 #[cfg(not(fuzzing))] debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
4742 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
4743 revocation_sig_claim as u8, 1);
4744 if ($holder_tx && revocation_sig_claim) ||
4745 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
4746 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
4747 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
4748 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4749 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" });
4750 } else {
4751 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
4752 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
4753 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4754 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
4755 }
4756 }
4757 }
4758
4759 macro_rules! check_htlc_valid_counterparty {
4760 ($htlc_output: expr, $per_commitment_data: expr) => {
4761 for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
4762 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
4763 if let &Some(ref source) = pending_source {
4764 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
4765 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
4766 break;
4767 }
4768 }
4769 }
4770 }
4771 }
4772
4773 macro_rules! scan_commitment {
4774 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
4775 for (ref htlc_output, source_option) in $htlcs {
4776 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
4777 if let Some(ref source) = source_option {
4778 log_claim!($tx_info, $holder_tx, htlc_output, true);
4779 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
4785 } else if !$holder_tx {
4786 if let Some(current_counterparty_commitment_txid) = &self.current_counterparty_commitment_txid {
4787 check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
4788 }
4789 if payment_data.is_none() {
4790 if let Some(prev_counterparty_commitment_txid) = &self.prev_counterparty_commitment_txid {
4791 check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
4792 }
4793 }
4794 }
4795 if payment_data.is_none() {
4796 log_claim!($tx_info, $holder_tx, htlc_output, false);
4797 let outbound_htlc = $holder_tx == htlc_output.offered;
4798 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4799 txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
4800 event: OnchainEvent::HTLCSpendConfirmation {
4801 commitment_tx_output_idx: input.previous_output.vout,
4802 preimage: if accepted_preimage_claim || offered_preimage_claim {
4803 Some(payment_preimage) } else { None },
4804 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
4809 Some(self.on_holder_tx_csv) } else { None },
4810 },
4811 });
4812 continue 'outer_loop;
4813 }
4814 }
4815 }
4816 }
4817 }
4818
4819 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
4820 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4821 "our latest holder commitment tx", true);
4822 }
4823 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
4824 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
4825 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4826 "our previous holder commitment tx", true);
4827 }
4828 }
4829 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
4830 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))),
4831 "counterparty commitment tx", false);
4832 }
4833
4834 if let Some((source, payment_hash, amount_msat)) = payment_data {
4837 if accepted_preimage_claim {
4838 if !self.pending_monitor_events.iter().any(
4839 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
4840 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4841 txid: tx.compute_txid(),
4842 height,
4843 block_hash: Some(*block_hash),
4844 transaction: Some(tx.clone()),
4845 event: OnchainEvent::HTLCSpendConfirmation {
4846 commitment_tx_output_idx: input.previous_output.vout,
4847 preimage: Some(payment_preimage),
4848 on_to_local_output_csv: None,
4849 },
4850 });
4851 self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
4852 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4853 source,
4854 payment_preimage: Some(payment_preimage),
4855 payment_hash,
4856 htlc_value_satoshis: Some(amount_msat / 1000),
4857 }));
4858 }
4859 } else if offered_preimage_claim {
4860 if !self.pending_monitor_events.iter().any(
4861 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4862 upd.source == source
4863 } else { false }) {
4864 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4865 txid: tx.compute_txid(),
4866 transaction: Some(tx.clone()),
4867 height,
4868 block_hash: Some(*block_hash),
4869 event: OnchainEvent::HTLCSpendConfirmation {
4870 commitment_tx_output_idx: input.previous_output.vout,
4871 preimage: Some(payment_preimage),
4872 on_to_local_output_csv: None,
4873 },
4874 });
4875 self.counterparty_fulfilled_htlcs.insert(SentHTLCId::from_source(&source), payment_preimage);
4876 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4877 source,
4878 payment_preimage: Some(payment_preimage),
4879 payment_hash,
4880 htlc_value_satoshis: Some(amount_msat / 1000),
4881 }));
4882 }
4883 } else {
4884 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
4885 if entry.height != height { return true; }
4886 match entry.event {
4887 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
4888 *htlc_source != source
4889 },
4890 _ => true,
4891 }
4892 });
4893 let entry = OnchainEventEntry {
4894 txid: tx.compute_txid(),
4895 transaction: Some(tx.clone()),
4896 height,
4897 block_hash: Some(*block_hash),
4898 event: OnchainEvent::HTLCUpdate {
4899 source,
4900 payment_hash,
4901 htlc_value_satoshis: Some(amount_msat / 1000),
4902 commitment_tx_output_idx: Some(input.previous_output.vout),
4903 },
4904 };
4905 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
4906 self.onchain_events_awaiting_threshold_conf.push(entry);
4907 }
4908 }
4909 }
4910 }
4911
4912 fn get_spendable_outputs(&self, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
4913 let mut spendable_outputs = Vec::new();
4914 for (i, outp) in tx.output.iter().enumerate() {
4915 if outp.script_pubkey == self.destination_script {
4916 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4917 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4918 output: outp.clone(),
4919 channel_keys_id: Some(self.channel_keys_id),
4920 });
4921 }
4922 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
4923 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
4924 spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
4925 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4926 per_commitment_point: broadcasted_holder_revokable_script.1,
4927 to_self_delay: self.on_holder_tx_csv,
4928 output: outp.clone(),
4929 revocation_pubkey: broadcasted_holder_revokable_script.2,
4930 channel_keys_id: self.channel_keys_id,
4931 channel_value_satoshis: self.channel_value_satoshis,
4932 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4933 }));
4934 }
4935 }
4936 if self.counterparty_payment_script == outp.script_pubkey {
4937 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4938 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4939 output: outp.clone(),
4940 channel_keys_id: self.channel_keys_id,
4941 channel_value_satoshis: self.channel_value_satoshis,
4942 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4943 }));
4944 }
4945 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4946 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4947 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4948 output: outp.clone(),
4949 channel_keys_id: Some(self.channel_keys_id),
4950 });
4951 }
4952 }
4953 spendable_outputs
4954 }
4955
4956 fn check_tx_and_push_spendable_outputs<L: Deref>(
4959 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4960 ) where L::Target: Logger {
4961 for spendable_output in self.get_spendable_outputs(tx) {
4962 let entry = OnchainEventEntry {
4963 txid: tx.compute_txid(),
4964 transaction: Some(tx.clone()),
4965 height,
4966 block_hash: Some(*block_hash),
4967 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4968 };
4969 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4970 self.onchain_events_awaiting_threshold_conf.push(entry);
4971 }
4972 }
4973}
4974
4975impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4976where
4977 T::Target: BroadcasterInterface,
4978 F::Target: FeeEstimator,
4979 L::Target: Logger,
4980{
4981 fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4982 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4983 }
4984
4985 fn block_disconnected(&self, header: &Header, height: u32) {
4986 self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4987 }
4988}
4989
4990impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4991where
4992 M: Deref<Target = ChannelMonitor<Signer>>,
4993 T::Target: BroadcasterInterface,
4994 F::Target: FeeEstimator,
4995 L::Target: Logger,
4996{
4997 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4998 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4999 }
5000
5001 fn transaction_unconfirmed(&self, txid: &Txid) {
5002 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
5003 }
5004
5005 fn best_block_updated(&self, header: &Header, height: u32) {
5006 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
5007 }
5008
5009 fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
5010 self.0.get_relevant_txids()
5011 }
5012}
5013
5014const MAX_ALLOC_SIZE: usize = 64*1024;
5015
5016impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
5017 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
5018 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
5019 macro_rules! unwrap_obj {
5020 ($key: expr) => {
5021 match $key {
5022 Ok(res) => res,
5023 Err(_) => return Err(DecodeError::InvalidValue),
5024 }
5025 }
5026 }
5027
5028 let (entropy_source, signer_provider) = args;
5029
5030 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
5031
5032 let latest_update_id: u64 = Readable::read(reader)?;
5033 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
5034
5035 let destination_script = Readable::read(reader)?;
5036 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
5037 0 => {
5038 let revokable_address = Readable::read(reader)?;
5039 let per_commitment_point = Readable::read(reader)?;
5040 let revokable_script = Readable::read(reader)?;
5041 Some((revokable_address, per_commitment_point, revokable_script))
5042 },
5043 1 => { None },
5044 _ => return Err(DecodeError::InvalidValue),
5045 };
5046 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
5047 let shutdown_script = {
5048 let script = <ScriptBuf as Readable>::read(reader)?;
5049 if script.is_empty() { None } else { Some(script) }
5050 };
5051
5052 let channel_keys_id = Readable::read(reader)?;
5053 let holder_revocation_basepoint = Readable::read(reader)?;
5054 let outpoint = OutPoint {
5057 txid: Readable::read(reader)?,
5058 index: Readable::read(reader)?,
5059 };
5060 let funding_info = (outpoint, Readable::read(reader)?);
5061 let current_counterparty_commitment_txid = Readable::read(reader)?;
5062 let prev_counterparty_commitment_txid = Readable::read(reader)?;
5063
5064 let counterparty_commitment_params = Readable::read(reader)?;
5065 let funding_redeemscript = Readable::read(reader)?;
5066 let channel_value_satoshis = Readable::read(reader)?;
5067
5068 let their_cur_per_commitment_points = {
5069 let first_idx = <U48 as Readable>::read(reader)?.0;
5070 if first_idx == 0 {
5071 None
5072 } else {
5073 let first_point = Readable::read(reader)?;
5074 let second_point_slice: [u8; 33] = Readable::read(reader)?;
5075 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
5076 Some((first_idx, first_point, None))
5077 } else {
5078 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
5079 }
5080 }
5081 };
5082
5083 let on_holder_tx_csv: u16 = Readable::read(reader)?;
5084
5085 let commitment_secrets = Readable::read(reader)?;
5086
5087 macro_rules! read_htlc_in_commitment {
5088 () => {
5089 {
5090 let offered: bool = Readable::read(reader)?;
5091 let amount_msat: u64 = Readable::read(reader)?;
5092 let cltv_expiry: u32 = Readable::read(reader)?;
5093 let payment_hash: PaymentHash = Readable::read(reader)?;
5094 let transaction_output_index: Option<u32> = Readable::read(reader)?;
5095
5096 HTLCOutputInCommitment {
5097 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
5098 }
5099 }
5100 }
5101 }
5102
5103 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
5104 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
5105 for _ in 0..counterparty_claimable_outpoints_len {
5106 let txid: Txid = Readable::read(reader)?;
5107 let htlcs_count: u64 = Readable::read(reader)?;
5108 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
5109 for _ in 0..htlcs_count {
5110 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
5111 }
5112 if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
5113 return Err(DecodeError::InvalidValue);
5114 }
5115 }
5116
5117 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
5118 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));
5119 for _ in 0..counterparty_commitment_txn_on_chain_len {
5120 let txid: Txid = Readable::read(reader)?;
5121 let commitment_number = <U48 as Readable>::read(reader)?.0;
5122 if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
5123 return Err(DecodeError::InvalidValue);
5124 }
5125 }
5126
5127 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
5128 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
5129 for _ in 0..counterparty_hash_commitment_number_len {
5130 let payment_hash: PaymentHash = Readable::read(reader)?;
5131 let commitment_number = <U48 as Readable>::read(reader)?.0;
5132 if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
5133 return Err(DecodeError::InvalidValue);
5134 }
5135 }
5136
5137 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
5138 match <u8 as Readable>::read(reader)? {
5139 0 => None,
5140 1 => Some(Readable::read(reader)?),
5141 _ => return Err(DecodeError::InvalidValue),
5142 };
5143 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
5144
5145 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
5146 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
5147
5148 let payment_preimages_len: u64 = Readable::read(reader)?;
5149 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
5150 for _ in 0..payment_preimages_len {
5151 let preimage: PaymentPreimage = Readable::read(reader)?;
5152 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
5153 if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
5154 return Err(DecodeError::InvalidValue);
5155 }
5156 }
5157
5158 let pending_monitor_events_len: u64 = Readable::read(reader)?;
5159 let mut pending_monitor_events = Some(
5160 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
5161 for _ in 0..pending_monitor_events_len {
5162 let ev = match <u8 as Readable>::read(reader)? {
5163 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
5164 1 => MonitorEvent::HolderForceClosed(funding_info.0),
5165 _ => return Err(DecodeError::InvalidValue)
5166 };
5167 pending_monitor_events.as_mut().unwrap().push(ev);
5168 }
5169
5170 let pending_events_len: u64 = Readable::read(reader)?;
5171 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
5172 for _ in 0..pending_events_len {
5173 if let Some(event) = MaybeReadable::read(reader)? {
5174 pending_events.push(event);
5175 }
5176 }
5177
5178 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
5179
5180 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
5181 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
5182 for _ in 0..waiting_threshold_conf_len {
5183 if let Some(val) = MaybeReadable::read(reader)? {
5184 onchain_events_awaiting_threshold_conf.push(val);
5185 }
5186 }
5187
5188 let outputs_to_watch_len: u64 = Readable::read(reader)?;
5189 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>>())));
5190 for _ in 0..outputs_to_watch_len {
5191 let txid = Readable::read(reader)?;
5192 let outputs_len: u64 = Readable::read(reader)?;
5193 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
5194 for _ in 0..outputs_len {
5195 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
5196 }
5197 if outputs_to_watch.insert(txid, outputs).is_some() {
5198 return Err(DecodeError::InvalidValue);
5199 }
5200 }
5201 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
5202 reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
5203 )?;
5204
5205 let lockdown_from_offchain = Readable::read(reader)?;
5206 let holder_tx_signed = Readable::read(reader)?;
5207
5208 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
5209 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
5210 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
5211 if prev_commitment_tx.to_self_value_sat == u64::MAX {
5212 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
5213 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
5214 return Err(DecodeError::InvalidValue);
5215 }
5216 }
5217
5218 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
5219 if current_holder_commitment_tx.to_self_value_sat == u64::MAX {
5220 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
5221 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
5222 return Err(DecodeError::InvalidValue);
5223 }
5224
5225 let mut funding_spend_confirmed = None;
5226 let mut htlcs_resolved_on_chain = Some(Vec::new());
5227 let mut htlcs_resolved_to_user = Some(new_hash_set());
5228 let mut funding_spend_seen = Some(false);
5229 let mut counterparty_node_id = None;
5230 let mut confirmed_commitment_tx_counterparty_output = None;
5231 let mut spendable_txids_confirmed = Some(Vec::new());
5232 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
5233 let mut initial_counterparty_commitment_info = None;
5234 let mut balances_empty_height = None;
5235 let mut channel_id = None;
5236 let mut holder_pays_commitment_tx_fee = None;
5237 let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
5238 read_tlv_fields!(reader, {
5239 (1, funding_spend_confirmed, option),
5240 (3, htlcs_resolved_on_chain, optional_vec),
5241 (5, pending_monitor_events, optional_vec),
5242 (7, funding_spend_seen, option),
5243 (9, counterparty_node_id, option),
5244 (11, confirmed_commitment_tx_counterparty_output, option),
5245 (13, spendable_txids_confirmed, optional_vec),
5246 (15, counterparty_fulfilled_htlcs, option),
5247 (17, initial_counterparty_commitment_info, option),
5248 (19, channel_id, option),
5249 (21, balances_empty_height, option),
5250 (23, holder_pays_commitment_tx_fee, option),
5251 (25, payment_preimages_with_info, option),
5252 (33, htlcs_resolved_to_user, option),
5253 });
5254 if let Some(payment_preimages_with_info) = payment_preimages_with_info {
5255 if payment_preimages_with_info.len() != payment_preimages.len() {
5256 return Err(DecodeError::InvalidValue);
5257 }
5258 for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
5259 let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
5264 if new_preimage != Some(payment_preimage) {
5265 return Err(DecodeError::InvalidValue);
5266 }
5267 }
5268 payment_preimages = payment_preimages_with_info;
5269 }
5270
5271 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
5274 if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
5275 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
5276 {
5277 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
5278 }
5279 }
5280
5281 if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
5285 counterparty_payment_script.is_p2wpkh()
5286 {
5287 let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
5288 counterparty_payment_script =
5289 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_p2wsh();
5290 }
5291
5292 Ok((best_block.block_hash, ChannelMonitor::from_impl(ChannelMonitorImpl {
5293 latest_update_id,
5294 commitment_transaction_number_obscure_factor,
5295
5296 destination_script,
5297 broadcasted_holder_revokable_script,
5298 counterparty_payment_script,
5299 shutdown_script,
5300
5301 channel_keys_id,
5302 holder_revocation_basepoint,
5303 channel_id: channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint)),
5304 funding_info,
5305 current_counterparty_commitment_txid,
5306 prev_counterparty_commitment_txid,
5307
5308 counterparty_commitment_params,
5309 funding_redeemscript,
5310 channel_value_satoshis,
5311 their_cur_per_commitment_points,
5312
5313 on_holder_tx_csv,
5314
5315 commitment_secrets,
5316 counterparty_claimable_outpoints,
5317 counterparty_commitment_txn_on_chain,
5318 counterparty_hash_commitment_number,
5319 counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
5320
5321 prev_holder_signed_commitment_tx,
5322 current_holder_commitment_tx,
5323 current_counterparty_commitment_number,
5324 current_holder_commitment_number,
5325
5326 payment_preimages,
5327 pending_monitor_events: pending_monitor_events.unwrap(),
5328 pending_events,
5329 is_processing_pending_events: false,
5330
5331 onchain_events_awaiting_threshold_conf,
5332 outputs_to_watch,
5333
5334 onchain_tx_handler,
5335
5336 lockdown_from_offchain,
5337 holder_tx_signed,
5338 holder_pays_commitment_tx_fee,
5339 funding_spend_seen: funding_spend_seen.unwrap(),
5340 funding_spend_confirmed,
5341 confirmed_commitment_tx_counterparty_output,
5342 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
5343 htlcs_resolved_to_user: htlcs_resolved_to_user.unwrap(),
5344 spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
5345
5346 best_block,
5347 counterparty_node_id,
5348 initial_counterparty_commitment_info,
5349 balances_empty_height,
5350 failed_back_htlc_ids: new_hash_set(),
5351 })))
5352 }
5353}
5354
5355#[cfg(test)]
5356mod tests {
5357 use bitcoin::amount::Amount;
5358 use bitcoin::locktime::absolute::LockTime;
5359 use bitcoin::script::{ScriptBuf, Builder};
5360 use bitcoin::opcodes;
5361 use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
5362 use bitcoin::transaction::OutPoint as BitcoinOutPoint;
5363 use bitcoin::sighash;
5364 use bitcoin::sighash::EcdsaSighashType;
5365 use bitcoin::hashes::Hash;
5366 use bitcoin::hashes::sha256::Hash as Sha256;
5367 use bitcoin::hex::FromHex;
5368 use bitcoin::hash_types::{BlockHash, Txid};
5369 use bitcoin::network::Network;
5370 use bitcoin::secp256k1::{SecretKey,PublicKey};
5371 use bitcoin::secp256k1::Secp256k1;
5372 use bitcoin::{Sequence, Witness};
5373
5374 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
5375
5376 use super::ChannelMonitorUpdateStep;
5377 use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash};
5378 use crate::chain::{BestBlock, Confirm};
5379 use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
5380 use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
5381 use crate::chain::transaction::OutPoint;
5382 use crate::sign::InMemorySigner;
5383 use crate::ln::types::ChannelId;
5384 use crate::types::payment::{PaymentPreimage, PaymentHash};
5385 use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
5386 use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
5387 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
5388 use crate::ln::functional_test_utils::*;
5389 use crate::ln::script::ShutdownScript;
5390 use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
5391 use crate::util::ser::{ReadableArgs, Writeable};
5392 use crate::util::logger::Logger;
5393 use crate::sync::Arc;
5394 use crate::io;
5395 use crate::types::features::ChannelTypeFeatures;
5396
5397 #[allow(unused_imports)]
5398 use crate::prelude::*;
5399
5400 use std::str::FromStr;
5401
5402 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
5403 let chanmon_cfgs = create_chanmon_cfgs(3);
5415 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5416 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5417 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5418 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
5419 create_announced_chan_between_nodes(&nodes, 1, 2);
5420
5421 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
5423
5424 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5426 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5427
5428 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
5429 assert_eq!(local_txn.len(), 1);
5430 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
5431 assert_eq!(remote_txn.len(), 3); check_spends!(remote_txn[1], remote_txn[0]);
5433 check_spends!(remote_txn[2], remote_txn[0]);
5434 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
5435
5436 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
5439 let conf_height = nodes[0].best_block_info().1 + 1;
5440 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
5441 &[(0, broadcast_tx)], conf_height);
5442
5443 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
5444 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
5445 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
5446
5447 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
5450 nodes[1].node.send_payment_with_route(route, payment_hash,
5451 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
5452 ).unwrap();
5453 check_added_monitors!(nodes[1], 1);
5454
5455 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
5459 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
5460 assert_eq!(replay_update.updates.len(), 1);
5461 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
5462 } else { panic!(); }
5463 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5464 payment_preimage: payment_preimage_1, payment_info: None,
5465 });
5466 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5467 payment_preimage: payment_preimage_2, payment_info: None,
5468 });
5469
5470 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
5471 assert!(
5472 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
5473 .is_err());
5474 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5477 assert!(txn_broadcasted.len() >= 2);
5478 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
5479 assert_eq!(tx.input.len(), 1);
5480 tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
5481 }).collect::<Vec<_>>();
5482 assert_eq!(htlc_txn.len(), 2);
5483 check_spends!(htlc_txn[0], broadcast_tx);
5484 check_spends!(htlc_txn[1], broadcast_tx);
5485 }
5486 #[test]
5487 fn test_funding_spend_refuses_updates() {
5488 do_test_funding_spend_refuses_updates(true);
5489 do_test_funding_spend_refuses_updates(false);
5490 }
5491
5492 #[test]
5493 fn test_prune_preimages() {
5494 let secp_ctx = Secp256k1::new();
5495 let logger = Arc::new(TestLogger::new());
5496 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
5497 let fee_estimator = TestFeeEstimator::new(253);
5498
5499 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5500
5501 let mut preimages = Vec::new();
5502 {
5503 for i in 0..20 {
5504 let preimage = PaymentPreimage([i; 32]);
5505 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
5506 preimages.push((preimage, hash));
5507 }
5508 }
5509
5510 macro_rules! preimages_slice_to_htlcs {
5511 ($preimages_slice: expr) => {
5512 {
5513 let mut res = Vec::new();
5514 for (idx, preimage) in $preimages_slice.iter().enumerate() {
5515 res.push((HTLCOutputInCommitment {
5516 offered: true,
5517 amount_msat: 0,
5518 cltv_expiry: 0,
5519 payment_hash: preimage.1.clone(),
5520 transaction_output_index: Some(idx as u32),
5521 }, ()));
5522 }
5523 res
5524 }
5525 }
5526 }
5527 macro_rules! preimages_slice_to_htlc_outputs {
5528 ($preimages_slice: expr) => {
5529 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
5530 }
5531 }
5532 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
5533 &bitcoin::secp256k1::Message::from_digest([42; 32]),
5534 &SecretKey::from_slice(&[42; 32]).unwrap());
5535
5536 macro_rules! test_preimages_exist {
5537 ($preimages_slice: expr, $monitor: expr) => {
5538 for preimage in $preimages_slice {
5539 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
5540 }
5541 }
5542 }
5543
5544 let keys = InMemorySigner::new(
5545 &secp_ctx,
5546 SecretKey::from_slice(&[41; 32]).unwrap(),
5547 SecretKey::from_slice(&[41; 32]).unwrap(),
5548 SecretKey::from_slice(&[41; 32]).unwrap(),
5549 SecretKey::from_slice(&[41; 32]).unwrap(),
5550 SecretKey::from_slice(&[41; 32]).unwrap(),
5551 [41; 32],
5552 0,
5553 [0; 32],
5554 [0; 32],
5555 );
5556
5557 let counterparty_pubkeys = ChannelPublicKeys {
5558 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5559 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5560 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5561 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5562 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
5563 };
5564 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5565 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5566 let channel_parameters = ChannelTransactionParameters {
5567 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5568 holder_selected_contest_delay: 66,
5569 is_outbound_from_holder: true,
5570 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5571 pubkeys: counterparty_pubkeys,
5572 selected_contest_delay: 67,
5573 }),
5574 funding_outpoint: Some(funding_outpoint),
5575 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5576 };
5577 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5580 let best_block = BestBlock::from_network(Network::Testnet);
5581 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5582 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5583 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5584 &channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5585 best_block, dummy_key, channel_id);
5586
5587 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
5588 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5589
5590 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5591 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5592 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
5593 preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
5594 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
5595 preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
5596 for &(ref preimage, ref hash) in preimages.iter() {
5597 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
5598 monitor.provide_payment_preimage_unsafe_legacy(
5599 hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
5600 );
5601 }
5602
5603 let mut secret = [0; 32];
5605 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
5606 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
5607 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
5608 test_preimages_exist!(&preimages[0..10], monitor);
5609 test_preimages_exist!(&preimages[15..20], monitor);
5610
5611 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
5612 preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
5613
5614 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
5616 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
5617 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
5618 test_preimages_exist!(&preimages[0..10], monitor);
5619 test_preimages_exist!(&preimages[17..20], monitor);
5620
5621 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
5622 preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
5623
5624 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
5627 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5628 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5629 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5630 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
5631 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
5632 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
5633 test_preimages_exist!(&preimages[0..10], monitor);
5634 test_preimages_exist!(&preimages[18..20], monitor);
5635
5636 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
5638 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5639 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
5640 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5641 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
5642 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
5643 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
5644 test_preimages_exist!(&preimages[0..5], monitor);
5645 }
5646
5647 #[test]
5648 fn test_claim_txn_weight_computation() {
5649 let secp_ctx = Secp256k1::new();
5653 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5654 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
5655
5656 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
5657 macro_rules! sign_input {
5658 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
5659 let htlc = HTLCOutputInCommitment {
5660 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
5661 amount_msat: 0,
5662 cltv_expiry: 2 << 16,
5663 payment_hash: PaymentHash([1; 32]),
5664 transaction_output_index: Some($idx as u32),
5665 };
5666 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)) };
5667 let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
5668 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
5669 let mut ser_sig = sig.serialize_der().to_vec();
5670 ser_sig.push(EcdsaSighashType::All as u8);
5671 $sum_actual_sigs += ser_sig.len() as u64;
5672 let witness = $sighash_parts.witness_mut($idx).unwrap();
5673 witness.push(ser_sig);
5674 if *$weight == WEIGHT_REVOKED_OUTPUT {
5675 witness.push(vec!(1));
5676 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
5677 witness.push(pubkey.clone().serialize().to_vec());
5678 } else if *$weight == weight_received_htlc($opt_anchors) {
5679 witness.push(vec![0]);
5680 } else {
5681 witness.push(PaymentPreimage([1; 32]).0.to_vec());
5682 }
5683 witness.push(redeem_script.into_bytes());
5684 let witness = witness.to_vec();
5685 println!("witness[0] {}", witness[0].len());
5686 println!("witness[1] {}", witness[1].len());
5687 println!("witness[2] {}", witness[2].len());
5688 }
5689 }
5690
5691 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
5692 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
5693
5694 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5696 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5697 let mut sum_actual_sigs = 0;
5698 for i in 0..4 {
5699 claim_tx.input.push(TxIn {
5700 previous_output: BitcoinOutPoint {
5701 txid,
5702 vout: i,
5703 },
5704 script_sig: ScriptBuf::new(),
5705 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5706 witness: Witness::new(),
5707 });
5708 }
5709 claim_tx.output.push(TxOut {
5710 script_pubkey: script_pubkey.clone(),
5711 value: Amount::ZERO,
5712 });
5713 let base_weight = claim_tx.weight().to_wu();
5714 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT, weight_revoked_offered_htlc(channel_type_features), weight_revoked_offered_htlc(channel_type_features), weight_revoked_received_htlc(channel_type_features)];
5715 let mut inputs_total_weight = 2; {
5717 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5718 for (idx, inp) in inputs_weight.iter().enumerate() {
5719 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5720 inputs_total_weight += inp;
5721 }
5722 }
5723 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5724 }
5725
5726 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5728 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5729 let mut sum_actual_sigs = 0;
5730 for i in 0..4 {
5731 claim_tx.input.push(TxIn {
5732 previous_output: BitcoinOutPoint {
5733 txid,
5734 vout: i,
5735 },
5736 script_sig: ScriptBuf::new(),
5737 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5738 witness: Witness::new(),
5739 });
5740 }
5741 claim_tx.output.push(TxOut {
5742 script_pubkey: script_pubkey.clone(),
5743 value: Amount::ZERO,
5744 });
5745 let base_weight = claim_tx.weight().to_wu();
5746 let inputs_weight = vec![weight_offered_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features), weight_received_htlc(channel_type_features)];
5747 let mut inputs_total_weight = 2; {
5749 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5750 for (idx, inp) in inputs_weight.iter().enumerate() {
5751 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5752 inputs_total_weight += inp;
5753 }
5754 }
5755 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5756 }
5757
5758 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5760 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5761 let mut sum_actual_sigs = 0;
5762 claim_tx.input.push(TxIn {
5763 previous_output: BitcoinOutPoint {
5764 txid,
5765 vout: 0,
5766 },
5767 script_sig: ScriptBuf::new(),
5768 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5769 witness: Witness::new(),
5770 });
5771 claim_tx.output.push(TxOut {
5772 script_pubkey: script_pubkey.clone(),
5773 value: Amount::ZERO,
5774 });
5775 let base_weight = claim_tx.weight().to_wu();
5776 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5777 let mut inputs_total_weight = 2; {
5779 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5780 for (idx, inp) in inputs_weight.iter().enumerate() {
5781 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5782 inputs_total_weight += inp;
5783 }
5784 }
5785 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5786 }
5787 }
5788
5789 #[test]
5790 fn test_with_channel_monitor_impl_logger() {
5791 let secp_ctx = Secp256k1::new();
5792 let logger = Arc::new(TestLogger::new());
5793
5794 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5795
5796 let keys = InMemorySigner::new(
5797 &secp_ctx,
5798 SecretKey::from_slice(&[41; 32]).unwrap(),
5799 SecretKey::from_slice(&[41; 32]).unwrap(),
5800 SecretKey::from_slice(&[41; 32]).unwrap(),
5801 SecretKey::from_slice(&[41; 32]).unwrap(),
5802 SecretKey::from_slice(&[41; 32]).unwrap(),
5803 [41; 32],
5804 0,
5805 [0; 32],
5806 [0; 32],
5807 );
5808
5809 let counterparty_pubkeys = ChannelPublicKeys {
5810 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5811 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5812 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5813 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5814 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5815 };
5816 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5817 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5818 let channel_parameters = ChannelTransactionParameters {
5819 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5820 holder_selected_contest_delay: 66,
5821 is_outbound_from_holder: true,
5822 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5823 pubkeys: counterparty_pubkeys,
5824 selected_contest_delay: 67,
5825 }),
5826 funding_outpoint: Some(funding_outpoint),
5827 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5828 };
5829 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5830 let best_block = BestBlock::from_network(Network::Testnet);
5831 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5832 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5833 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5834 &channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5835 best_block, dummy_key, channel_id);
5836
5837 let chan_id = monitor.inner.lock().unwrap().channel_id();
5838 let payment_hash = PaymentHash([1; 32]);
5839 let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
5840 log_error!(context_logger, "This is an error");
5841 log_warn!(context_logger, "This is an error");
5842 log_debug!(context_logger, "This is an error");
5843 log_trace!(context_logger, "This is an error");
5844 log_gossip!(context_logger, "This is an error");
5845 log_info!(context_logger, "This is an error");
5846 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5847 }
5848 }