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, LockTestExt};
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}
571
572impl ChannelMonitorUpdateStep {
573 fn variant_name(&self) -> &'static str {
574 match self {
575 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. } => "LatestHolderCommitmentTXInfo",
576 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } => "LatestCounterpartyCommitmentTXInfo",
577 ChannelMonitorUpdateStep::PaymentPreimage { .. } => "PaymentPreimage",
578 ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
579 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
580 ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
581 }
582 }
583}
584
585impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
586 (0, LatestHolderCommitmentTXInfo) => {
587 (0, commitment_tx, required),
588 (1, claimed_htlcs, optional_vec),
589 (2, htlc_outputs, required_vec),
590 (4, nondust_htlc_sources, optional_vec),
591 },
592 (1, LatestCounterpartyCommitmentTXInfo) => {
593 (0, commitment_txid, required),
594 (1, feerate_per_kw, option),
595 (2, commitment_number, required),
596 (3, to_broadcaster_value_sat, option),
597 (4, their_per_commitment_point, required),
598 (5, to_countersignatory_value_sat, option),
599 (6, htlc_outputs, required_vec),
600 },
601 (2, PaymentPreimage) => {
602 (0, payment_preimage, required),
603 (1, payment_info, option),
604 },
605 (3, CommitmentSecret) => {
606 (0, idx, required),
607 (2, secret, required),
608 },
609 (4, ChannelForceClosed) => {
610 (0, should_broadcast, required),
611 },
612 (5, ShutdownScript) => {
613 (0, scriptpubkey, required),
614 },
615);
616
617#[derive(Clone, Debug, PartialEq, Eq)]
620#[cfg_attr(test, derive(PartialOrd, Ord))]
621pub enum BalanceSource {
622 HolderForceClosed,
624 CounterpartyForceClosed,
626 CoopClose,
628 Htlc,
630}
631
632#[derive(Clone, Debug, PartialEq, Eq)]
637#[cfg_attr(test, derive(PartialOrd, Ord))]
638pub enum Balance {
639 ClaimableOnChannelClose {
643 amount_satoshis: u64,
646 transaction_fee_satoshis: u64,
653 outbound_payment_htlc_rounded_msat: u64,
662 outbound_forwarded_htlc_rounded_msat: u64,
670 inbound_claiming_htlc_rounded_msat: u64,
680 inbound_htlc_rounded_msat: u64,
689 },
690 ClaimableAwaitingConfirmations {
693 amount_satoshis: u64,
696 confirmation_height: u32,
699 source: BalanceSource,
701 },
702 ContentiousClaimable {
710 amount_satoshis: u64,
713 timeout_height: u32,
716 payment_hash: PaymentHash,
718 payment_preimage: PaymentPreimage,
720 },
721 MaybeTimeoutClaimableHTLC {
725 amount_satoshis: u64,
728 claimable_height: u32,
731 payment_hash: PaymentHash,
733 outbound_payment: bool,
737 },
738 MaybePreimageClaimableHTLC {
742 amount_satoshis: u64,
745 expiry_height: u32,
748 payment_hash: PaymentHash,
750 },
751 CounterpartyRevokedOutputClaimable {
757 amount_satoshis: u64,
762 },
763}
764
765impl Balance {
766 pub fn claimable_amount_satoshis(&self) -> u64 {
779 match self {
780 Balance::ClaimableOnChannelClose { amount_satoshis, .. }|
781 Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. }|
782 Balance::ContentiousClaimable { amount_satoshis, .. }|
783 Balance::CounterpartyRevokedOutputClaimable { amount_satoshis, .. }
784 => *amount_satoshis,
785 Balance::MaybeTimeoutClaimableHTLC { amount_satoshis, outbound_payment, .. }
786 => if *outbound_payment { 0 } else { *amount_satoshis },
787 Balance::MaybePreimageClaimableHTLC { .. } => 0,
788 }
789 }
790}
791
792#[derive(Clone, PartialEq, Eq)]
794struct IrrevocablyResolvedHTLC {
795 commitment_tx_output_idx: Option<u32>,
796 resolving_txid: Option<Txid>, resolving_tx: Option<Transaction>,
801 payment_preimage: Option<PaymentPreimage>,
803}
804
805impl Writeable for IrrevocablyResolvedHTLC {
810 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
811 let mapped_commitment_tx_output_idx = self.commitment_tx_output_idx.unwrap_or(u32::MAX);
812 write_tlv_fields!(writer, {
813 (0, mapped_commitment_tx_output_idx, required),
814 (1, self.resolving_txid, option),
815 (2, self.payment_preimage, option),
816 (3, self.resolving_tx, option),
817 });
818 Ok(())
819 }
820}
821
822impl Readable for IrrevocablyResolvedHTLC {
823 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
824 let mut mapped_commitment_tx_output_idx = 0;
825 let mut resolving_txid = None;
826 let mut payment_preimage = None;
827 let mut resolving_tx = None;
828 read_tlv_fields!(reader, {
829 (0, mapped_commitment_tx_output_idx, required),
830 (1, resolving_txid, option),
831 (2, payment_preimage, option),
832 (3, resolving_tx, option),
833 });
834 Ok(Self {
835 commitment_tx_output_idx: if mapped_commitment_tx_output_idx == u32::MAX { None } else { Some(mapped_commitment_tx_output_idx) },
836 resolving_txid,
837 payment_preimage,
838 resolving_tx,
839 })
840 }
841}
842
843pub struct ChannelMonitor<Signer: EcdsaChannelSigner> {
855 #[cfg(test)]
856 pub(crate) inner: Mutex<ChannelMonitorImpl<Signer>>,
857 #[cfg(not(test))]
858 pub(super) inner: Mutex<ChannelMonitorImpl<Signer>>,
859}
860
861impl<Signer: EcdsaChannelSigner> Clone for ChannelMonitor<Signer> where Signer: Clone {
862 fn clone(&self) -> Self {
863 let inner = self.inner.lock().unwrap().clone();
864 ChannelMonitor::from_impl(inner)
865 }
866}
867
868#[derive(Clone, PartialEq)]
869pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
870 latest_update_id: u64,
871 commitment_transaction_number_obscure_factor: u64,
872
873 destination_script: ScriptBuf,
874 broadcasted_holder_revokable_script: Option<(ScriptBuf, PublicKey, RevocationKey)>,
875 counterparty_payment_script: ScriptBuf,
876 shutdown_script: Option<ScriptBuf>,
877
878 channel_keys_id: [u8; 32],
879 holder_revocation_basepoint: RevocationBasepoint,
880 channel_id: ChannelId,
881 funding_info: (OutPoint, ScriptBuf),
882 current_counterparty_commitment_txid: Option<Txid>,
883 prev_counterparty_commitment_txid: Option<Txid>,
884
885 counterparty_commitment_params: CounterpartyCommitmentParameters,
886 funding_redeemscript: ScriptBuf,
887 channel_value_satoshis: u64,
888 their_cur_per_commitment_points: Option<(u64, PublicKey, Option<PublicKey>)>,
890
891 on_holder_tx_csv: u16,
892
893 commitment_secrets: CounterpartyCommitmentSecrets,
894 counterparty_claimable_outpoints: HashMap<Txid, Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>,
898 counterparty_commitment_txn_on_chain: HashMap<Txid, u64>,
904 counterparty_hash_commitment_number: HashMap<PaymentHash, u64>,
909
910 counterparty_fulfilled_htlcs: HashMap<SentHTLCId, PaymentPreimage>,
911
912 prev_holder_signed_commitment_tx: Option<HolderSignedTx>,
917 current_holder_commitment_tx: HolderSignedTx,
918
919 current_counterparty_commitment_number: u64,
922 current_holder_commitment_number: u64,
925
926 payment_preimages: HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)>,
939
940 pending_monitor_events: Vec<MonitorEvent>,
950
951 pub(super) pending_events: Vec<Event>,
952 pub(super) is_processing_pending_events: bool,
953
954 onchain_events_awaiting_threshold_conf: Vec<OnchainEventEntry>,
958
959 outputs_to_watch: HashMap<Txid, Vec<(u32, ScriptBuf)>>,
964
965 #[cfg(test)]
966 pub onchain_tx_handler: OnchainTxHandler<Signer>,
967 #[cfg(not(test))]
968 onchain_tx_handler: OnchainTxHandler<Signer>,
969
970 lockdown_from_offchain: bool,
974
975 holder_tx_signed: bool,
983
984 funding_spend_seen: bool,
988
989 holder_pays_commitment_tx_fee: Option<bool>,
992
993 funding_spend_confirmed: Option<Txid>,
996
997 confirmed_commitment_tx_counterparty_output: CommitmentTxCounterpartyOutputInfo,
998 htlcs_resolved_on_chain: Vec<IrrevocablyResolvedHTLC>,
1002
1003 spendable_txids_confirmed: Vec<Txid>,
1009
1010 best_block: BestBlock,
1016
1017 counterparty_node_id: Option<PublicKey>,
1019
1020 initial_counterparty_commitment_info: Option<(PublicKey, u32, u64, u64)>,
1027
1028 balances_empty_height: Option<u32>,
1030
1031 failed_back_htlc_ids: HashSet<SentHTLCId>,
1036}
1037
1038pub type TransactionOutputs = (Txid, Vec<(u32, TxOut)>);
1040
1041impl<Signer: EcdsaChannelSigner> PartialEq for ChannelMonitor<Signer> where Signer: PartialEq {
1042 fn eq(&self, other: &Self) -> bool {
1043 let ord = ((self as *const _) as usize) < ((other as *const _) as usize);
1047 let a = if ord { self.inner.unsafe_well_ordered_double_lock_self() } else { other.inner.unsafe_well_ordered_double_lock_self() };
1048 let b = if ord { other.inner.unsafe_well_ordered_double_lock_self() } else { self.inner.unsafe_well_ordered_double_lock_self() };
1049 a.eq(&b)
1050 }
1051}
1052
1053impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitor<Signer> {
1054 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1055 self.inner.lock().unwrap().write(writer)
1056 }
1057}
1058
1059const SERIALIZATION_VERSION: u8 = 1;
1061const MIN_SERIALIZATION_VERSION: u8 = 1;
1062
1063impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
1064 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), Error> {
1065 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
1066
1067 self.latest_update_id.write(writer)?;
1068
1069 U48(self.commitment_transaction_number_obscure_factor).write(writer)?;
1071
1072 self.destination_script.write(writer)?;
1073 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
1074 writer.write_all(&[0; 1])?;
1075 broadcasted_holder_revokable_script.0.write(writer)?;
1076 broadcasted_holder_revokable_script.1.write(writer)?;
1077 broadcasted_holder_revokable_script.2.write(writer)?;
1078 } else {
1079 writer.write_all(&[1; 1])?;
1080 }
1081
1082 self.counterparty_payment_script.write(writer)?;
1083 match &self.shutdown_script {
1084 Some(script) => script.write(writer)?,
1085 None => ScriptBuf::new().write(writer)?,
1086 }
1087
1088 self.channel_keys_id.write(writer)?;
1089 self.holder_revocation_basepoint.write(writer)?;
1090 writer.write_all(&self.funding_info.0.txid[..])?;
1091 writer.write_all(&self.funding_info.0.index.to_be_bytes())?;
1092 self.funding_info.1.write(writer)?;
1093 self.current_counterparty_commitment_txid.write(writer)?;
1094 self.prev_counterparty_commitment_txid.write(writer)?;
1095
1096 self.counterparty_commitment_params.write(writer)?;
1097 self.funding_redeemscript.write(writer)?;
1098 self.channel_value_satoshis.write(writer)?;
1099
1100 match self.their_cur_per_commitment_points {
1101 Some((idx, pubkey, second_option)) => {
1102 writer.write_all(&byte_utils::be48_to_array(idx))?;
1103 writer.write_all(&pubkey.serialize())?;
1104 match second_option {
1105 Some(second_pubkey) => {
1106 writer.write_all(&second_pubkey.serialize())?;
1107 },
1108 None => {
1109 writer.write_all(&[0; 33])?;
1110 },
1111 }
1112 },
1113 None => {
1114 writer.write_all(&byte_utils::be48_to_array(0))?;
1115 },
1116 }
1117
1118 writer.write_all(&self.on_holder_tx_csv.to_be_bytes())?;
1119
1120 self.commitment_secrets.write(writer)?;
1121
1122 macro_rules! serialize_htlc_in_commitment {
1123 ($htlc_output: expr) => {
1124 writer.write_all(&[$htlc_output.offered as u8; 1])?;
1125 writer.write_all(&$htlc_output.amount_msat.to_be_bytes())?;
1126 writer.write_all(&$htlc_output.cltv_expiry.to_be_bytes())?;
1127 writer.write_all(&$htlc_output.payment_hash.0[..])?;
1128 $htlc_output.transaction_output_index.write(writer)?;
1129 }
1130 }
1131
1132 writer.write_all(&(self.counterparty_claimable_outpoints.len() as u64).to_be_bytes())?;
1133 for (ref txid, ref htlc_infos) in self.counterparty_claimable_outpoints.iter() {
1134 writer.write_all(&txid[..])?;
1135 writer.write_all(&(htlc_infos.len() as u64).to_be_bytes())?;
1136 for &(ref htlc_output, ref htlc_source) in htlc_infos.iter() {
1137 debug_assert!(htlc_source.is_none() || Some(**txid) == self.current_counterparty_commitment_txid
1138 || Some(**txid) == self.prev_counterparty_commitment_txid,
1139 "HTLC Sources for all revoked commitment transactions should be none!");
1140 serialize_htlc_in_commitment!(htlc_output);
1141 htlc_source.as_ref().map(|b| b.as_ref()).write(writer)?;
1142 }
1143 }
1144
1145 writer.write_all(&(self.counterparty_commitment_txn_on_chain.len() as u64).to_be_bytes())?;
1146 for (ref txid, commitment_number) in self.counterparty_commitment_txn_on_chain.iter() {
1147 writer.write_all(&txid[..])?;
1148 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1149 }
1150
1151 writer.write_all(&(self.counterparty_hash_commitment_number.len() as u64).to_be_bytes())?;
1152 for (ref payment_hash, commitment_number) in self.counterparty_hash_commitment_number.iter() {
1153 writer.write_all(&payment_hash.0[..])?;
1154 writer.write_all(&byte_utils::be48_to_array(*commitment_number))?;
1155 }
1156
1157 if let Some(ref prev_holder_tx) = self.prev_holder_signed_commitment_tx {
1158 writer.write_all(&[1; 1])?;
1159 prev_holder_tx.write(writer)?;
1160 } else {
1161 writer.write_all(&[0; 1])?;
1162 }
1163
1164 self.current_holder_commitment_tx.write(writer)?;
1165
1166 writer.write_all(&byte_utils::be48_to_array(self.current_counterparty_commitment_number))?;
1167 writer.write_all(&byte_utils::be48_to_array(self.current_holder_commitment_number))?;
1168
1169 writer.write_all(&(self.payment_preimages.len() as u64).to_be_bytes())?;
1170 for (payment_preimage, _) in self.payment_preimages.values() {
1171 writer.write_all(&payment_preimage.0[..])?;
1172 }
1173
1174 writer.write_all(&(self.pending_monitor_events.iter().filter(|ev| match ev {
1175 MonitorEvent::HTLCEvent(_) => true,
1176 MonitorEvent::HolderForceClosed(_) => true,
1177 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1178 _ => false,
1179 }).count() as u64).to_be_bytes())?;
1180 for event in self.pending_monitor_events.iter() {
1181 match event {
1182 MonitorEvent::HTLCEvent(upd) => {
1183 0u8.write(writer)?;
1184 upd.write(writer)?;
1185 },
1186 MonitorEvent::HolderForceClosed(_) => 1u8.write(writer)?,
1187 MonitorEvent::HolderForceClosedWithInfo { .. } => 1u8.write(writer)?,
1191 _ => {}, }
1193 }
1194
1195 writer.write_all(&(self.pending_events.len() as u64).to_be_bytes())?;
1196 for event in self.pending_events.iter() {
1197 event.write(writer)?;
1198 }
1199
1200 self.best_block.block_hash.write(writer)?;
1201 writer.write_all(&self.best_block.height.to_be_bytes())?;
1202
1203 writer.write_all(&(self.onchain_events_awaiting_threshold_conf.len() as u64).to_be_bytes())?;
1204 for ref entry in self.onchain_events_awaiting_threshold_conf.iter() {
1205 entry.write(writer)?;
1206 }
1207
1208 (self.outputs_to_watch.len() as u64).write(writer)?;
1209 for (txid, idx_scripts) in self.outputs_to_watch.iter() {
1210 txid.write(writer)?;
1211 (idx_scripts.len() as u64).write(writer)?;
1212 for (idx, script) in idx_scripts.iter() {
1213 idx.write(writer)?;
1214 script.write(writer)?;
1215 }
1216 }
1217 self.onchain_tx_handler.write(writer)?;
1218
1219 self.lockdown_from_offchain.write(writer)?;
1220 self.holder_tx_signed.write(writer)?;
1221
1222 let pending_monitor_events = match self.pending_monitor_events.iter().find(|ev| match ev {
1224 MonitorEvent::HolderForceClosedWithInfo { .. } => true,
1225 _ => false,
1226 }) {
1227 Some(MonitorEvent::HolderForceClosedWithInfo { outpoint, .. }) => {
1228 let mut pending_monitor_events = self.pending_monitor_events.clone();
1229 pending_monitor_events.push(MonitorEvent::HolderForceClosed(*outpoint));
1230 pending_monitor_events
1231 }
1232 _ => self.pending_monitor_events.clone(),
1233 };
1234
1235 write_tlv_fields!(writer, {
1236 (1, self.funding_spend_confirmed, option),
1237 (3, self.htlcs_resolved_on_chain, required_vec),
1238 (5, pending_monitor_events, required_vec),
1239 (7, self.funding_spend_seen, required),
1240 (9, self.counterparty_node_id, option),
1241 (11, self.confirmed_commitment_tx_counterparty_output, option),
1242 (13, self.spendable_txids_confirmed, required_vec),
1243 (15, self.counterparty_fulfilled_htlcs, required),
1244 (17, self.initial_counterparty_commitment_info, option),
1245 (19, self.channel_id, required),
1246 (21, self.balances_empty_height, option),
1247 (23, self.holder_pays_commitment_tx_fee, option),
1248 (25, self.payment_preimages, required),
1249 });
1250
1251 Ok(())
1252 }
1253}
1254
1255macro_rules! _process_events_body {
1256 ($self_opt: expr, $logger: expr, $event_to_handle: expr, $handle_event: expr) => {
1257 loop {
1258 let mut handling_res = Ok(());
1259 let (pending_events, repeated_events);
1260 if let Some(us) = $self_opt {
1261 let mut inner = us.inner.lock().unwrap();
1262 if inner.is_processing_pending_events {
1263 break handling_res;
1264 }
1265 inner.is_processing_pending_events = true;
1266
1267 pending_events = inner.pending_events.clone();
1268 repeated_events = inner.get_repeated_events();
1269 } else { break handling_res; }
1270
1271 let mut num_handled_events = 0;
1272 for event in pending_events {
1273 log_trace!($logger, "Handling event {:?}...", event);
1274 $event_to_handle = event;
1275 let event_handling_result = $handle_event;
1276 log_trace!($logger, "Done handling event, result: {:?}", event_handling_result);
1277 match event_handling_result {
1278 Ok(()) => num_handled_events += 1,
1279 Err(e) => {
1280 handling_res = Err(e);
1283 break;
1284 }
1285 }
1286 }
1287
1288 if handling_res.is_ok() {
1289 for event in repeated_events {
1290 $event_to_handle = event;
1293 let _ = $handle_event;
1294 }
1295 }
1296
1297 if let Some(us) = $self_opt {
1298 let mut inner = us.inner.lock().unwrap();
1299 inner.pending_events.drain(..num_handled_events);
1300 inner.is_processing_pending_events = false;
1301 if handling_res.is_ok() && !inner.pending_events.is_empty() {
1302 continue;
1305 }
1306 }
1307 break handling_res;
1308 }
1309 }
1310}
1311pub(super) use _process_events_body as process_events_body;
1312
1313pub(crate) struct WithChannelMonitor<'a, L: Deref> where L::Target: Logger {
1314 logger: &'a L,
1315 peer_id: Option<PublicKey>,
1316 channel_id: Option<ChannelId>,
1317 payment_hash: Option<PaymentHash>,
1318}
1319
1320impl<'a, L: Deref> Logger for WithChannelMonitor<'a, L> where L::Target: Logger {
1321 fn log(&self, mut record: Record) {
1322 record.peer_id = self.peer_id;
1323 record.channel_id = self.channel_id;
1324 record.payment_hash = self.payment_hash;
1325 self.logger.log(record)
1326 }
1327}
1328
1329impl<'a, L: Deref> WithChannelMonitor<'a, L> where L::Target: Logger {
1330 pub(crate) fn from<S: EcdsaChannelSigner>(logger: &'a L, monitor: &ChannelMonitor<S>, payment_hash: Option<PaymentHash>) -> Self {
1331 Self::from_impl(logger, &*monitor.inner.lock().unwrap(), payment_hash)
1332 }
1333
1334 pub(crate) fn from_impl<S: EcdsaChannelSigner>(logger: &'a L, monitor_impl: &ChannelMonitorImpl<S>, payment_hash: Option<PaymentHash>) -> Self {
1335 let peer_id = monitor_impl.counterparty_node_id;
1336 let channel_id = Some(monitor_impl.channel_id());
1337 WithChannelMonitor {
1338 logger, peer_id, channel_id, payment_hash,
1339 }
1340 }
1341}
1342
1343impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
1344 fn from_impl(imp: ChannelMonitorImpl<Signer>) -> Self {
1348 ChannelMonitor { inner: Mutex::new(imp) }
1349 }
1350
1351 pub(crate) fn new(secp_ctx: Secp256k1<secp256k1::All>, keys: Signer, shutdown_script: Option<ScriptBuf>,
1352 on_counterparty_tx_csv: u16, destination_script: &Script, funding_info: (OutPoint, ScriptBuf),
1353 channel_parameters: &ChannelTransactionParameters, holder_pays_commitment_tx_fee: bool,
1354 funding_redeemscript: ScriptBuf, channel_value_satoshis: u64,
1355 commitment_transaction_number_obscure_factor: u64,
1356 initial_holder_commitment_tx: HolderCommitmentTransaction,
1357 best_block: BestBlock, counterparty_node_id: PublicKey, channel_id: ChannelId,
1358 ) -> ChannelMonitor<Signer> {
1359
1360 assert!(commitment_transaction_number_obscure_factor <= (1 << 48));
1361 let counterparty_payment_script = chan_utils::get_counterparty_payment_script(
1362 &channel_parameters.channel_type_features, &keys.pubkeys().payment_point
1363 );
1364
1365 let counterparty_channel_parameters = channel_parameters.counterparty_parameters.as_ref().unwrap();
1366 let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
1367 let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
1368 let counterparty_commitment_params = CounterpartyCommitmentParameters { counterparty_delayed_payment_base_key, counterparty_htlc_base_key, on_counterparty_tx_csv };
1369
1370 let channel_keys_id = keys.channel_keys_id();
1371 let holder_revocation_basepoint = keys.pubkeys().revocation_basepoint;
1372
1373 let (holder_commitment_tx, current_holder_commitment_number) = {
1375 let trusted_tx = initial_holder_commitment_tx.trust();
1376 let txid = trusted_tx.txid();
1377
1378 let tx_keys = trusted_tx.keys();
1379 let holder_commitment_tx = HolderSignedTx {
1380 txid,
1381 revocation_key: tx_keys.revocation_key,
1382 a_htlc_key: tx_keys.broadcaster_htlc_key,
1383 b_htlc_key: tx_keys.countersignatory_htlc_key,
1384 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
1385 per_commitment_point: tx_keys.per_commitment_point,
1386 htlc_outputs: Vec::new(), to_self_value_sat: initial_holder_commitment_tx.to_broadcaster_value_sat(),
1388 feerate_per_kw: trusted_tx.feerate_per_kw(),
1389 };
1390 (holder_commitment_tx, trusted_tx.commitment_number())
1391 };
1392
1393 let onchain_tx_handler = OnchainTxHandler::new(
1394 channel_value_satoshis, channel_keys_id, destination_script.into(), keys,
1395 channel_parameters.clone(), initial_holder_commitment_tx, secp_ctx
1396 );
1397
1398 let mut outputs_to_watch = new_hash_map();
1399 outputs_to_watch.insert(funding_info.0.txid, vec![(funding_info.0.index as u32, funding_info.1.clone())]);
1400
1401 Self::from_impl(ChannelMonitorImpl {
1402 latest_update_id: 0,
1403 commitment_transaction_number_obscure_factor,
1404
1405 destination_script: destination_script.into(),
1406 broadcasted_holder_revokable_script: None,
1407 counterparty_payment_script,
1408 shutdown_script,
1409
1410 channel_keys_id,
1411 holder_revocation_basepoint,
1412 channel_id,
1413 funding_info,
1414 current_counterparty_commitment_txid: None,
1415 prev_counterparty_commitment_txid: None,
1416
1417 counterparty_commitment_params,
1418 funding_redeemscript,
1419 channel_value_satoshis,
1420 their_cur_per_commitment_points: None,
1421
1422 on_holder_tx_csv: counterparty_channel_parameters.selected_contest_delay,
1423
1424 commitment_secrets: CounterpartyCommitmentSecrets::new(),
1425 counterparty_claimable_outpoints: new_hash_map(),
1426 counterparty_commitment_txn_on_chain: new_hash_map(),
1427 counterparty_hash_commitment_number: new_hash_map(),
1428 counterparty_fulfilled_htlcs: new_hash_map(),
1429
1430 prev_holder_signed_commitment_tx: None,
1431 current_holder_commitment_tx: holder_commitment_tx,
1432 current_counterparty_commitment_number: 1 << 48,
1433 current_holder_commitment_number,
1434
1435 payment_preimages: new_hash_map(),
1436 pending_monitor_events: Vec::new(),
1437 pending_events: Vec::new(),
1438 is_processing_pending_events: false,
1439
1440 onchain_events_awaiting_threshold_conf: Vec::new(),
1441 outputs_to_watch,
1442
1443 onchain_tx_handler,
1444
1445 holder_pays_commitment_tx_fee: Some(holder_pays_commitment_tx_fee),
1446 lockdown_from_offchain: false,
1447 holder_tx_signed: false,
1448 funding_spend_seen: false,
1449 funding_spend_confirmed: None,
1450 confirmed_commitment_tx_counterparty_output: None,
1451 htlcs_resolved_on_chain: Vec::new(),
1452 spendable_txids_confirmed: Vec::new(),
1453
1454 best_block,
1455 counterparty_node_id: Some(counterparty_node_id),
1456 initial_counterparty_commitment_info: None,
1457 balances_empty_height: None,
1458
1459 failed_back_htlc_ids: new_hash_set(),
1460 })
1461 }
1462
1463 #[cfg(test)]
1464 fn provide_secret(&self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
1465 self.inner.lock().unwrap().provide_secret(idx, secret)
1466 }
1467
1468 pub(crate) fn provide_initial_counterparty_commitment_tx<L: Deref>(
1476 &self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1477 commitment_number: u64, their_cur_per_commitment_point: PublicKey, feerate_per_kw: u32,
1478 to_broadcaster_value_sat: u64, to_countersignatory_value_sat: u64, logger: &L,
1479 )
1480 where L::Target: Logger
1481 {
1482 let mut inner = self.inner.lock().unwrap();
1483 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1484 inner.provide_initial_counterparty_commitment_tx(txid,
1485 htlc_outputs, commitment_number, their_cur_per_commitment_point, feerate_per_kw,
1486 to_broadcaster_value_sat, to_countersignatory_value_sat, &logger);
1487 }
1488
1489 #[cfg(test)]
1494 fn provide_latest_counterparty_commitment_tx<L: Deref>(
1495 &self,
1496 txid: Txid,
1497 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
1498 commitment_number: u64,
1499 their_per_commitment_point: PublicKey,
1500 logger: &L,
1501 ) where L::Target: Logger {
1502 let mut inner = self.inner.lock().unwrap();
1503 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1504 inner.provide_latest_counterparty_commitment_tx(
1505 txid, htlc_outputs, commitment_number, their_per_commitment_point, &logger)
1506 }
1507
1508 #[cfg(test)]
1509 fn provide_latest_holder_commitment_tx(
1510 &self, holder_commitment_tx: HolderCommitmentTransaction,
1511 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Signature>, Option<HTLCSource>)>,
1512 ) {
1513 self.inner.lock().unwrap().provide_latest_holder_commitment_tx(holder_commitment_tx, htlc_outputs, &Vec::new(), Vec::new())
1514 }
1515
1516 pub(crate) fn provide_payment_preimage_unsafe_legacy<B: Deref, F: Deref, L: Deref>(
1527 &self,
1528 payment_hash: &PaymentHash,
1529 payment_preimage: &PaymentPreimage,
1530 broadcaster: &B,
1531 fee_estimator: &LowerBoundedFeeEstimator<F>,
1532 logger: &L,
1533 ) where
1534 B::Target: BroadcasterInterface,
1535 F::Target: FeeEstimator,
1536 L::Target: Logger,
1537 {
1538 let mut inner = self.inner.lock().unwrap();
1539 let logger = WithChannelMonitor::from_impl(logger, &*inner, Some(*payment_hash));
1540 inner.provide_payment_preimage(
1544 payment_hash, payment_preimage, &None, broadcaster, fee_estimator, &logger)
1545 }
1546
1547 pub fn update_monitor<B: Deref, F: Deref, L: Deref>(
1552 &self,
1553 updates: &ChannelMonitorUpdate,
1554 broadcaster: &B,
1555 fee_estimator: &F,
1556 logger: &L,
1557 ) -> Result<(), ()>
1558 where
1559 B::Target: BroadcasterInterface,
1560 F::Target: FeeEstimator,
1561 L::Target: Logger,
1562 {
1563 let mut inner = self.inner.lock().unwrap();
1564 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1565 inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
1566 }
1567
1568 pub fn get_latest_update_id(&self) -> u64 {
1573 self.inner.lock().unwrap().get_latest_update_id()
1574 }
1575
1576 pub fn get_funding_txo(&self) -> (OutPoint, ScriptBuf) {
1578 self.inner.lock().unwrap().get_funding_txo().clone()
1579 }
1580
1581 pub fn channel_id(&self) -> ChannelId {
1583 self.inner.lock().unwrap().channel_id()
1584 }
1585
1586 pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
1589 self.inner.lock().unwrap().get_outputs_to_watch()
1590 .iter().map(|(txid, outputs)| (*txid, outputs.clone())).collect()
1591 }
1592
1593 pub fn load_outputs_to_watch<F: Deref, L: Deref>(&self, filter: &F, logger: &L)
1597 where
1598 F::Target: chain::Filter, L::Target: Logger,
1599 {
1600 let lock = self.inner.lock().unwrap();
1601 let logger = WithChannelMonitor::from_impl(logger, &*lock, None);
1602 log_trace!(&logger, "Registering funding outpoint {}", &lock.get_funding_txo().0);
1603 filter.register_tx(&lock.get_funding_txo().0.txid, &lock.get_funding_txo().1);
1604 for (txid, outputs) in lock.get_outputs_to_watch().iter() {
1605 for (index, script_pubkey) in outputs.iter() {
1606 assert!(*index <= u16::MAX as u32);
1607 let outpoint = OutPoint { txid: *txid, index: *index as u16 };
1608 log_trace!(logger, "Registering outpoint {} with the filter for monitoring spends", outpoint);
1609 filter.register_output(WatchedOutput {
1610 block_hash: None,
1611 outpoint,
1612 script_pubkey: script_pubkey.clone(),
1613 });
1614 }
1615 }
1616 }
1617
1618 pub fn get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
1621 self.inner.lock().unwrap().get_and_clear_pending_monitor_events()
1622 }
1623
1624 pub fn process_pending_events<H: Deref, L: Deref>(&self, handler: &H, logger: &L)
1640 -> Result<(), ReplayEvent> where H::Target: EventHandler, L::Target: Logger {
1641 let mut ev;
1642 process_events_body!(Some(self), logger, ev, handler.handle_event(ev))
1643 }
1644
1645 pub async fn process_pending_events_async<
1649 Future: core::future::Future<Output = Result<(), ReplayEvent>>, H: Fn(Event) -> Future,
1650 L: Deref,
1651 >(
1652 &self, handler: &H, logger: &L,
1653 ) -> Result<(), ReplayEvent> where L::Target: Logger {
1654 let mut ev;
1655 process_events_body!(Some(self), logger, ev, { handler(ev).await })
1656 }
1657
1658 #[cfg(test)]
1659 pub fn get_and_clear_pending_events(&self) -> Vec<Event> {
1660 let mut ret = Vec::new();
1661 let mut lck = self.inner.lock().unwrap();
1662 mem::swap(&mut ret, &mut lck.pending_events);
1663 ret.append(&mut lck.get_repeated_events());
1664 ret
1665 }
1666
1667 pub fn initial_counterparty_commitment_tx(&self) -> Option<CommitmentTransaction> {
1680 self.inner.lock().unwrap().initial_counterparty_commitment_tx()
1681 }
1682
1683 pub fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
1704 self.inner.lock().unwrap().counterparty_commitment_txs_from_update(update)
1705 }
1706
1707 pub fn sign_to_local_justice_tx(&self, justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64) -> Result<Transaction, ()> {
1725 self.inner.lock().unwrap().sign_to_local_justice_tx(justice_tx, input_idx, value, commitment_number)
1726 }
1727
1728 pub(crate) fn get_min_seen_secret(&self) -> u64 {
1729 self.inner.lock().unwrap().get_min_seen_secret()
1730 }
1731
1732 pub(crate) fn get_cur_counterparty_commitment_number(&self) -> u64 {
1733 self.inner.lock().unwrap().get_cur_counterparty_commitment_number()
1734 }
1735
1736 pub(crate) fn get_cur_holder_commitment_number(&self) -> u64 {
1737 self.inner.lock().unwrap().get_cur_holder_commitment_number()
1738 }
1739
1740 pub(crate) fn no_further_updates_allowed(&self) -> bool {
1747 self.inner.lock().unwrap().no_further_updates_allowed()
1748 }
1749
1750 pub fn get_counterparty_node_id(&self) -> Option<PublicKey> {
1755 self.inner.lock().unwrap().counterparty_node_id
1756 }
1757
1758 pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
1768 &self, broadcaster: &B, fee_estimator: &F, logger: &L
1769 )
1770 where
1771 B::Target: BroadcasterInterface,
1772 F::Target: FeeEstimator,
1773 L::Target: Logger
1774 {
1775 let mut inner = self.inner.lock().unwrap();
1776 let fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
1777 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1778 inner.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &fee_estimator, &logger);
1779 }
1780
1781 #[cfg(any(test, feature = "unsafe_revoked_tx_signing"))]
1785 pub fn unsafe_get_latest_holder_commitment_txn<L: Deref>(&self, logger: &L) -> Vec<Transaction>
1786 where L::Target: Logger {
1787 let mut inner = self.inner.lock().unwrap();
1788 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1789 inner.unsafe_get_latest_holder_commitment_txn(&logger)
1790 }
1791
1792 pub fn block_connected<B: Deref, F: Deref, L: Deref>(
1804 &self,
1805 header: &Header,
1806 txdata: &TransactionData,
1807 height: u32,
1808 broadcaster: B,
1809 fee_estimator: F,
1810 logger: &L,
1811 ) -> Vec<TransactionOutputs>
1812 where
1813 B::Target: BroadcasterInterface,
1814 F::Target: FeeEstimator,
1815 L::Target: Logger,
1816 {
1817 let mut inner = self.inner.lock().unwrap();
1818 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1819 inner.block_connected(
1820 header, txdata, height, broadcaster, fee_estimator, &logger)
1821 }
1822
1823 pub fn block_disconnected<B: Deref, F: Deref, L: Deref>(
1826 &self,
1827 header: &Header,
1828 height: u32,
1829 broadcaster: B,
1830 fee_estimator: F,
1831 logger: &L,
1832 ) where
1833 B::Target: BroadcasterInterface,
1834 F::Target: FeeEstimator,
1835 L::Target: Logger,
1836 {
1837 let mut inner = self.inner.lock().unwrap();
1838 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1839 inner.block_disconnected(
1840 header, height, broadcaster, fee_estimator, &logger)
1841 }
1842
1843 pub fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
1851 &self,
1852 header: &Header,
1853 txdata: &TransactionData,
1854 height: u32,
1855 broadcaster: B,
1856 fee_estimator: F,
1857 logger: &L,
1858 ) -> Vec<TransactionOutputs>
1859 where
1860 B::Target: BroadcasterInterface,
1861 F::Target: FeeEstimator,
1862 L::Target: Logger,
1863 {
1864 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1865 let mut inner = self.inner.lock().unwrap();
1866 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1867 inner.transactions_confirmed(
1868 header, txdata, height, broadcaster, &bounded_fee_estimator, &logger)
1869 }
1870
1871 pub fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
1878 &self,
1879 txid: &Txid,
1880 broadcaster: B,
1881 fee_estimator: F,
1882 logger: &L,
1883 ) where
1884 B::Target: BroadcasterInterface,
1885 F::Target: FeeEstimator,
1886 L::Target: Logger,
1887 {
1888 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1889 let mut inner = self.inner.lock().unwrap();
1890 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1891 inner.transaction_unconfirmed(
1892 txid, broadcaster, &bounded_fee_estimator, &logger
1893 );
1894 }
1895
1896 pub fn best_block_updated<B: Deref, F: Deref, L: Deref>(
1904 &self,
1905 header: &Header,
1906 height: u32,
1907 broadcaster: B,
1908 fee_estimator: F,
1909 logger: &L,
1910 ) -> Vec<TransactionOutputs>
1911 where
1912 B::Target: BroadcasterInterface,
1913 F::Target: FeeEstimator,
1914 L::Target: Logger,
1915 {
1916 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1917 let mut inner = self.inner.lock().unwrap();
1918 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1919 inner.best_block_updated(
1920 header, height, broadcaster, &bounded_fee_estimator, &logger
1921 )
1922 }
1923
1924 pub fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
1926 let inner = self.inner.lock().unwrap();
1927 let mut txids: Vec<(Txid, u32, Option<BlockHash>)> = inner.onchain_events_awaiting_threshold_conf
1928 .iter()
1929 .map(|entry| (entry.txid, entry.height, entry.block_hash))
1930 .chain(inner.onchain_tx_handler.get_relevant_txids().into_iter())
1931 .collect();
1932 txids.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
1933 txids.dedup_by_key(|(txid, _, _)| *txid);
1934 txids
1935 }
1936
1937 pub fn current_best_block(&self) -> BestBlock {
1940 self.inner.lock().unwrap().best_block.clone()
1941 }
1942
1943 pub fn rebroadcast_pending_claims<B: Deref, F: Deref, L: Deref>(
1949 &self, broadcaster: B, fee_estimator: F, logger: &L,
1950 )
1951 where
1952 B::Target: BroadcasterInterface,
1953 F::Target: FeeEstimator,
1954 L::Target: Logger,
1955 {
1956 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1957 let mut inner = self.inner.lock().unwrap();
1958 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1959 let current_height = inner.best_block.height;
1960 let conf_target = inner.closure_conf_target();
1961 inner.onchain_tx_handler.rebroadcast_pending_claims(
1962 current_height, FeerateStrategy::HighestOfPreviousOrNew, &broadcaster, conf_target, &fee_estimator, &logger,
1963 );
1964 }
1965
1966 pub fn has_pending_claims(&self) -> bool
1968 {
1969 self.inner.lock().unwrap().onchain_tx_handler.has_pending_claims()
1970 }
1971
1972 pub fn signer_unblocked<B: Deref, F: Deref, L: Deref>(
1975 &self, broadcaster: B, fee_estimator: F, logger: &L,
1976 )
1977 where
1978 B::Target: BroadcasterInterface,
1979 F::Target: FeeEstimator,
1980 L::Target: Logger,
1981 {
1982 let fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
1983 let mut inner = self.inner.lock().unwrap();
1984 let logger = WithChannelMonitor::from_impl(logger, &*inner, None);
1985 let current_height = inner.best_block.height;
1986 let conf_target = inner.closure_conf_target();
1987 inner.onchain_tx_handler.rebroadcast_pending_claims(
1988 current_height, FeerateStrategy::RetryPrevious, &broadcaster, conf_target, &fee_estimator, &logger,
1989 );
1990 }
1991
1992 pub fn get_spendable_outputs(&self, tx: &Transaction, confirmation_height: u32) -> Vec<SpendableOutputDescriptor> {
2011 let inner = self.inner.lock().unwrap();
2012 let current_height = inner.best_block.height;
2013 let mut spendable_outputs = inner.get_spendable_outputs(tx);
2014 spendable_outputs.retain(|descriptor| {
2015 let mut conf_threshold = current_height.saturating_sub(ANTI_REORG_DELAY) + 1;
2016 if let SpendableOutputDescriptor::DelayedPaymentOutput(descriptor) = descriptor {
2017 conf_threshold = cmp::min(conf_threshold,
2018 current_height.saturating_sub(descriptor.to_self_delay as u32) + 1);
2019 }
2020 conf_threshold >= confirmation_height
2021 });
2022 spendable_outputs
2023 }
2024
2025 pub fn check_and_update_full_resolution_status<L: Logger>(&self, logger: &L) -> (bool, bool) {
2040 let mut is_all_funds_claimed = self.get_claimable_balances().is_empty();
2041 let current_height = self.current_best_block().height;
2042 let mut inner = self.inner.lock().unwrap();
2043
2044 if is_all_funds_claimed && !inner.funding_spend_seen {
2045 debug_assert!(false, "We should see funding spend by the time a monitor clears out");
2046 is_all_funds_claimed = false;
2047 }
2048
2049 let preimages_not_needed_elsewhere = inner.pending_monitor_events.is_empty();
2053
2054 match (inner.balances_empty_height, is_all_funds_claimed, preimages_not_needed_elsewhere) {
2055 (Some(balances_empty_height), true, true) => {
2056 (current_height >= balances_empty_height + ARCHIVAL_DELAY_BLOCKS, false)
2058 },
2059 (Some(_), false, _)|(Some(_), _, false) => {
2060 debug_assert!(false,
2065 "Thought we were done claiming funds, but claimable_balances now has entries");
2066 log_error!(logger,
2067 "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",
2068 inner.get_funding_txo().0);
2069 inner.balances_empty_height = None;
2070 (false, true)
2071 },
2072 (None, true, true) => {
2073 log_debug!(logger,
2076 "ChannelMonitor funded at {} is now fully resolved. It will become archivable in {} blocks",
2077 inner.get_funding_txo().0, ARCHIVAL_DELAY_BLOCKS);
2078 inner.balances_empty_height = Some(current_height);
2079 (false, true)
2080 },
2081 (None, false, _)|(None, _, false) => {
2082 (false, false)
2084 },
2085 }
2086 }
2087
2088 #[cfg(test)]
2089 pub fn get_counterparty_payment_script(&self) -> ScriptBuf {
2090 self.inner.lock().unwrap().counterparty_payment_script.clone()
2091 }
2092
2093 #[cfg(test)]
2094 pub fn set_counterparty_payment_script(&self, script: ScriptBuf) {
2095 self.inner.lock().unwrap().counterparty_payment_script = script;
2096 }
2097
2098 #[cfg(test)]
2099 pub fn do_mut_signer_call<F: FnMut(&mut Signer) -> ()>(&self, mut f: F) {
2100 let mut inner = self.inner.lock().unwrap();
2101 f(&mut inner.onchain_tx_handler.signer);
2102 }
2103}
2104
2105impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2106 fn get_htlc_balance(&self, htlc: &HTLCOutputInCommitment, source: Option<&HTLCSource>,
2109 holder_commitment: bool, counterparty_revoked_commitment: bool,
2110 confirmed_txid: Option<Txid>
2111 ) -> Option<Balance> {
2112 let htlc_commitment_tx_output_idx = htlc.transaction_output_index?;
2113
2114 let mut htlc_spend_txid_opt = None;
2115 let mut htlc_spend_tx_opt = None;
2116 let mut holder_timeout_spend_pending = None;
2117 let mut htlc_spend_pending = None;
2118 let mut holder_delayed_output_pending = None;
2119 for event in self.onchain_events_awaiting_threshold_conf.iter() {
2120 match event.event {
2121 OnchainEvent::HTLCUpdate { commitment_tx_output_idx, htlc_value_satoshis, .. }
2122 if commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) => {
2123 debug_assert!(htlc_spend_txid_opt.is_none());
2124 htlc_spend_txid_opt = Some(&event.txid);
2125 debug_assert!(htlc_spend_tx_opt.is_none());
2126 htlc_spend_tx_opt = event.transaction.as_ref();
2127 debug_assert!(holder_timeout_spend_pending.is_none());
2128 debug_assert_eq!(htlc_value_satoshis.unwrap(), htlc.amount_msat / 1000);
2129 holder_timeout_spend_pending = Some(event.confirmation_threshold());
2130 },
2131 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. }
2132 if commitment_tx_output_idx == htlc_commitment_tx_output_idx => {
2133 debug_assert!(htlc_spend_txid_opt.is_none());
2134 htlc_spend_txid_opt = Some(&event.txid);
2135 debug_assert!(htlc_spend_tx_opt.is_none());
2136 htlc_spend_tx_opt = event.transaction.as_ref();
2137 debug_assert!(htlc_spend_pending.is_none());
2138 htlc_spend_pending = Some((event.confirmation_threshold(), preimage.is_some()));
2139 },
2140 OnchainEvent::MaturingOutput {
2141 descriptor: SpendableOutputDescriptor::DelayedPaymentOutput(ref descriptor) }
2142 if event.transaction.as_ref().map(|tx| tx.input.iter().enumerate()
2143 .any(|(input_idx, inp)|
2144 Some(inp.previous_output.txid) == confirmed_txid &&
2145 inp.previous_output.vout == htlc_commitment_tx_output_idx &&
2146 descriptor.outpoint.index as usize == input_idx
2152 ))
2153 .unwrap_or(false)
2154 => {
2155 debug_assert!(holder_delayed_output_pending.is_none());
2156 holder_delayed_output_pending = Some(event.confirmation_threshold());
2157 },
2158 _ => {},
2159 }
2160 }
2161 let htlc_resolved = self.htlcs_resolved_on_chain.iter()
2162 .any(|v| if v.commitment_tx_output_idx == Some(htlc_commitment_tx_output_idx) {
2163 debug_assert!(htlc_spend_txid_opt.is_none());
2164 htlc_spend_txid_opt = v.resolving_txid.as_ref();
2165 debug_assert!(htlc_spend_tx_opt.is_none());
2166 htlc_spend_tx_opt = v.resolving_tx.as_ref();
2167 true
2168 } else { false });
2169 debug_assert!(holder_timeout_spend_pending.is_some() as u8 + htlc_spend_pending.is_some() as u8 + htlc_resolved as u8 <= 1);
2170
2171 let htlc_commitment_outpoint = BitcoinOutPoint::new(confirmed_txid.unwrap(), htlc_commitment_tx_output_idx);
2172 let htlc_output_to_spend =
2173 if let Some(txid) = htlc_spend_txid_opt {
2174 if let Some(ref tx) = htlc_spend_tx_opt {
2179 let htlc_input_idx_opt = tx.input.iter().enumerate()
2180 .find(|(_, input)| input.previous_output == htlc_commitment_outpoint)
2181 .map(|(idx, _)| idx as u32);
2182 debug_assert!(htlc_input_idx_opt.is_some());
2183 BitcoinOutPoint::new(*txid, htlc_input_idx_opt.unwrap_or(0))
2184 } else {
2185 debug_assert!(!self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx());
2186 BitcoinOutPoint::new(*txid, 0)
2187 }
2188 } else {
2189 htlc_commitment_outpoint
2190 };
2191 let htlc_output_spend_pending = self.onchain_tx_handler.is_output_spend_pending(&htlc_output_to_spend);
2192
2193 if let Some(conf_thresh) = holder_delayed_output_pending {
2194 debug_assert!(holder_commitment);
2195 return Some(Balance::ClaimableAwaitingConfirmations {
2196 amount_satoshis: htlc.amount_msat / 1000,
2197 confirmation_height: conf_thresh,
2198 source: BalanceSource::Htlc,
2199 });
2200 } else if htlc_resolved && !htlc_output_spend_pending {
2201 debug_assert!(holder_commitment || self.funding_spend_confirmed.is_some());
2207 } else if counterparty_revoked_commitment {
2208 let htlc_output_claim_pending = self.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2209 if let OnchainEvent::MaturingOutput {
2210 descriptor: SpendableOutputDescriptor::StaticOutput { .. }
2211 } = &event.event {
2212 event.transaction.as_ref().map(|tx| tx.input.iter().any(|inp| {
2213 if let Some(htlc_spend_txid) = htlc_spend_txid_opt {
2214 tx.compute_txid() == *htlc_spend_txid || inp.previous_output.txid == *htlc_spend_txid
2215 } else {
2216 Some(inp.previous_output.txid) == confirmed_txid &&
2217 inp.previous_output.vout == htlc_commitment_tx_output_idx
2218 }
2219 })).unwrap_or(false)
2220 } else {
2221 false
2222 }
2223 });
2224 if htlc_output_claim_pending {
2225 } else {
2230 debug_assert!(holder_timeout_spend_pending.is_none(),
2231 "HTLCUpdate OnchainEvents should never appear for preimage claims");
2232 debug_assert!(!htlc.offered || htlc_spend_pending.is_none() || !htlc_spend_pending.unwrap().1,
2233 "We don't (currently) generate preimage claims against revoked outputs, where did you get one?!");
2234 return Some(Balance::CounterpartyRevokedOutputClaimable {
2235 amount_satoshis: htlc.amount_msat / 1000,
2236 });
2237 }
2238 } else if htlc.offered == holder_commitment {
2239 if let Some(conf_thresh) = holder_timeout_spend_pending {
2243 return Some(Balance::ClaimableAwaitingConfirmations {
2244 amount_satoshis: htlc.amount_msat / 1000,
2245 confirmation_height: conf_thresh,
2246 source: BalanceSource::Htlc,
2247 });
2248 } else {
2249 let outbound_payment = match source {
2250 None => {
2251 debug_assert!(false, "Outbound HTLCs should have a source");
2252 true
2253 },
2254 Some(&HTLCSource::PreviousHopData(_)) => false,
2255 Some(&HTLCSource::OutboundRoute { .. }) => true,
2256 };
2257 return Some(Balance::MaybeTimeoutClaimableHTLC {
2258 amount_satoshis: htlc.amount_msat / 1000,
2259 claimable_height: htlc.cltv_expiry,
2260 payment_hash: htlc.payment_hash,
2261 outbound_payment,
2262 });
2263 }
2264 } else if let Some((payment_preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
2265 debug_assert!(holder_timeout_spend_pending.is_none());
2271 if let Some((conf_thresh, true)) = htlc_spend_pending {
2272 return Some(Balance::ClaimableAwaitingConfirmations {
2273 amount_satoshis: htlc.amount_msat / 1000,
2274 confirmation_height: conf_thresh,
2275 source: BalanceSource::Htlc,
2276 });
2277 } else {
2278 return Some(Balance::ContentiousClaimable {
2279 amount_satoshis: htlc.amount_msat / 1000,
2280 timeout_height: htlc.cltv_expiry,
2281 payment_hash: htlc.payment_hash,
2282 payment_preimage: *payment_preimage,
2283 });
2284 }
2285 } else if !htlc_resolved {
2286 return Some(Balance::MaybePreimageClaimableHTLC {
2287 amount_satoshis: htlc.amount_msat / 1000,
2288 expiry_height: htlc.cltv_expiry,
2289 payment_hash: htlc.payment_hash,
2290 });
2291 }
2292 None
2293 }
2294}
2295
2296impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
2297 pub fn get_claimable_balances(&self) -> Vec<Balance> {
2312 let mut res = Vec::new();
2313 let us = self.inner.lock().unwrap();
2314
2315 let mut confirmed_txid = us.funding_spend_confirmed;
2316 let mut confirmed_counterparty_output = us.confirmed_commitment_tx_counterparty_output;
2317 let mut pending_commitment_tx_conf_thresh = None;
2318 let funding_spend_pending = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2319 if let OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } =
2320 event.event
2321 {
2322 confirmed_counterparty_output = commitment_tx_to_counterparty_output;
2323 Some((event.txid, event.confirmation_threshold()))
2324 } else { None }
2325 });
2326 if let Some((txid, conf_thresh)) = funding_spend_pending {
2327 debug_assert!(us.funding_spend_confirmed.is_none(),
2328 "We have a pending funding spend awaiting anti-reorg confirmation, we can't have confirmed it already!");
2329 confirmed_txid = Some(txid);
2330 pending_commitment_tx_conf_thresh = Some(conf_thresh);
2331 }
2332
2333 macro_rules! walk_htlcs {
2334 ($holder_commitment: expr, $counterparty_revoked_commitment: expr, $htlc_iter: expr) => {
2335 for (htlc, source) in $htlc_iter {
2336 if htlc.transaction_output_index.is_some() {
2337
2338 if let Some(bal) = us.get_htlc_balance(
2339 htlc, source, $holder_commitment, $counterparty_revoked_commitment, confirmed_txid
2340 ) {
2341 res.push(bal);
2342 }
2343 }
2344 }
2345 }
2346 }
2347
2348 if let Some(txid) = confirmed_txid {
2349 let mut found_commitment_tx = false;
2350 if let Some(counterparty_tx_htlcs) = us.counterparty_claimable_outpoints.get(&txid) {
2351 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2353 if let Some(value) = us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2354 if let OnchainEvent::MaturingOutput {
2355 descriptor: SpendableOutputDescriptor::StaticPaymentOutput(descriptor)
2356 } = &event.event {
2357 Some(descriptor.output.value)
2358 } else { None }
2359 }) {
2360 res.push(Balance::ClaimableAwaitingConfirmations {
2361 amount_satoshis: value.to_sat(),
2362 confirmation_height: conf_thresh,
2363 source: BalanceSource::CounterpartyForceClosed,
2364 });
2365 } else {
2366 }
2370 }
2371 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2372 walk_htlcs!(false, false, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2373 } else {
2374 walk_htlcs!(false, true, counterparty_tx_htlcs.iter().map(|(a, b)| (a, b.as_ref().map(|b| &**b))));
2375 let mut spent_counterparty_output = false;
2380 for event in us.onchain_events_awaiting_threshold_conf.iter() {
2381 if let OnchainEvent::MaturingOutput {
2382 descriptor: SpendableOutputDescriptor::StaticOutput { output, .. }
2383 } = &event.event {
2384 res.push(Balance::ClaimableAwaitingConfirmations {
2385 amount_satoshis: output.value.to_sat(),
2386 confirmation_height: event.confirmation_threshold(),
2387 source: BalanceSource::CounterpartyForceClosed,
2388 });
2389 if let Some(confirmed_to_self_idx) = confirmed_counterparty_output.map(|(idx, _)| idx) {
2390 if event.transaction.as_ref().map(|tx|
2391 tx.input.iter().any(|inp| inp.previous_output.vout == confirmed_to_self_idx)
2392 ).unwrap_or(false) {
2393 spent_counterparty_output = true;
2394 }
2395 }
2396 }
2397 }
2398
2399 if spent_counterparty_output {
2400 } else if let Some((confirmed_to_self_idx, amt)) = confirmed_counterparty_output {
2401 let output_spendable = us.onchain_tx_handler
2402 .is_output_spend_pending(&BitcoinOutPoint::new(txid, confirmed_to_self_idx));
2403 if output_spendable {
2404 res.push(Balance::CounterpartyRevokedOutputClaimable {
2405 amount_satoshis: amt.to_sat(),
2406 });
2407 }
2408 } else {
2409 }
2412 }
2413 found_commitment_tx = true;
2414 } else if txid == us.current_holder_commitment_tx.txid {
2415 walk_htlcs!(true, false, us.current_holder_commitment_tx.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())));
2416 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2417 res.push(Balance::ClaimableAwaitingConfirmations {
2418 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2419 confirmation_height: conf_thresh,
2420 source: BalanceSource::HolderForceClosed,
2421 });
2422 }
2423 found_commitment_tx = true;
2424 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2425 if txid == prev_commitment.txid {
2426 walk_htlcs!(true, false, prev_commitment.htlc_outputs.iter().map(|(a, _, c)| (a, c.as_ref())));
2427 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2428 res.push(Balance::ClaimableAwaitingConfirmations {
2429 amount_satoshis: prev_commitment.to_self_value_sat,
2430 confirmation_height: conf_thresh,
2431 source: BalanceSource::HolderForceClosed,
2432 });
2433 }
2434 found_commitment_tx = true;
2435 }
2436 }
2437 if !found_commitment_tx {
2438 if let Some(conf_thresh) = pending_commitment_tx_conf_thresh {
2439 res.push(Balance::ClaimableAwaitingConfirmations {
2443 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat,
2444 confirmation_height: conf_thresh,
2445 source: BalanceSource::CoopClose,
2446 });
2447 }
2448 }
2449 } else {
2450 let mut claimable_inbound_htlc_value_sat = 0;
2451 let mut nondust_htlc_count = 0;
2452 let mut outbound_payment_htlc_rounded_msat = 0;
2453 let mut outbound_forwarded_htlc_rounded_msat = 0;
2454 let mut inbound_claiming_htlc_rounded_msat = 0;
2455 let mut inbound_htlc_rounded_msat = 0;
2456 for (htlc, _, source) in us.current_holder_commitment_tx.htlc_outputs.iter() {
2457 if htlc.transaction_output_index.is_some() {
2458 nondust_htlc_count += 1;
2459 }
2460 let rounded_value_msat = if htlc.transaction_output_index.is_none() {
2461 htlc.amount_msat
2462 } else { htlc.amount_msat % 1000 };
2463 if htlc.offered {
2464 let outbound_payment = match source {
2465 None => {
2466 debug_assert!(false, "Outbound HTLCs should have a source");
2467 true
2468 },
2469 Some(HTLCSource::PreviousHopData(_)) => false,
2470 Some(HTLCSource::OutboundRoute { .. }) => true,
2471 };
2472 if outbound_payment {
2473 outbound_payment_htlc_rounded_msat += rounded_value_msat;
2474 } else {
2475 outbound_forwarded_htlc_rounded_msat += rounded_value_msat;
2476 }
2477 if htlc.transaction_output_index.is_some() {
2478 res.push(Balance::MaybeTimeoutClaimableHTLC {
2479 amount_satoshis: htlc.amount_msat / 1000,
2480 claimable_height: htlc.cltv_expiry,
2481 payment_hash: htlc.payment_hash,
2482 outbound_payment,
2483 });
2484 }
2485 } else if us.payment_preimages.contains_key(&htlc.payment_hash) {
2486 inbound_claiming_htlc_rounded_msat += rounded_value_msat;
2487 if htlc.transaction_output_index.is_some() {
2488 claimable_inbound_htlc_value_sat += htlc.amount_msat / 1000;
2489 }
2490 } else {
2491 inbound_htlc_rounded_msat += rounded_value_msat;
2492 if htlc.transaction_output_index.is_some() {
2493 res.push(Balance::MaybePreimageClaimableHTLC {
2496 amount_satoshis: htlc.amount_msat / 1000,
2497 expiry_height: htlc.cltv_expiry,
2498 payment_hash: htlc.payment_hash,
2499 });
2500 }
2501 }
2502 }
2503 res.push(Balance::ClaimableOnChannelClose {
2504 amount_satoshis: us.current_holder_commitment_tx.to_self_value_sat + claimable_inbound_htlc_value_sat,
2505 transaction_fee_satoshis: if us.holder_pays_commitment_tx_fee.unwrap_or(true) {
2506 chan_utils::commit_tx_fee_sat(
2507 us.current_holder_commitment_tx.feerate_per_kw, nondust_htlc_count,
2508 us.onchain_tx_handler.channel_type_features())
2509 } else { 0 },
2510 outbound_payment_htlc_rounded_msat,
2511 outbound_forwarded_htlc_rounded_msat,
2512 inbound_claiming_htlc_rounded_msat,
2513 inbound_htlc_rounded_msat,
2514 });
2515 }
2516
2517 res
2518 }
2519
2520 pub(crate) fn get_all_current_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2528 let mut res = new_hash_map();
2529 let us = self.inner.lock().unwrap();
2532 macro_rules! walk_counterparty_commitment {
2533 ($txid: expr) => {
2534 if let Some(ref latest_outpoints) = us.counterparty_claimable_outpoints.get($txid) {
2535 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2536 if let &Some(ref source) = source_option {
2537 res.insert((**source).clone(), (htlc.clone(),
2538 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned()));
2539 }
2540 }
2541 }
2542 }
2543 }
2544 if let Some(ref txid) = us.current_counterparty_commitment_txid {
2545 walk_counterparty_commitment!(txid);
2546 }
2547 if let Some(ref txid) = us.prev_counterparty_commitment_txid {
2548 walk_counterparty_commitment!(txid);
2549 }
2550 res
2551 }
2552
2553 pub(crate) fn get_pending_or_resolved_outbound_htlcs(&self) -> HashMap<HTLCSource, (HTLCOutputInCommitment, Option<PaymentPreimage>)> {
2561 let us = self.inner.lock().unwrap();
2562 let confirmed_txid = us.funding_spend_confirmed.or_else(|| {
2566 us.onchain_events_awaiting_threshold_conf.iter().find_map(|event| {
2567 if let OnchainEvent::FundingSpendConfirmation { .. } = event.event {
2568 Some(event.txid)
2569 } else { None }
2570 })
2571 });
2572
2573 if confirmed_txid.is_none() {
2574 mem::drop(us);
2577 return self.get_all_current_outbound_htlcs();
2578 }
2579
2580 let mut res = new_hash_map();
2581 macro_rules! walk_htlcs {
2582 ($holder_commitment: expr, $htlc_iter: expr) => {
2583 for (htlc, source) in $htlc_iter {
2584 if us.htlcs_resolved_on_chain.iter().any(|v| v.commitment_tx_output_idx == htlc.transaction_output_index) {
2585 } else if htlc.offered == $holder_commitment {
2591 let htlc_update_confd = us.onchain_events_awaiting_threshold_conf.iter().any(|event| {
2595 if let OnchainEvent::HTLCUpdate { commitment_tx_output_idx: Some(commitment_tx_output_idx), .. } = event.event {
2596 Some(commitment_tx_output_idx) == htlc.transaction_output_index &&
2600 us.best_block.height >= event.height + ANTI_REORG_DELAY - 1
2601 } else if let OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, .. } = event.event {
2602 Some(commitment_tx_output_idx) == htlc.transaction_output_index
2606 } else { false }
2607 });
2608 let counterparty_resolved_preimage_opt =
2609 us.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).cloned();
2610 if !htlc_update_confd || counterparty_resolved_preimage_opt.is_some() {
2611 res.insert(source.clone(), (htlc.clone(), counterparty_resolved_preimage_opt));
2612 }
2613 }
2614 }
2615 }
2616 }
2617
2618 let txid = confirmed_txid.unwrap();
2619 if Some(txid) == us.current_counterparty_commitment_txid || Some(txid) == us.prev_counterparty_commitment_txid {
2620 walk_htlcs!(false, us.counterparty_claimable_outpoints.get(&txid).unwrap().iter().filter_map(|(a, b)| {
2621 if let &Some(ref source) = b {
2622 Some((a, &**source))
2623 } else { None }
2624 }));
2625 } else if txid == us.current_holder_commitment_tx.txid {
2626 walk_htlcs!(true, us.current_holder_commitment_tx.htlc_outputs.iter().filter_map(|(a, _, c)| {
2627 if let Some(source) = c { Some((a, source)) } else { None }
2628 }));
2629 } else if let Some(prev_commitment) = &us.prev_holder_signed_commitment_tx {
2630 if txid == prev_commitment.txid {
2631 walk_htlcs!(true, prev_commitment.htlc_outputs.iter().filter_map(|(a, _, c)| {
2632 if let Some(source) = c { Some((a, source)) } else { None }
2633 }));
2634 }
2635 }
2636
2637 res
2638 }
2639
2640 pub(crate) fn get_stored_preimages(&self) -> HashMap<PaymentHash, (PaymentPreimage, Vec<PaymentClaimDetails>)> {
2641 self.inner.lock().unwrap().payment_preimages.clone()
2642 }
2643}
2644
2645macro_rules! fail_unbroadcast_htlcs {
2661 ($self: expr, $commitment_tx_type: expr, $commitment_txid_confirmed: expr, $commitment_tx_confirmed: expr,
2662 $commitment_tx_conf_height: expr, $commitment_tx_conf_hash: expr, $confirmed_htlcs_list: expr, $logger: expr) => { {
2663 debug_assert_eq!($commitment_tx_confirmed.compute_txid(), $commitment_txid_confirmed);
2664
2665 macro_rules! check_htlc_fails {
2666 ($txid: expr, $commitment_tx: expr, $per_commitment_outpoints: expr) => {
2667 if let Some(ref latest_outpoints) = $per_commitment_outpoints {
2668 for &(ref htlc, ref source_option) in latest_outpoints.iter() {
2669 if let &Some(ref source) = source_option {
2670 let confirmed_htlcs_iter: &mut dyn Iterator<Item = (&HTLCOutputInCommitment, Option<&HTLCSource>)> = &mut $confirmed_htlcs_list;
2680
2681 let mut matched_htlc = false;
2682 for (ref broadcast_htlc, ref broadcast_source) in confirmed_htlcs_iter {
2683 if broadcast_htlc.transaction_output_index.is_some() &&
2684 (Some(&**source) == *broadcast_source ||
2685 (broadcast_source.is_none() &&
2686 broadcast_htlc.payment_hash == htlc.payment_hash &&
2687 broadcast_htlc.amount_msat == htlc.amount_msat)) {
2688 matched_htlc = true;
2689 break;
2690 }
2691 }
2692 if matched_htlc { continue; }
2693 if $self.counterparty_fulfilled_htlcs.get(&SentHTLCId::from_source(source)).is_some() {
2694 continue;
2695 }
2696 $self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
2697 if entry.height != $commitment_tx_conf_height { return true; }
2698 match entry.event {
2699 OnchainEvent::HTLCUpdate { source: ref update_source, .. } => {
2700 *update_source != **source
2701 },
2702 _ => true,
2703 }
2704 });
2705 let entry = OnchainEventEntry {
2706 txid: $commitment_txid_confirmed,
2707 transaction: Some($commitment_tx_confirmed.clone()),
2708 height: $commitment_tx_conf_height,
2709 block_hash: Some(*$commitment_tx_conf_hash),
2710 event: OnchainEvent::HTLCUpdate {
2711 source: (**source).clone(),
2712 payment_hash: htlc.payment_hash.clone(),
2713 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
2714 commitment_tx_output_idx: None,
2715 },
2716 };
2717 log_trace!($logger, "Failing HTLC with payment_hash {} from {} counterparty commitment tx due to broadcast of {} commitment transaction {}, waiting for confirmation (at height {})",
2718 &htlc.payment_hash, $commitment_tx, $commitment_tx_type,
2719 $commitment_txid_confirmed, entry.confirmation_threshold());
2720 $self.onchain_events_awaiting_threshold_conf.push(entry);
2721 }
2722 }
2723 }
2724 }
2725 }
2726 if let Some(ref txid) = $self.current_counterparty_commitment_txid {
2727 check_htlc_fails!(txid, "current", $self.counterparty_claimable_outpoints.get(txid));
2728 }
2729 if let Some(ref txid) = $self.prev_counterparty_commitment_txid {
2730 check_htlc_fails!(txid, "previous", $self.counterparty_claimable_outpoints.get(txid));
2731 }
2732 } }
2733}
2734
2735#[cfg(test)]
2740pub fn deliberately_bogus_accepted_htlc_witness_program() -> Vec<u8> {
2741 use bitcoin::opcodes;
2742 let mut ret = [opcodes::all::OP_NOP.to_u8(); 136];
2743 ret[131] = opcodes::all::OP_DROP.to_u8();
2744 ret[132] = opcodes::all::OP_DROP.to_u8();
2745 ret[133] = opcodes::all::OP_DROP.to_u8();
2746 ret[134] = opcodes::all::OP_DROP.to_u8();
2747 ret[135] = opcodes::OP_TRUE.to_u8();
2748 Vec::from(&ret[..])
2749}
2750
2751#[cfg(test)]
2752pub fn deliberately_bogus_accepted_htlc_witness() -> Vec<Vec<u8>> {
2753 vec![Vec::new(), Vec::new(), Vec::new(), Vec::new(), deliberately_bogus_accepted_htlc_witness_program().into()].into()
2754}
2755
2756impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
2757 fn closure_conf_target(&self) -> ConfirmationTarget {
2760 if !self.current_holder_commitment_tx.htlc_outputs.is_empty() {
2763 return ConfirmationTarget::UrgentOnChainSweep;
2764 }
2765 if self.prev_holder_signed_commitment_tx.as_ref().map(|t| !t.htlc_outputs.is_empty()).unwrap_or(false) {
2766 return ConfirmationTarget::UrgentOnChainSweep;
2767 }
2768 if let Some(txid) = self.current_counterparty_commitment_txid {
2769 if !self.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
2770 return ConfirmationTarget::UrgentOnChainSweep;
2771 }
2772 }
2773 if let Some(txid) = self.prev_counterparty_commitment_txid {
2774 if !self.counterparty_claimable_outpoints.get(&txid).unwrap().is_empty() {
2775 return ConfirmationTarget::UrgentOnChainSweep;
2776 }
2777 }
2778 ConfirmationTarget::OutputSpendingFee
2779 }
2780
2781 fn provide_secret(&mut self, idx: u64, secret: [u8; 32]) -> Result<(), &'static str> {
2785 if let Err(()) = self.commitment_secrets.provide_secret(idx, secret) {
2786 return Err("Previous secret did not match new one");
2787 }
2788
2789 if let Some(txid) = self.prev_counterparty_commitment_txid.take() {
2792 if self.current_counterparty_commitment_txid.unwrap() != txid {
2793 let cur_claimables = self.counterparty_claimable_outpoints.get(
2794 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2795 for (_, ref source_opt) in self.counterparty_claimable_outpoints.get(&txid).unwrap() {
2796 if let Some(source) = source_opt {
2797 if !cur_claimables.iter()
2798 .any(|(_, cur_source_opt)| cur_source_opt == source_opt)
2799 {
2800 self.counterparty_fulfilled_htlcs.remove(&SentHTLCId::from_source(source));
2801 }
2802 }
2803 }
2804 for &mut (_, ref mut source_opt) in self.counterparty_claimable_outpoints.get_mut(&txid).unwrap() {
2805 *source_opt = None;
2806 }
2807 } else {
2808 assert!(cfg!(fuzzing), "Commitment txids are unique outside of fuzzing, where hashes can collide");
2809 }
2810 }
2811
2812 if !self.payment_preimages.is_empty() {
2813 let cur_holder_signed_commitment_tx = &self.current_holder_commitment_tx;
2814 let prev_holder_signed_commitment_tx = self.prev_holder_signed_commitment_tx.as_ref();
2815 let min_idx = self.get_min_seen_secret();
2816 let counterparty_hash_commitment_number = &mut self.counterparty_hash_commitment_number;
2817
2818 self.payment_preimages.retain(|&k, _| {
2819 for &(ref htlc, _, _) in cur_holder_signed_commitment_tx.htlc_outputs.iter() {
2820 if k == htlc.payment_hash {
2821 return true
2822 }
2823 }
2824 if let Some(prev_holder_commitment_tx) = prev_holder_signed_commitment_tx {
2825 for &(ref htlc, _, _) in prev_holder_commitment_tx.htlc_outputs.iter() {
2826 if k == htlc.payment_hash {
2827 return true
2828 }
2829 }
2830 }
2831 let contains = if let Some(cn) = counterparty_hash_commitment_number.get(&k) {
2832 if *cn < min_idx {
2833 return true
2834 }
2835 true
2836 } else { false };
2837 if contains {
2838 counterparty_hash_commitment_number.remove(&k);
2839 }
2840 false
2841 });
2842 }
2843
2844 Ok(())
2845 }
2846
2847 fn provide_initial_counterparty_commitment_tx<L: Deref>(
2848 &mut self, txid: Txid, htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2849 commitment_number: u64, their_per_commitment_point: PublicKey, feerate_per_kw: u32,
2850 to_broadcaster_value: u64, to_countersignatory_value: u64, logger: &WithChannelMonitor<L>,
2851 ) where L::Target: Logger {
2852 self.initial_counterparty_commitment_info = Some((their_per_commitment_point.clone(),
2853 feerate_per_kw, to_broadcaster_value, to_countersignatory_value));
2854
2855 #[cfg(debug_assertions)] {
2856 let rebuilt_commitment_tx = self.initial_counterparty_commitment_tx().unwrap();
2857 debug_assert_eq!(rebuilt_commitment_tx.trust().txid(), txid);
2858 }
2859
2860 self.provide_latest_counterparty_commitment_tx(txid, htlc_outputs, commitment_number,
2861 their_per_commitment_point, logger);
2862 }
2863
2864 fn provide_latest_counterparty_commitment_tx<L: Deref>(
2865 &mut self, txid: Txid,
2866 htlc_outputs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>,
2867 commitment_number: u64, their_per_commitment_point: PublicKey, logger: &WithChannelMonitor<L>,
2868 ) where L::Target: Logger {
2869 for &(ref htlc, _) in &htlc_outputs {
2874 self.counterparty_hash_commitment_number.insert(htlc.payment_hash, commitment_number);
2875 }
2876
2877 log_trace!(logger, "Tracking new counterparty commitment transaction with txid {} at commitment number {} with {} HTLC outputs", txid, commitment_number, htlc_outputs.len());
2878 self.prev_counterparty_commitment_txid = self.current_counterparty_commitment_txid.take();
2879 self.current_counterparty_commitment_txid = Some(txid);
2880 self.counterparty_claimable_outpoints.insert(txid, htlc_outputs.clone());
2881 self.current_counterparty_commitment_number = commitment_number;
2882 match self.their_cur_per_commitment_points {
2884 Some(old_points) => {
2885 if old_points.0 == commitment_number + 1 {
2886 self.their_cur_per_commitment_points = Some((old_points.0, old_points.1, Some(their_per_commitment_point)));
2887 } else if old_points.0 == commitment_number + 2 {
2888 if let Some(old_second_point) = old_points.2 {
2889 self.their_cur_per_commitment_points = Some((old_points.0 - 1, old_second_point, Some(their_per_commitment_point)));
2890 } else {
2891 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2892 }
2893 } else {
2894 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2895 }
2896 },
2897 None => {
2898 self.their_cur_per_commitment_points = Some((commitment_number, their_per_commitment_point, None));
2899 }
2900 }
2901 }
2902
2903 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>) {
2909 if htlc_outputs.iter().any(|(_, s, _)| s.is_some()) {
2910 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.trust().htlcs().len());
2914 for (a, b) in htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).map(|(h, _, _)| h).zip(holder_commitment_tx.trust().htlcs().iter()) {
2915 debug_assert_eq!(a, b);
2916 }
2917 debug_assert_eq!(htlc_outputs.iter().filter(|(_, s, _)| s.is_some()).count(), holder_commitment_tx.counterparty_htlc_sigs.len());
2918 for (a, b) in htlc_outputs.iter().filter_map(|(_, s, _)| s.as_ref()).zip(holder_commitment_tx.counterparty_htlc_sigs.iter()) {
2919 debug_assert_eq!(a, b);
2920 }
2921 debug_assert!(nondust_htlc_sources.is_empty());
2922 } else {
2923 #[cfg(debug_assertions)] {
2927 let mut prev = -1;
2928 for htlc in holder_commitment_tx.trust().htlcs().iter() {
2929 assert!(htlc.transaction_output_index.unwrap() as i32 > prev);
2930 prev = htlc.transaction_output_index.unwrap() as i32;
2931 }
2932 }
2933 debug_assert!(htlc_outputs.iter().all(|(htlc, _, _)| htlc.transaction_output_index.is_none()));
2934 debug_assert!(htlc_outputs.iter().all(|(_, sig_opt, _)| sig_opt.is_none()));
2935 debug_assert_eq!(holder_commitment_tx.trust().htlcs().len(), holder_commitment_tx.counterparty_htlc_sigs.len());
2936
2937 let mut sources_iter = nondust_htlc_sources.into_iter();
2938
2939 for (htlc, counterparty_sig) in holder_commitment_tx.trust().htlcs().iter()
2940 .zip(holder_commitment_tx.counterparty_htlc_sigs.iter())
2941 {
2942 if htlc.offered {
2943 let source = sources_iter.next().expect("Non-dust HTLC sources didn't match commitment tx");
2944 #[cfg(debug_assertions)] {
2945 assert!(source.possibly_matches_output(htlc));
2946 }
2947 htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), Some(source)));
2948 } else {
2949 htlc_outputs.push((htlc.clone(), Some(counterparty_sig.clone()), None));
2950 }
2951 }
2952 debug_assert!(sources_iter.next().is_none());
2953 }
2954
2955 let trusted_tx = holder_commitment_tx.trust();
2956 let txid = trusted_tx.txid();
2957 let tx_keys = trusted_tx.keys();
2958 self.current_holder_commitment_number = trusted_tx.commitment_number();
2959 let mut new_holder_commitment_tx = HolderSignedTx {
2960 txid,
2961 revocation_key: tx_keys.revocation_key,
2962 a_htlc_key: tx_keys.broadcaster_htlc_key,
2963 b_htlc_key: tx_keys.countersignatory_htlc_key,
2964 delayed_payment_key: tx_keys.broadcaster_delayed_payment_key,
2965 per_commitment_point: tx_keys.per_commitment_point,
2966 htlc_outputs,
2967 to_self_value_sat: holder_commitment_tx.to_broadcaster_value_sat(),
2968 feerate_per_kw: trusted_tx.feerate_per_kw(),
2969 };
2970 self.onchain_tx_handler.provide_latest_holder_tx(holder_commitment_tx);
2971 mem::swap(&mut new_holder_commitment_tx, &mut self.current_holder_commitment_tx);
2972 self.prev_holder_signed_commitment_tx = Some(new_holder_commitment_tx);
2973 for (claimed_htlc_id, claimed_preimage) in claimed_htlcs {
2974 #[cfg(debug_assertions)] {
2975 let cur_counterparty_htlcs = self.counterparty_claimable_outpoints.get(
2976 &self.current_counterparty_commitment_txid.unwrap()).unwrap();
2977 assert!(cur_counterparty_htlcs.iter().any(|(_, source_opt)| {
2978 if let Some(source) = source_opt {
2979 SentHTLCId::from_source(source) == *claimed_htlc_id
2980 } else { false }
2981 }));
2982 }
2983 self.counterparty_fulfilled_htlcs.insert(*claimed_htlc_id, *claimed_preimage);
2984 }
2985 }
2986
2987 fn provide_payment_preimage<B: Deref, F: Deref, L: Deref>(
2992 &mut self, payment_hash: &PaymentHash, payment_preimage: &PaymentPreimage,
2993 payment_info: &Option<PaymentClaimDetails>, broadcaster: &B,
2994 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>)
2995 where B::Target: BroadcasterInterface,
2996 F::Target: FeeEstimator,
2997 L::Target: Logger,
2998 {
2999 self.payment_preimages.entry(payment_hash.clone())
3000 .and_modify(|(_, payment_infos)| {
3001 if let Some(payment_info) = payment_info {
3002 if !payment_infos.contains(&payment_info) {
3003 payment_infos.push(payment_info.clone());
3004 }
3005 }
3006 })
3007 .or_insert_with(|| {
3008 (payment_preimage.clone(), payment_info.clone().into_iter().collect())
3009 });
3010
3011 let confirmed_spend_txid = self.funding_spend_confirmed.or_else(|| {
3012 self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3013 OnchainEvent::FundingSpendConfirmation { .. } => Some(event.txid),
3014 _ => None,
3015 })
3016 });
3017 let confirmed_spend_txid = if let Some(txid) = confirmed_spend_txid {
3018 txid
3019 } else {
3020 return;
3021 };
3022
3023 macro_rules! claim_htlcs {
3026 ($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3027 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None, $htlcs);
3028 let conf_target = self.closure_conf_target();
3029 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);
3030 }
3031 }
3032 if let Some(txid) = self.current_counterparty_commitment_txid {
3033 if txid == confirmed_spend_txid {
3034 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3035 claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3036 } else {
3037 debug_assert!(false);
3038 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3039 }
3040 return;
3041 }
3042 }
3043 if let Some(txid) = self.prev_counterparty_commitment_txid {
3044 if txid == confirmed_spend_txid {
3045 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3046 claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3047 } else {
3048 debug_assert!(false);
3049 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3050 }
3051 return;
3052 }
3053 }
3054
3055 if self.broadcasted_holder_revokable_script.is_some() {
3061 let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
3062 Some(&self.current_holder_commitment_tx)
3063 } else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3064 if prev_holder_commitment_tx.txid == confirmed_spend_txid {
3065 Some(prev_holder_commitment_tx)
3066 } else {
3067 None
3068 }
3069 } else {
3070 None
3071 };
3072 if let Some(holder_commitment_tx) = holder_commitment_tx {
3073 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
3077 let conf_target = self.closure_conf_target();
3078 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);
3079 }
3080 }
3081 }
3082
3083 fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3084 let funding_outp = HolderFundingOutput::build(
3085 self.funding_redeemscript.clone(),
3086 self.channel_value_satoshis,
3087 self.onchain_tx_handler.channel_type_features().clone()
3088 );
3089 let commitment_package = PackageTemplate::build_package(
3090 self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
3091 PackageSolvingData::HolderFundingOutput(funding_outp),
3092 self.best_block.height,
3093 );
3094 let mut claimable_outpoints = vec![commitment_package];
3095 let event = MonitorEvent::HolderForceClosedWithInfo {
3096 reason,
3097 outpoint: self.funding_info.0,
3098 channel_id: self.channel_id,
3099 };
3100 self.pending_monitor_events.push(event);
3101
3102 self.holder_tx_signed = true;
3106 let mut watch_outputs = Vec::new();
3107 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3111 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3115 &self.current_holder_commitment_tx, self.best_block.height,
3116 );
3117 let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
3118 let new_outputs = self.get_broadcasted_holder_watch_outputs(
3119 &self.current_holder_commitment_tx, &unsigned_commitment_tx
3120 );
3121 if !new_outputs.is_empty() {
3122 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
3123 }
3124 claimable_outpoints.append(&mut new_outpoints);
3125 }
3126 (claimable_outpoints, watch_outputs)
3127 }
3128
3129 pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
3130 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
3131 )
3132 where
3133 B::Target: BroadcasterInterface,
3134 F::Target: FeeEstimator,
3135 L::Target: Logger,
3136 {
3137 let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) });
3138 let conf_target = self.closure_conf_target();
3139 self.onchain_tx_handler.update_claims_view_from_requests(
3140 claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
3141 conf_target, fee_estimator, logger,
3142 );
3143 }
3144
3145 fn update_monitor<B: Deref, F: Deref, L: Deref>(
3146 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
3147 ) -> Result<(), ()>
3148 where B::Target: BroadcasterInterface,
3149 F::Target: FeeEstimator,
3150 L::Target: Logger,
3151 {
3152 if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3153 log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
3154 log_funding_info!(self), updates.updates.len());
3155 } else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3156 log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
3157 log_funding_info!(self), updates.updates.len());
3158 } else {
3159 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
3160 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
3161 }
3162
3163 if updates.counterparty_node_id.is_some() {
3164 if self.counterparty_node_id.is_none() {
3165 self.counterparty_node_id = updates.counterparty_node_id;
3166 } else {
3167 debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
3168 }
3169 }
3170
3171 if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
3180 assert_eq!(updates.updates.len(), 1);
3181 match updates.updates[0] {
3182 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3183 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
3186 debug_assert!(self.lockdown_from_offchain),
3187 _ => {
3188 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
3189 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
3190 },
3191 }
3192 }
3193 if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3194 if self.latest_update_id + 1 != updates.update_id {
3195 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
3196 }
3197 }
3198 let mut ret = Ok(());
3199 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
3200 for update in updates.updates.iter() {
3201 match update {
3202 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
3203 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
3204 if self.lockdown_from_offchain { panic!(); }
3205 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone());
3206 }
3207 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
3208 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
3209 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
3210 },
3211 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
3212 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
3213 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
3214 },
3215 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
3216 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
3217 if let Err(e) = self.provide_secret(*idx, *secret) {
3218 debug_assert!(false, "Latest counterparty commitment secret was invalid");
3219 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
3220 log_error!(logger, " {}", e);
3221 ret = Err(());
3222 }
3223 },
3224 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
3225 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
3226 self.lockdown_from_offchain = true;
3227 if *should_broadcast {
3228 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
3232 self.onchain_events_awaiting_threshold_conf.iter().any(
3233 |event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
3234 if detected_funding_spend {
3235 log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
3236 continue;
3237 }
3238 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
3239 } else if !self.holder_tx_signed {
3240 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
3241 log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
3242 log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
3243 } else {
3244 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
3248 }
3249 },
3250 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
3251 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
3252 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
3253 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
3254 }
3255 },
3256 }
3257 }
3258
3259 #[cfg(debug_assertions)] {
3260 self.counterparty_commitment_txs_from_update(updates);
3261 }
3262
3263 self.latest_update_id = updates.update_id;
3264
3265 let mut is_pre_close_update = false;
3269 for update in updates.updates.iter() {
3270 match update {
3271 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
3272 |ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
3273 |ChannelMonitorUpdateStep::ShutdownScript { .. }
3274 |ChannelMonitorUpdateStep::CommitmentSecret { .. } =>
3275 is_pre_close_update = true,
3276 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
3281 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3282 }
3283 }
3284
3285 if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
3286 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
3287 Err(())
3288 } else { ret }
3289 }
3290
3291 fn no_further_updates_allowed(&self) -> bool {
3292 self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
3293 }
3294
3295 fn get_latest_update_id(&self) -> u64 {
3296 self.latest_update_id
3297 }
3298
3299 fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
3300 &self.funding_info
3301 }
3302
3303 pub fn channel_id(&self) -> ChannelId {
3304 self.channel_id
3305 }
3306
3307 fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
3308 for txid in self.counterparty_commitment_txn_on_chain.keys() {
3312 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
3313 }
3314 &self.outputs_to_watch
3315 }
3316
3317 fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
3318 let mut ret = Vec::new();
3319 mem::swap(&mut ret, &mut self.pending_monitor_events);
3320 ret
3321 }
3322
3323 pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
3327 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
3328 let mut ret = Vec::with_capacity(pending_claim_events.len());
3329 for (claim_id, claim_event) in pending_claim_events {
3330 match claim_event {
3331 ClaimEvent::BumpCommitment {
3332 package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
3333 } => {
3334 let channel_id = self.channel_id;
3335 let counterparty_node_id = self.counterparty_node_id.unwrap();
3339 let commitment_txid = commitment_tx.compute_txid();
3340 debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
3341 let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
3342 let commitment_tx_fee_satoshis = self.channel_value_satoshis -
3343 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value.to_sat());
3344 ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
3345 channel_id,
3346 counterparty_node_id,
3347 claim_id,
3348 package_target_feerate_sat_per_1000_weight,
3349 commitment_tx,
3350 commitment_tx_fee_satoshis,
3351 anchor_descriptor: AnchorDescriptor {
3352 channel_derivation_parameters: ChannelDerivationParameters {
3353 keys_id: self.channel_keys_id,
3354 value_satoshis: self.channel_value_satoshis,
3355 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3356 },
3357 outpoint: BitcoinOutPoint {
3358 txid: commitment_txid,
3359 vout: anchor_output_idx,
3360 },
3361 },
3362 pending_htlcs,
3363 }));
3364 },
3365 ClaimEvent::BumpHTLC {
3366 target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
3367 } => {
3368 let channel_id = self.channel_id;
3369 let counterparty_node_id = self.counterparty_node_id.unwrap();
3373 let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
3374 for htlc in htlcs {
3375 htlc_descriptors.push(HTLCDescriptor {
3376 channel_derivation_parameters: ChannelDerivationParameters {
3377 keys_id: self.channel_keys_id,
3378 value_satoshis: self.channel_value_satoshis,
3379 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3380 },
3381 commitment_txid: htlc.commitment_txid,
3382 per_commitment_number: htlc.per_commitment_number,
3383 per_commitment_point: htlc.per_commitment_point,
3384 feerate_per_kw: 0,
3385 htlc: htlc.htlc,
3386 preimage: htlc.preimage,
3387 counterparty_sig: htlc.counterparty_sig,
3388 });
3389 }
3390 ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
3391 channel_id,
3392 counterparty_node_id,
3393 claim_id,
3394 target_feerate_sat_per_1000_weight,
3395 htlc_descriptors,
3396 tx_lock_time,
3397 }));
3398 }
3399 }
3400 }
3401 ret
3402 }
3403
3404 fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
3405 let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value,
3406 to_countersignatory_value) = self.initial_counterparty_commitment_info?;
3407 let htlc_outputs = vec![];
3408
3409 let commitment_tx = self.build_counterparty_commitment_tx(INITIAL_COMMITMENT_NUMBER,
3410 &their_per_commitment_point, to_broadcaster_value, to_countersignatory_value,
3411 feerate_per_kw, htlc_outputs);
3412 Some(commitment_tx)
3413 }
3414
3415 fn build_counterparty_commitment_tx(
3416 &self, commitment_number: u64, their_per_commitment_point: &PublicKey,
3417 to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
3418 mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
3419 ) -> CommitmentTransaction {
3420 let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
3421 .counterparty_parameters.as_ref().unwrap().pubkeys;
3422 let countersignatory_keys =
3423 &self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
3424
3425 let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
3426 let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
3427 let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
3428 &broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
3429 let channel_parameters =
3430 &self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
3431
3432 CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
3433 to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
3434 countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
3435 channel_parameters)
3436 }
3437
3438 fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
3439 update.updates.iter().filter_map(|update| {
3440 match update {
3441 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
3442 ref htlc_outputs, commitment_number, their_per_commitment_point,
3443 feerate_per_kw: Some(feerate_per_kw),
3444 to_broadcaster_value_sat: Some(to_broadcaster_value),
3445 to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
3446
3447 let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
3448 htlc.transaction_output_index.map(|_| (htlc.clone(), None))
3449 }).collect::<Vec<_>>();
3450
3451 let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
3452 &their_per_commitment_point, to_broadcaster_value,
3453 to_countersignatory_value, feerate_per_kw, nondust_htlcs);
3454
3455 debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
3456
3457 Some(commitment_tx)
3458 },
3459 _ => None,
3460 }
3461 }).collect()
3462 }
3463
3464 fn sign_to_local_justice_tx(
3465 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
3466 ) -> Result<Transaction, ()> {
3467 let secret = self.get_secret(commitment_number).ok_or(())?;
3468 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
3469 let their_per_commitment_point = PublicKey::from_secret_key(
3470 &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3471
3472 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3473 &self.holder_revocation_basepoint, &their_per_commitment_point);
3474 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3475 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
3476 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3477 self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3478
3479 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
3480 &justice_tx, input_idx, value, &per_commitment_key, &self.onchain_tx_handler.secp_ctx)?;
3481 justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
3482 justice_tx.input[input_idx].witness.push(&[1u8]);
3483 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
3484 Ok(justice_tx)
3485 }
3486
3487 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
3489 self.commitment_secrets.get_secret(idx)
3490 }
3491
3492 fn get_min_seen_secret(&self) -> u64 {
3493 self.commitment_secrets.get_min_seen_secret()
3494 }
3495
3496 fn get_cur_counterparty_commitment_number(&self) -> u64 {
3497 self.current_counterparty_commitment_number
3498 }
3499
3500 fn get_cur_holder_commitment_number(&self) -> u64 {
3501 self.current_holder_commitment_number
3502 }
3503
3504 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
3512 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
3513 where L::Target: Logger {
3514 let mut claimable_outpoints = Vec::new();
3517 let mut to_counterparty_output_info = None;
3518
3519 let commitment_txid = tx.compute_txid(); let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
3521
3522 macro_rules! ignore_error {
3523 ( $thing : expr ) => {
3524 match $thing {
3525 Ok(a) => a,
3526 Err(_) => return (claimable_outpoints, to_counterparty_output_info)
3527 }
3528 };
3529 }
3530
3531 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);
3532 if commitment_number >= self.get_min_seen_secret() {
3533 let secret = self.get_secret(commitment_number).unwrap();
3534 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
3535 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3536 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point,);
3537 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));
3538
3539 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3540 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
3541
3542 for (idx, outp) in tx.output.iter().enumerate() {
3544 if outp.script_pubkey == revokeable_p2wsh {
3545 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());
3546 let justice_package = PackageTemplate::build_package(
3547 commitment_txid, idx as u32,
3548 PackageSolvingData::RevokedOutput(revk_outp),
3549 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3550 );
3551 claimable_outpoints.push(justice_package);
3552 to_counterparty_output_info =
3553 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
3554 }
3555 }
3556
3557 if let Some(per_commitment_claimable_data) = per_commitment_option {
3559 for (htlc, _) in per_commitment_claimable_data {
3560 if let Some(transaction_output_index) = htlc.transaction_output_index {
3561 if transaction_output_index as usize >= tx.output.len() ||
3562 tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3563 return (claimable_outpoints, to_counterparty_output_info);
3565 }
3566 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);
3567 let counterparty_spendable_height = if htlc.offered {
3568 htlc.cltv_expiry
3569 } else {
3570 height
3571 };
3572 let justice_package = PackageTemplate::build_package(
3573 commitment_txid,
3574 transaction_output_index,
3575 PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
3576 counterparty_spendable_height,
3577 );
3578 claimable_outpoints.push(justice_package);
3579 }
3580 }
3581 }
3582
3583 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());
3587 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3588
3589 if let Some(per_commitment_claimable_data) = per_commitment_option {
3590 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
3591 block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3592 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3593 ), logger);
3594 } else {
3595 debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
3600 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
3601 block_hash, [].iter().map(|reference| *reference), logger);
3602 }
3603 }
3604 } else if let Some(per_commitment_claimable_data) = per_commitment_option {
3605 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3613
3614 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
3615 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
3616 per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3617 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3618 ), logger);
3619 let (htlc_claim_reqs, counterparty_output_info) =
3620 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx), per_commitment_option);
3621 to_counterparty_output_info = counterparty_output_info;
3622 for req in htlc_claim_reqs {
3623 claimable_outpoints.push(req);
3624 }
3625
3626 }
3627 (claimable_outpoints, to_counterparty_output_info)
3628 }
3629
3630 fn get_counterparty_output_claim_info(&self, commitment_number: u64, commitment_txid: Txid, tx: Option<&Transaction>, per_commitment_option: Option<&Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>>)
3632 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
3633 let mut claimable_outpoints = Vec::new();
3634 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
3635
3636 let per_commitment_claimable_data = match per_commitment_option {
3637 Some(outputs) => outputs,
3638 None => return (claimable_outpoints, to_counterparty_output_info),
3639 };
3640 let per_commitment_points = match self.their_cur_per_commitment_points {
3641 Some(points) => points,
3642 None => return (claimable_outpoints, to_counterparty_output_info),
3643 };
3644
3645 let per_commitment_point =
3646 if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
3649 else if let Some(point) = per_commitment_points.2.as_ref() {
3650 if per_commitment_points.0 == commitment_number + 1 {
3654 point
3655 } else { return (claimable_outpoints, to_counterparty_output_info); }
3656 } else { return (claimable_outpoints, to_counterparty_output_info); };
3657
3658 if let Some(transaction) = tx {
3659 let revocation_pubkey = RevocationKey::from_basepoint(
3660 &self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point);
3661
3662 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &per_commitment_point);
3663
3664 let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3665 self.counterparty_commitment_params.on_counterparty_tx_csv,
3666 &delayed_key).to_p2wsh();
3667 for (idx, outp) in transaction.output.iter().enumerate() {
3668 if outp.script_pubkey == revokeable_p2wsh {
3669 to_counterparty_output_info =
3670 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
3671 }
3672 }
3673 }
3674
3675 for &(ref htlc, _) in per_commitment_claimable_data.iter() {
3676 if let Some(transaction_output_index) = htlc.transaction_output_index {
3677 if let Some(transaction) = tx {
3678 if transaction_output_index as usize >= transaction.output.len() ||
3679 transaction.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3680 return (claimable_outpoints, to_counterparty_output_info);
3682 }
3683 }
3684 let preimage = if htlc.offered { if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
3685 if preimage.is_some() || !htlc.offered {
3686 let counterparty_htlc_outp = if htlc.offered {
3687 PackageSolvingData::CounterpartyOfferedHTLCOutput(
3688 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
3689 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3690 self.counterparty_commitment_params.counterparty_htlc_base_key,
3691 preimage.unwrap(), htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
3692 } else {
3693 PackageSolvingData::CounterpartyReceivedHTLCOutput(
3694 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
3695 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3696 self.counterparty_commitment_params.counterparty_htlc_base_key,
3697 htlc.clone(), self.onchain_tx_handler.channel_type_features().clone()))
3698 };
3699 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry);
3700 claimable_outpoints.push(counterparty_package);
3701 }
3702 }
3703 }
3704
3705 (claimable_outpoints, to_counterparty_output_info)
3706 }
3707
3708 fn check_spend_counterparty_htlc<L: Deref>(
3710 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
3711 ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
3712 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
3713 let per_commitment_key = match SecretKey::from_slice(&secret) {
3714 Ok(key) => key,
3715 Err(_) => return (Vec::new(), None)
3716 };
3717 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3718
3719 let htlc_txid = tx.compute_txid();
3720 let mut claimable_outpoints = vec![];
3721 let mut outputs_to_watch = None;
3722 for (idx, input) in tx.input.iter().enumerate() {
3733 if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
3734 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
3735 let revk_outp = RevokedOutput::build(
3736 per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3737 self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
3738 tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
3739 false
3740 );
3741 let justice_package = PackageTemplate::build_package(
3742 htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
3743 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3744 );
3745 claimable_outpoints.push(justice_package);
3746 if outputs_to_watch.is_none() {
3747 outputs_to_watch = Some((htlc_txid, vec![]));
3748 }
3749 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
3750 }
3751 }
3752 (claimable_outpoints, outputs_to_watch)
3753 }
3754
3755 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
3759 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3760
3761 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3762 let broadcasted_holder_revokable_script = Some((redeemscript.to_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3763
3764 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3765 if let Some(transaction_output_index) = htlc.transaction_output_index {
3766 let (htlc_output, counterparty_spendable_height) = if htlc.offered {
3767 let htlc_output = HolderHTLCOutput::build_offered(
3768 htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone()
3769 );
3770 (htlc_output, conf_height)
3771 } else {
3772 let payment_preimage = if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
3773 preimage.clone()
3774 } else {
3775 continue;
3777 };
3778 let htlc_output = HolderHTLCOutput::build_accepted(
3779 payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone()
3780 );
3781 (htlc_output, htlc.cltv_expiry)
3782 };
3783 let htlc_package = PackageTemplate::build_package(
3784 holder_tx.txid, transaction_output_index,
3785 PackageSolvingData::HolderHTLCOutput(htlc_output),
3786 counterparty_spendable_height,
3787 );
3788 claim_requests.push(htlc_package);
3789 }
3790 }
3791
3792 (claim_requests, broadcasted_holder_revokable_script)
3793 }
3794
3795 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3797 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3798 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3799 if let Some(transaction_output_index) = htlc.transaction_output_index {
3800 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3801 }
3802 }
3803 watch_outputs
3804 }
3805
3806 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 {
3811 let commitment_txid = tx.compute_txid();
3812 let mut claim_requests = Vec::new();
3813 let mut watch_outputs = Vec::new();
3814
3815 macro_rules! append_onchain_update {
3816 ($updates: expr, $to_watch: expr) => {
3817 claim_requests = $updates.0;
3818 self.broadcasted_holder_revokable_script = $updates.1;
3819 watch_outputs.append(&mut $to_watch);
3820 }
3821 }
3822
3823 let mut is_holder_tx = false;
3825
3826 if self.current_holder_commitment_tx.txid == commitment_txid {
3827 is_holder_tx = true;
3828 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3829 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
3830 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
3831 append_onchain_update!(res, to_watch);
3832 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
3833 block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
3834 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
3835 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
3836 if holder_tx.txid == commitment_txid {
3837 is_holder_tx = true;
3838 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3839 let res = self.get_broadcasted_holder_claims(holder_tx, height);
3840 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
3841 append_onchain_update!(res, to_watch);
3842 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
3843 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
3844 logger);
3845 }
3846 }
3847
3848 if is_holder_tx {
3849 Some((claim_requests, (commitment_txid, watch_outputs)))
3850 } else {
3851 None
3852 }
3853 }
3854
3855 pub fn cancel_prev_commitment_claims<L: Deref>(
3858 &mut self, logger: &L, confirmed_commitment_txid: &Txid
3859 ) where L::Target: Logger {
3860 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
3861 if counterparty_commitment_txid == confirmed_commitment_txid {
3863 continue;
3864 }
3865 for (htlc, _) in self.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
3868 log_trace!(logger, "Canceling claims for previously confirmed counterparty commitment {}",
3869 counterparty_commitment_txid);
3870 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
3871 if let Some(vout) = htlc.transaction_output_index {
3872 outpoint.vout = vout;
3873 self.onchain_tx_handler.abandon_claim(&outpoint);
3874 }
3875 }
3876 }
3877 if self.current_holder_commitment_tx.txid != *confirmed_commitment_txid {
3881 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3882 self.current_holder_commitment_tx.txid);
3883 let mut outpoint = BitcoinOutPoint { txid: self.current_holder_commitment_tx.txid, vout: 0 };
3884 for (htlc, _, _) in &self.current_holder_commitment_tx.htlc_outputs {
3885 if let Some(vout) = htlc.transaction_output_index {
3886 outpoint.vout = vout;
3887 self.onchain_tx_handler.abandon_claim(&outpoint);
3888 }
3889 }
3890 }
3891 if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3892 if prev_holder_commitment_tx.txid != *confirmed_commitment_txid {
3893 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3894 prev_holder_commitment_tx.txid);
3895 let mut outpoint = BitcoinOutPoint { txid: prev_holder_commitment_tx.txid, vout: 0 };
3896 for (htlc, _, _) in &prev_holder_commitment_tx.htlc_outputs {
3897 if let Some(vout) = htlc.transaction_output_index {
3898 outpoint.vout = vout;
3899 self.onchain_tx_handler.abandon_claim(&outpoint);
3900 }
3901 }
3902 }
3903 }
3904 }
3905
3906 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
3907 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
3909 &mut self, logger: &WithChannelMonitor<L>
3910 ) -> Vec<Transaction> where L::Target: Logger {
3911 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
3912 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
3913 let txid = commitment_tx.compute_txid();
3914 let mut holder_transactions = vec![commitment_tx];
3915 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3918 return holder_transactions;
3919 }
3920 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3921 if let Some(vout) = htlc.0.transaction_output_index {
3922 let preimage = if !htlc.0.offered {
3923 if let Some((preimage, _)) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3924 continue;
3926 }
3927 } else { None };
3928 if let Some(htlc_tx) = self.onchain_tx_handler.get_maybe_signed_htlc_tx(
3929 &::bitcoin::OutPoint { txid, vout }, &preimage
3930 ) {
3931 if htlc_tx.is_fully_signed() {
3932 holder_transactions.push(htlc_tx.0);
3933 }
3934 }
3935 }
3936 }
3937 holder_transactions
3938 }
3939
3940 fn block_connected<B: Deref, F: Deref, L: Deref>(
3941 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
3942 fee_estimator: F, logger: &WithChannelMonitor<L>,
3943 ) -> Vec<TransactionOutputs>
3944 where B::Target: BroadcasterInterface,
3945 F::Target: FeeEstimator,
3946 L::Target: Logger,
3947 {
3948 let block_hash = header.block_hash();
3949 self.best_block = BestBlock::new(block_hash, height);
3950
3951 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3952 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
3953 }
3954
3955 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
3956 &mut self,
3957 header: &Header,
3958 height: u32,
3959 broadcaster: B,
3960 fee_estimator: &LowerBoundedFeeEstimator<F>,
3961 logger: &WithChannelMonitor<L>,
3962 ) -> Vec<TransactionOutputs>
3963 where
3964 B::Target: BroadcasterInterface,
3965 F::Target: FeeEstimator,
3966 L::Target: Logger,
3967 {
3968 let block_hash = header.block_hash();
3969
3970 if height > self.best_block.height {
3971 self.best_block = BestBlock::new(block_hash, height);
3972 log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
3973 self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
3974 } else if block_hash != self.best_block.block_hash {
3975 self.best_block = BestBlock::new(block_hash, height);
3976 log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
3977 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3978 let conf_target = self.closure_conf_target();
3979 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, conf_target, fee_estimator, logger);
3980 Vec::new()
3981 } else { Vec::new() }
3982 }
3983
3984 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
3985 &mut self,
3986 header: &Header,
3987 txdata: &TransactionData,
3988 height: u32,
3989 broadcaster: B,
3990 fee_estimator: &LowerBoundedFeeEstimator<F>,
3991 logger: &WithChannelMonitor<L>,
3992 ) -> Vec<TransactionOutputs>
3993 where
3994 B::Target: BroadcasterInterface,
3995 F::Target: FeeEstimator,
3996 L::Target: Logger,
3997 {
3998 let txn_matched = self.filter_block(txdata);
3999 for tx in &txn_matched {
4000 let mut output_val = Amount::ZERO;
4001 for out in tx.output.iter() {
4002 if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4003 output_val += out.value;
4004 if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4005 }
4006 }
4007
4008 let block_hash = header.block_hash();
4009
4010 let mut watch_outputs = Vec::new();
4011 let mut claimable_outpoints = Vec::new();
4012 'tx_iter: for tx in &txn_matched {
4013 let txid = tx.compute_txid();
4014 log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
4015 if Some(txid) == self.funding_spend_confirmed {
4017 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
4018 continue 'tx_iter;
4019 }
4020 for ev in self.onchain_events_awaiting_threshold_conf.iter() {
4021 if ev.txid == txid {
4022 if let Some(conf_hash) = ev.block_hash {
4023 assert_eq!(header.block_hash(), conf_hash,
4024 "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
4025 This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
4026 }
4027 log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
4028 continue 'tx_iter;
4029 }
4030 }
4031 for htlc in self.htlcs_resolved_on_chain.iter() {
4032 if Some(txid) == htlc.resolving_txid {
4033 log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
4034 continue 'tx_iter;
4035 }
4036 }
4037 for spendable_txid in self.spendable_txids_confirmed.iter() {
4038 if txid == *spendable_txid {
4039 log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
4040 continue 'tx_iter;
4041 }
4042 }
4043
4044 if tx.input.len() == 1 {
4045 let prevout = &tx.input[0].previous_output;
4050 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
4051 let mut balance_spendable_csv = None;
4052 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
4053 &self.channel_id(), txid);
4054 self.funding_spend_seen = true;
4055 let mut commitment_tx_to_counterparty_output = None;
4056 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
4057 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
4058 if !new_outputs.1.is_empty() {
4059 watch_outputs.push(new_outputs);
4060 }
4061
4062 claimable_outpoints.append(&mut new_outpoints);
4063 balance_spendable_csv = Some(self.on_holder_tx_csv);
4064 } else {
4065 let mut new_watch_outputs = Vec::new();
4066 for (idx, outp) in tx.output.iter().enumerate() {
4067 new_watch_outputs.push((idx as u32, outp.clone()));
4068 }
4069 watch_outputs.push((txid, new_watch_outputs));
4070
4071 let (mut new_outpoints, counterparty_output_idx_sats) =
4072 self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
4073 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
4074
4075 claimable_outpoints.append(&mut new_outpoints);
4076 }
4077 }
4078 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4079 txid,
4080 transaction: Some((*tx).clone()),
4081 height,
4082 block_hash: Some(block_hash),
4083 event: OnchainEvent::FundingSpendConfirmation {
4084 on_local_output_csv: balance_spendable_csv,
4085 commitment_tx_to_counterparty_output,
4086 },
4087 });
4088 self.cancel_prev_commitment_claims(&logger, &txid);
4092 }
4093 }
4094 if tx.input.len() >= 1 {
4095 for tx_input in &tx.input {
4099 let commitment_txid = tx_input.previous_output.txid;
4100 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
4101 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
4102 &tx, commitment_number, &commitment_txid, height, &logger
4103 );
4104 claimable_outpoints.append(&mut new_outpoints);
4105 if let Some(new_outputs) = new_outputs_option {
4106 watch_outputs.push(new_outputs);
4107 }
4108 break;
4113 }
4114 }
4115 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
4116
4117 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
4118 }
4119 }
4120
4121 if height > self.best_block.height {
4122 self.best_block = BestBlock::new(block_hash, height);
4123 }
4124
4125 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
4126 }
4127
4128 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
4137 &mut self,
4138 conf_height: u32,
4139 conf_hash: BlockHash,
4140 txn_matched: Vec<&Transaction>,
4141 mut watch_outputs: Vec<TransactionOutputs>,
4142 mut claimable_outpoints: Vec<PackageTemplate>,
4143 broadcaster: &B,
4144 fee_estimator: &LowerBoundedFeeEstimator<F>,
4145 logger: &WithChannelMonitor<L>,
4146 ) -> Vec<TransactionOutputs>
4147 where
4148 B::Target: BroadcasterInterface,
4149 F::Target: FeeEstimator,
4150 L::Target: Logger,
4151 {
4152 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
4153 debug_assert!(self.best_block.height >= conf_height);
4154
4155 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
4156 if should_broadcast {
4157 let (mut new_outpoints, mut new_outputs) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HTLCsTimedOut);
4158 claimable_outpoints.append(&mut new_outpoints);
4159 watch_outputs.append(&mut new_outputs);
4160 }
4161
4162 let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
4164 self.onchain_events_awaiting_threshold_conf.drain(..).partition(
4165 |entry| entry.has_reached_confirmation_threshold(&self.best_block));
4166 self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
4167
4168 #[cfg(debug_assertions)]
4170 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
4171 .iter()
4172 .filter_map(|entry| match &entry.event {
4173 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
4174 _ => None,
4175 })
4176 .collect();
4177 #[cfg(debug_assertions)]
4178 let mut matured_htlcs = Vec::new();
4179
4180 for entry in onchain_events_reaching_threshold_conf {
4182 match entry.event {
4183 OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
4184 #[cfg(debug_assertions)]
4186 {
4187 debug_assert!(
4188 !unmatured_htlcs.contains(&&source),
4189 "An unmature HTLC transaction conflicts with a maturing one; failed to \
4190 call either transaction_unconfirmed for the conflicting transaction \
4191 or block_disconnected for a block containing it.");
4192 debug_assert!(
4193 !matured_htlcs.contains(&source),
4194 "A matured HTLC transaction conflicts with a maturing one; failed to \
4195 call either transaction_unconfirmed for the conflicting transaction \
4196 or block_disconnected for a block containing it.");
4197 matured_htlcs.push(source.clone());
4198 }
4199
4200 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
4201 &payment_hash, entry.txid);
4202 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4203 payment_hash,
4204 payment_preimage: None,
4205 source,
4206 htlc_value_satoshis,
4207 }));
4208 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4209 commitment_tx_output_idx,
4210 resolving_txid: Some(entry.txid),
4211 resolving_tx: entry.transaction,
4212 payment_preimage: None,
4213 });
4214 },
4215 OnchainEvent::MaturingOutput { descriptor } => {
4216 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
4217 self.pending_events.push(Event::SpendableOutputs {
4218 outputs: vec![descriptor],
4219 channel_id: Some(self.channel_id()),
4220 });
4221 self.spendable_txids_confirmed.push(entry.txid);
4222 },
4223 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
4224 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4225 commitment_tx_output_idx: Some(commitment_tx_output_idx),
4226 resolving_txid: Some(entry.txid),
4227 resolving_tx: entry.transaction,
4228 payment_preimage: preimage,
4229 });
4230 },
4231 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
4232 self.funding_spend_confirmed = Some(entry.txid);
4233 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
4234 },
4235 }
4236 }
4237
4238 if self.no_further_updates_allowed() {
4239 let current_holder_htlcs = self.current_holder_commitment_tx.htlc_outputs.iter()
4246 .map(|&(ref a, _, ref b)| (a, b.as_ref()));
4247
4248 let current_counterparty_htlcs = if let Some(txid) = self.current_counterparty_commitment_txid {
4249 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4250 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4251 } else { None }
4252 } else { None }.into_iter().flatten();
4253
4254 let prev_counterparty_htlcs = if let Some(txid) = self.prev_counterparty_commitment_txid {
4255 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4256 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4257 } else { None }
4258 } else { None }.into_iter().flatten();
4259
4260 let htlcs = current_holder_htlcs
4261 .chain(current_counterparty_htlcs)
4262 .chain(prev_counterparty_htlcs);
4263
4264 let height = self.best_block.height;
4265 for (htlc, source_opt) in htlcs {
4266 let source = match source_opt {
4268 Some(source) => source,
4269 None => continue,
4270 };
4271 let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
4272 Some(cltv_expiry) => cltv_expiry,
4273 None => continue,
4274 };
4275 let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
4276 if inbound_htlc_expiry > max_expiry_height {
4277 continue;
4278 }
4279 let duplicate_event = self.pending_monitor_events.iter().any(
4280 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4281 upd.source == *source
4282 } else { false });
4283 if duplicate_event {
4284 continue;
4285 }
4286 if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
4287 continue;
4288 }
4289 if !duplicate_event {
4290 log_error!(logger, "Failing back HTLC {} upstream to preserve the \
4291 channel as the forward HTLC hasn't resolved and our backward HTLC \
4292 expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
4293 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4294 source: source.clone(),
4295 payment_preimage: None,
4296 payment_hash: htlc.payment_hash,
4297 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
4298 }));
4299 }
4300 }
4301 }
4302
4303 let conf_target = self.closure_conf_target();
4304 self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
4305 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);
4306
4307 watch_outputs.retain(|&(ref txid, ref txouts)| {
4310 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
4311 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
4312 });
4313 #[cfg(test)]
4314 {
4315 for tx in &txn_matched {
4319 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
4320 for idx_and_script in outputs.iter() {
4321 assert!((idx_and_script.0 as usize) < tx.output.len());
4322 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
4323 }
4324 }
4325 }
4326 }
4327 watch_outputs
4328 }
4329
4330 fn block_disconnected<B: Deref, F: Deref, L: Deref>(
4331 &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
4332 ) where B::Target: BroadcasterInterface,
4333 F::Target: FeeEstimator,
4334 L::Target: Logger,
4335 {
4336 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
4337
4338 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
4342
4343 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4344 let conf_target = self.closure_conf_target();
4345 self.onchain_tx_handler.block_disconnected(height, broadcaster, conf_target, &bounded_fee_estimator, logger);
4346
4347 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
4348 }
4349
4350 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
4351 &mut self,
4352 txid: &Txid,
4353 broadcaster: B,
4354 fee_estimator: &LowerBoundedFeeEstimator<F>,
4355 logger: &WithChannelMonitor<L>,
4356 ) where
4357 B::Target: BroadcasterInterface,
4358 F::Target: FeeEstimator,
4359 L::Target: Logger,
4360 {
4361 let mut removed_height = None;
4362 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
4363 if entry.txid == *txid {
4364 removed_height = Some(entry.height);
4365 break;
4366 }
4367 }
4368
4369 if let Some(removed_height) = removed_height {
4370 log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
4371 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
4372 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
4373 false
4374 } else { true });
4375 }
4376
4377 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
4378
4379 let conf_target = self.closure_conf_target();
4380 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, conf_target, fee_estimator, logger);
4381 }
4382
4383 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
4386 let mut matched_txn = new_hash_set();
4387 txdata.iter().filter(|&&(_, tx)| {
4388 let mut matches = self.spends_watched_output(tx);
4389 for input in tx.input.iter() {
4390 if matches { break; }
4391 if matched_txn.contains(&input.previous_output.txid) {
4392 matches = true;
4393 }
4394 }
4395 if matches {
4396 matched_txn.insert(tx.compute_txid());
4397 }
4398 matches
4399 }).map(|(_, tx)| *tx).collect()
4400 }
4401
4402 fn spends_watched_output(&self, tx: &Transaction) -> bool {
4404 for input in tx.input.iter() {
4405 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
4406 for (idx, _script_pubkey) in outputs.iter() {
4407 if *idx == input.previous_output.vout {
4408 #[cfg(test)]
4409 {
4410 if _script_pubkey.is_p2wsh() {
4414 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
4415 return true;
4419 }
4420
4421 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4422 } else if _script_pubkey.is_p2wpkh() {
4423 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4424 } else { panic!(); }
4425 }
4426 return true;
4427 }
4428 }
4429 }
4430 }
4431
4432 false
4433 }
4434
4435 fn should_broadcast_holder_commitment_txn<L: Deref>(
4436 &self, logger: &WithChannelMonitor<L>
4437 ) -> bool where L::Target: Logger {
4438 if self.funding_spend_confirmed.is_some() ||
4441 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
4442 OnchainEvent::FundingSpendConfirmation { .. } => true,
4443 _ => false,
4444 }).is_some()
4445 {
4446 return false;
4447 }
4448 let height = self.best_block.height;
4459 macro_rules! scan_commitment {
4460 ($htlcs: expr, $holder_tx: expr) => {
4461 for ref htlc in $htlcs {
4462 let htlc_outbound = $holder_tx == htlc.offered;
4486 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
4487 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
4488 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
4489 return true;
4490 }
4491 }
4492 }
4493 }
4494
4495 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
4496
4497 if let Some(ref txid) = self.current_counterparty_commitment_txid {
4498 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4499 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4500 }
4501 }
4502 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
4503 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4504 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4505 }
4506 }
4507
4508 false
4509 }
4510
4511 fn is_resolving_htlc_output<L: Deref>(
4514 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4515 ) where L::Target: Logger {
4516 'outer_loop: for input in &tx.input {
4517 let mut payment_data = None;
4518 let htlc_claim = HTLCClaim::from_witness(&input.witness);
4519 let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
4520 let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
4521 #[cfg(not(fuzzing))]
4522 let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
4523 let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
4524 #[cfg(not(fuzzing))]
4525 let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
4526
4527 let mut payment_preimage = PaymentPreimage([0; 32]);
4528 if offered_preimage_claim || accepted_preimage_claim {
4529 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
4530 }
4531
4532 macro_rules! log_claim {
4533 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
4534 let outbound_htlc = $holder_tx == $htlc.offered;
4535 #[cfg(not(fuzzing))] debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
4539 #[cfg(not(fuzzing))] debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
4541 #[cfg(not(fuzzing))] debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
4545 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
4546 revocation_sig_claim as u8, 1);
4547 if ($holder_tx && revocation_sig_claim) ||
4548 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
4549 log_error!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}!",
4550 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
4551 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4552 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" });
4553 } else {
4554 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
4555 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
4556 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4557 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
4558 }
4559 }
4560 }
4561
4562 macro_rules! check_htlc_valid_counterparty {
4563 ($htlc_output: expr, $per_commitment_data: expr) => {
4564 for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
4565 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
4566 if let &Some(ref source) = pending_source {
4567 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
4568 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
4569 break;
4570 }
4571 }
4572 }
4573 }
4574 }
4575
4576 macro_rules! scan_commitment {
4577 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
4578 for (ref htlc_output, source_option) in $htlcs {
4579 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
4580 if let Some(ref source) = source_option {
4581 log_claim!($tx_info, $holder_tx, htlc_output, true);
4582 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
4588 } else if !$holder_tx {
4589 if let Some(current_counterparty_commitment_txid) = &self.current_counterparty_commitment_txid {
4590 check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
4591 }
4592 if payment_data.is_none() {
4593 if let Some(prev_counterparty_commitment_txid) = &self.prev_counterparty_commitment_txid {
4594 check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
4595 }
4596 }
4597 }
4598 if payment_data.is_none() {
4599 log_claim!($tx_info, $holder_tx, htlc_output, false);
4600 let outbound_htlc = $holder_tx == htlc_output.offered;
4601 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4602 txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
4603 event: OnchainEvent::HTLCSpendConfirmation {
4604 commitment_tx_output_idx: input.previous_output.vout,
4605 preimage: if accepted_preimage_claim || offered_preimage_claim {
4606 Some(payment_preimage) } else { None },
4607 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
4612 Some(self.on_holder_tx_csv) } else { None },
4613 },
4614 });
4615 continue 'outer_loop;
4616 }
4617 }
4618 }
4619 }
4620 }
4621
4622 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
4623 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4624 "our latest holder commitment tx", true);
4625 }
4626 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
4627 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
4628 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4629 "our previous holder commitment tx", true);
4630 }
4631 }
4632 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
4633 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))),
4634 "counterparty commitment tx", false);
4635 }
4636
4637 if let Some((source, payment_hash, amount_msat)) = payment_data {
4640 if accepted_preimage_claim {
4641 if !self.pending_monitor_events.iter().any(
4642 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
4643 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4644 txid: tx.compute_txid(),
4645 height,
4646 block_hash: Some(*block_hash),
4647 transaction: Some(tx.clone()),
4648 event: OnchainEvent::HTLCSpendConfirmation {
4649 commitment_tx_output_idx: input.previous_output.vout,
4650 preimage: Some(payment_preimage),
4651 on_to_local_output_csv: None,
4652 },
4653 });
4654 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4655 source,
4656 payment_preimage: Some(payment_preimage),
4657 payment_hash,
4658 htlc_value_satoshis: Some(amount_msat / 1000),
4659 }));
4660 }
4661 } else if offered_preimage_claim {
4662 if !self.pending_monitor_events.iter().any(
4663 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4664 upd.source == source
4665 } else { false }) {
4666 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4667 txid: tx.compute_txid(),
4668 transaction: Some(tx.clone()),
4669 height,
4670 block_hash: Some(*block_hash),
4671 event: OnchainEvent::HTLCSpendConfirmation {
4672 commitment_tx_output_idx: input.previous_output.vout,
4673 preimage: Some(payment_preimage),
4674 on_to_local_output_csv: None,
4675 },
4676 });
4677 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4678 source,
4679 payment_preimage: Some(payment_preimage),
4680 payment_hash,
4681 htlc_value_satoshis: Some(amount_msat / 1000),
4682 }));
4683 }
4684 } else {
4685 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
4686 if entry.height != height { return true; }
4687 match entry.event {
4688 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
4689 *htlc_source != source
4690 },
4691 _ => true,
4692 }
4693 });
4694 let entry = OnchainEventEntry {
4695 txid: tx.compute_txid(),
4696 transaction: Some(tx.clone()),
4697 height,
4698 block_hash: Some(*block_hash),
4699 event: OnchainEvent::HTLCUpdate {
4700 source,
4701 payment_hash,
4702 htlc_value_satoshis: Some(amount_msat / 1000),
4703 commitment_tx_output_idx: Some(input.previous_output.vout),
4704 },
4705 };
4706 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
4707 self.onchain_events_awaiting_threshold_conf.push(entry);
4708 }
4709 }
4710 }
4711 }
4712
4713 fn get_spendable_outputs(&self, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
4714 let mut spendable_outputs = Vec::new();
4715 for (i, outp) in tx.output.iter().enumerate() {
4716 if outp.script_pubkey == self.destination_script {
4717 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4718 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4719 output: outp.clone(),
4720 channel_keys_id: Some(self.channel_keys_id),
4721 });
4722 }
4723 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
4724 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
4725 spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
4726 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4727 per_commitment_point: broadcasted_holder_revokable_script.1,
4728 to_self_delay: self.on_holder_tx_csv,
4729 output: outp.clone(),
4730 revocation_pubkey: broadcasted_holder_revokable_script.2,
4731 channel_keys_id: self.channel_keys_id,
4732 channel_value_satoshis: self.channel_value_satoshis,
4733 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4734 }));
4735 }
4736 }
4737 if self.counterparty_payment_script == outp.script_pubkey {
4738 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4739 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4740 output: outp.clone(),
4741 channel_keys_id: self.channel_keys_id,
4742 channel_value_satoshis: self.channel_value_satoshis,
4743 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4744 }));
4745 }
4746 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4747 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4748 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4749 output: outp.clone(),
4750 channel_keys_id: Some(self.channel_keys_id),
4751 });
4752 }
4753 }
4754 spendable_outputs
4755 }
4756
4757 fn check_tx_and_push_spendable_outputs<L: Deref>(
4760 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4761 ) where L::Target: Logger {
4762 for spendable_output in self.get_spendable_outputs(tx) {
4763 let entry = OnchainEventEntry {
4764 txid: tx.compute_txid(),
4765 transaction: Some(tx.clone()),
4766 height,
4767 block_hash: Some(*block_hash),
4768 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4769 };
4770 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4771 self.onchain_events_awaiting_threshold_conf.push(entry);
4772 }
4773 }
4774}
4775
4776impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4777where
4778 T::Target: BroadcasterInterface,
4779 F::Target: FeeEstimator,
4780 L::Target: Logger,
4781{
4782 fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4783 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4784 }
4785
4786 fn block_disconnected(&self, header: &Header, height: u32) {
4787 self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4788 }
4789}
4790
4791impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4792where
4793 M: Deref<Target = ChannelMonitor<Signer>>,
4794 T::Target: BroadcasterInterface,
4795 F::Target: FeeEstimator,
4796 L::Target: Logger,
4797{
4798 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4799 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4800 }
4801
4802 fn transaction_unconfirmed(&self, txid: &Txid) {
4803 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
4804 }
4805
4806 fn best_block_updated(&self, header: &Header, height: u32) {
4807 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
4808 }
4809
4810 fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
4811 self.0.get_relevant_txids()
4812 }
4813}
4814
4815const MAX_ALLOC_SIZE: usize = 64*1024;
4816
4817impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
4818 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
4819 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
4820 macro_rules! unwrap_obj {
4821 ($key: expr) => {
4822 match $key {
4823 Ok(res) => res,
4824 Err(_) => return Err(DecodeError::InvalidValue),
4825 }
4826 }
4827 }
4828
4829 let (entropy_source, signer_provider) = args;
4830
4831 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4832
4833 let latest_update_id: u64 = Readable::read(reader)?;
4834 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
4835
4836 let destination_script = Readable::read(reader)?;
4837 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4838 0 => {
4839 let revokable_address = Readable::read(reader)?;
4840 let per_commitment_point = Readable::read(reader)?;
4841 let revokable_script = Readable::read(reader)?;
4842 Some((revokable_address, per_commitment_point, revokable_script))
4843 },
4844 1 => { None },
4845 _ => return Err(DecodeError::InvalidValue),
4846 };
4847 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
4848 let shutdown_script = {
4849 let script = <ScriptBuf as Readable>::read(reader)?;
4850 if script.is_empty() { None } else { Some(script) }
4851 };
4852
4853 let channel_keys_id = Readable::read(reader)?;
4854 let holder_revocation_basepoint = Readable::read(reader)?;
4855 let outpoint = OutPoint {
4858 txid: Readable::read(reader)?,
4859 index: Readable::read(reader)?,
4860 };
4861 let funding_info = (outpoint, Readable::read(reader)?);
4862 let current_counterparty_commitment_txid = Readable::read(reader)?;
4863 let prev_counterparty_commitment_txid = Readable::read(reader)?;
4864
4865 let counterparty_commitment_params = Readable::read(reader)?;
4866 let funding_redeemscript = Readable::read(reader)?;
4867 let channel_value_satoshis = Readable::read(reader)?;
4868
4869 let their_cur_per_commitment_points = {
4870 let first_idx = <U48 as Readable>::read(reader)?.0;
4871 if first_idx == 0 {
4872 None
4873 } else {
4874 let first_point = Readable::read(reader)?;
4875 let second_point_slice: [u8; 33] = Readable::read(reader)?;
4876 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4877 Some((first_idx, first_point, None))
4878 } else {
4879 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4880 }
4881 }
4882 };
4883
4884 let on_holder_tx_csv: u16 = Readable::read(reader)?;
4885
4886 let commitment_secrets = Readable::read(reader)?;
4887
4888 macro_rules! read_htlc_in_commitment {
4889 () => {
4890 {
4891 let offered: bool = Readable::read(reader)?;
4892 let amount_msat: u64 = Readable::read(reader)?;
4893 let cltv_expiry: u32 = Readable::read(reader)?;
4894 let payment_hash: PaymentHash = Readable::read(reader)?;
4895 let transaction_output_index: Option<u32> = Readable::read(reader)?;
4896
4897 HTLCOutputInCommitment {
4898 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4899 }
4900 }
4901 }
4902 }
4903
4904 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4905 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4906 for _ in 0..counterparty_claimable_outpoints_len {
4907 let txid: Txid = Readable::read(reader)?;
4908 let htlcs_count: u64 = Readable::read(reader)?;
4909 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4910 for _ in 0..htlcs_count {
4911 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4912 }
4913 if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
4914 return Err(DecodeError::InvalidValue);
4915 }
4916 }
4917
4918 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4919 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));
4920 for _ in 0..counterparty_commitment_txn_on_chain_len {
4921 let txid: Txid = Readable::read(reader)?;
4922 let commitment_number = <U48 as Readable>::read(reader)?.0;
4923 if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
4924 return Err(DecodeError::InvalidValue);
4925 }
4926 }
4927
4928 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4929 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4930 for _ in 0..counterparty_hash_commitment_number_len {
4931 let payment_hash: PaymentHash = Readable::read(reader)?;
4932 let commitment_number = <U48 as Readable>::read(reader)?.0;
4933 if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
4934 return Err(DecodeError::InvalidValue);
4935 }
4936 }
4937
4938 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4939 match <u8 as Readable>::read(reader)? {
4940 0 => None,
4941 1 => Some(Readable::read(reader)?),
4942 _ => return Err(DecodeError::InvalidValue),
4943 };
4944 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4945
4946 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4947 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4948
4949 let payment_preimages_len: u64 = Readable::read(reader)?;
4950 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4951 for _ in 0..payment_preimages_len {
4952 let preimage: PaymentPreimage = Readable::read(reader)?;
4953 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4954 if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
4955 return Err(DecodeError::InvalidValue);
4956 }
4957 }
4958
4959 let pending_monitor_events_len: u64 = Readable::read(reader)?;
4960 let mut pending_monitor_events = Some(
4961 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4962 for _ in 0..pending_monitor_events_len {
4963 let ev = match <u8 as Readable>::read(reader)? {
4964 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4965 1 => MonitorEvent::HolderForceClosed(funding_info.0),
4966 _ => return Err(DecodeError::InvalidValue)
4967 };
4968 pending_monitor_events.as_mut().unwrap().push(ev);
4969 }
4970
4971 let pending_events_len: u64 = Readable::read(reader)?;
4972 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4973 for _ in 0..pending_events_len {
4974 if let Some(event) = MaybeReadable::read(reader)? {
4975 pending_events.push(event);
4976 }
4977 }
4978
4979 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4980
4981 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4982 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4983 for _ in 0..waiting_threshold_conf_len {
4984 if let Some(val) = MaybeReadable::read(reader)? {
4985 onchain_events_awaiting_threshold_conf.push(val);
4986 }
4987 }
4988
4989 let outputs_to_watch_len: u64 = Readable::read(reader)?;
4990 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>>())));
4991 for _ in 0..outputs_to_watch_len {
4992 let txid = Readable::read(reader)?;
4993 let outputs_len: u64 = Readable::read(reader)?;
4994 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
4995 for _ in 0..outputs_len {
4996 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
4997 }
4998 if outputs_to_watch.insert(txid, outputs).is_some() {
4999 return Err(DecodeError::InvalidValue);
5000 }
5001 }
5002 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
5003 reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
5004 )?;
5005
5006 let lockdown_from_offchain = Readable::read(reader)?;
5007 let holder_tx_signed = Readable::read(reader)?;
5008
5009 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
5010 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
5011 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
5012 if prev_commitment_tx.to_self_value_sat == u64::MAX {
5013 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
5014 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
5015 return Err(DecodeError::InvalidValue);
5016 }
5017 }
5018
5019 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
5020 if current_holder_commitment_tx.to_self_value_sat == u64::MAX {
5021 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
5022 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
5023 return Err(DecodeError::InvalidValue);
5024 }
5025
5026 let mut funding_spend_confirmed = None;
5027 let mut htlcs_resolved_on_chain = Some(Vec::new());
5028 let mut funding_spend_seen = Some(false);
5029 let mut counterparty_node_id = None;
5030 let mut confirmed_commitment_tx_counterparty_output = None;
5031 let mut spendable_txids_confirmed = Some(Vec::new());
5032 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
5033 let mut initial_counterparty_commitment_info = None;
5034 let mut balances_empty_height = None;
5035 let mut channel_id = None;
5036 let mut holder_pays_commitment_tx_fee = None;
5037 let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
5038 read_tlv_fields!(reader, {
5039 (1, funding_spend_confirmed, option),
5040 (3, htlcs_resolved_on_chain, optional_vec),
5041 (5, pending_monitor_events, optional_vec),
5042 (7, funding_spend_seen, option),
5043 (9, counterparty_node_id, option),
5044 (11, confirmed_commitment_tx_counterparty_output, option),
5045 (13, spendable_txids_confirmed, optional_vec),
5046 (15, counterparty_fulfilled_htlcs, option),
5047 (17, initial_counterparty_commitment_info, option),
5048 (19, channel_id, option),
5049 (21, balances_empty_height, option),
5050 (23, holder_pays_commitment_tx_fee, option),
5051 (25, payment_preimages_with_info, option),
5052 });
5053 if let Some(payment_preimages_with_info) = payment_preimages_with_info {
5054 if payment_preimages_with_info.len() != payment_preimages.len() {
5055 return Err(DecodeError::InvalidValue);
5056 }
5057 for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
5058 let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
5063 if new_preimage != Some(payment_preimage) {
5064 return Err(DecodeError::InvalidValue);
5065 }
5066 }
5067 payment_preimages = payment_preimages_with_info;
5068 }
5069
5070 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
5073 if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
5074 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
5075 {
5076 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
5077 }
5078 }
5079
5080 if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
5084 counterparty_payment_script.is_p2wpkh()
5085 {
5086 let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
5087 counterparty_payment_script =
5088 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_p2wsh();
5089 }
5090
5091 Ok((best_block.block_hash, ChannelMonitor::from_impl(ChannelMonitorImpl {
5092 latest_update_id,
5093 commitment_transaction_number_obscure_factor,
5094
5095 destination_script,
5096 broadcasted_holder_revokable_script,
5097 counterparty_payment_script,
5098 shutdown_script,
5099
5100 channel_keys_id,
5101 holder_revocation_basepoint,
5102 channel_id: channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint)),
5103 funding_info,
5104 current_counterparty_commitment_txid,
5105 prev_counterparty_commitment_txid,
5106
5107 counterparty_commitment_params,
5108 funding_redeemscript,
5109 channel_value_satoshis,
5110 their_cur_per_commitment_points,
5111
5112 on_holder_tx_csv,
5113
5114 commitment_secrets,
5115 counterparty_claimable_outpoints,
5116 counterparty_commitment_txn_on_chain,
5117 counterparty_hash_commitment_number,
5118 counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
5119
5120 prev_holder_signed_commitment_tx,
5121 current_holder_commitment_tx,
5122 current_counterparty_commitment_number,
5123 current_holder_commitment_number,
5124
5125 payment_preimages,
5126 pending_monitor_events: pending_monitor_events.unwrap(),
5127 pending_events,
5128 is_processing_pending_events: false,
5129
5130 onchain_events_awaiting_threshold_conf,
5131 outputs_to_watch,
5132
5133 onchain_tx_handler,
5134
5135 lockdown_from_offchain,
5136 holder_tx_signed,
5137 holder_pays_commitment_tx_fee,
5138 funding_spend_seen: funding_spend_seen.unwrap(),
5139 funding_spend_confirmed,
5140 confirmed_commitment_tx_counterparty_output,
5141 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
5142 spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
5143
5144 best_block,
5145 counterparty_node_id,
5146 initial_counterparty_commitment_info,
5147 balances_empty_height,
5148 failed_back_htlc_ids: new_hash_set(),
5149 })))
5150 }
5151}
5152
5153#[cfg(test)]
5154mod tests {
5155 use bitcoin::amount::Amount;
5156 use bitcoin::locktime::absolute::LockTime;
5157 use bitcoin::script::{ScriptBuf, Builder};
5158 use bitcoin::opcodes;
5159 use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
5160 use bitcoin::transaction::OutPoint as BitcoinOutPoint;
5161 use bitcoin::sighash;
5162 use bitcoin::sighash::EcdsaSighashType;
5163 use bitcoin::hashes::Hash;
5164 use bitcoin::hashes::sha256::Hash as Sha256;
5165 use bitcoin::hex::FromHex;
5166 use bitcoin::hash_types::{BlockHash, Txid};
5167 use bitcoin::network::Network;
5168 use bitcoin::secp256k1::{SecretKey,PublicKey};
5169 use bitcoin::secp256k1::Secp256k1;
5170 use bitcoin::{Sequence, Witness};
5171
5172 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
5173
5174 use super::ChannelMonitorUpdateStep;
5175 use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash};
5176 use crate::chain::{BestBlock, Confirm};
5177 use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
5178 use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
5179 use crate::chain::transaction::OutPoint;
5180 use crate::sign::InMemorySigner;
5181 use crate::ln::types::ChannelId;
5182 use crate::types::payment::{PaymentPreimage, PaymentHash};
5183 use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
5184 use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
5185 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
5186 use crate::ln::functional_test_utils::*;
5187 use crate::ln::script::ShutdownScript;
5188 use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
5189 use crate::util::ser::{ReadableArgs, Writeable};
5190 use crate::util::logger::Logger;
5191 use crate::sync::Arc;
5192 use crate::io;
5193 use crate::types::features::ChannelTypeFeatures;
5194
5195 #[allow(unused_imports)]
5196 use crate::prelude::*;
5197
5198 use std::str::FromStr;
5199
5200 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
5201 let chanmon_cfgs = create_chanmon_cfgs(3);
5213 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5214 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5215 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5216 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
5217 create_announced_chan_between_nodes(&nodes, 1, 2);
5218
5219 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
5221
5222 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5224 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5225
5226 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
5227 assert_eq!(local_txn.len(), 1);
5228 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
5229 assert_eq!(remote_txn.len(), 3); check_spends!(remote_txn[1], remote_txn[0]);
5231 check_spends!(remote_txn[2], remote_txn[0]);
5232 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
5233
5234 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
5237 let conf_height = nodes[0].best_block_info().1 + 1;
5238 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
5239 &[(0, broadcast_tx)], conf_height);
5240
5241 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
5242 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
5243 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
5244
5245 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
5248 nodes[1].node.send_payment_with_route(route, payment_hash,
5249 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
5250 ).unwrap();
5251 check_added_monitors!(nodes[1], 1);
5252
5253 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
5257 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
5258 assert_eq!(replay_update.updates.len(), 1);
5259 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
5260 } else { panic!(); }
5261 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5262 payment_preimage: payment_preimage_1, payment_info: None,
5263 });
5264 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5265 payment_preimage: payment_preimage_2, payment_info: None,
5266 });
5267
5268 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
5269 assert!(
5270 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
5271 .is_err());
5272 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5275 assert!(txn_broadcasted.len() >= 2);
5276 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
5277 assert_eq!(tx.input.len(), 1);
5278 tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
5279 }).collect::<Vec<_>>();
5280 assert_eq!(htlc_txn.len(), 2);
5281 check_spends!(htlc_txn[0], broadcast_tx);
5282 check_spends!(htlc_txn[1], broadcast_tx);
5283 }
5284 #[test]
5285 fn test_funding_spend_refuses_updates() {
5286 do_test_funding_spend_refuses_updates(true);
5287 do_test_funding_spend_refuses_updates(false);
5288 }
5289
5290 #[test]
5291 fn test_prune_preimages() {
5292 let secp_ctx = Secp256k1::new();
5293 let logger = Arc::new(TestLogger::new());
5294 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
5295 let fee_estimator = TestFeeEstimator::new(253);
5296
5297 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5298
5299 let mut preimages = Vec::new();
5300 {
5301 for i in 0..20 {
5302 let preimage = PaymentPreimage([i; 32]);
5303 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
5304 preimages.push((preimage, hash));
5305 }
5306 }
5307
5308 macro_rules! preimages_slice_to_htlcs {
5309 ($preimages_slice: expr) => {
5310 {
5311 let mut res = Vec::new();
5312 for (idx, preimage) in $preimages_slice.iter().enumerate() {
5313 res.push((HTLCOutputInCommitment {
5314 offered: true,
5315 amount_msat: 0,
5316 cltv_expiry: 0,
5317 payment_hash: preimage.1.clone(),
5318 transaction_output_index: Some(idx as u32),
5319 }, ()));
5320 }
5321 res
5322 }
5323 }
5324 }
5325 macro_rules! preimages_slice_to_htlc_outputs {
5326 ($preimages_slice: expr) => {
5327 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
5328 }
5329 }
5330 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
5331 &bitcoin::secp256k1::Message::from_digest([42; 32]),
5332 &SecretKey::from_slice(&[42; 32]).unwrap());
5333
5334 macro_rules! test_preimages_exist {
5335 ($preimages_slice: expr, $monitor: expr) => {
5336 for preimage in $preimages_slice {
5337 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
5338 }
5339 }
5340 }
5341
5342 let keys = InMemorySigner::new(
5343 &secp_ctx,
5344 SecretKey::from_slice(&[41; 32]).unwrap(),
5345 SecretKey::from_slice(&[41; 32]).unwrap(),
5346 SecretKey::from_slice(&[41; 32]).unwrap(),
5347 SecretKey::from_slice(&[41; 32]).unwrap(),
5348 SecretKey::from_slice(&[41; 32]).unwrap(),
5349 [41; 32],
5350 0,
5351 [0; 32],
5352 [0; 32],
5353 );
5354
5355 let counterparty_pubkeys = ChannelPublicKeys {
5356 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5357 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5358 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5359 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5360 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
5361 };
5362 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5363 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5364 let channel_parameters = ChannelTransactionParameters {
5365 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5366 holder_selected_contest_delay: 66,
5367 is_outbound_from_holder: true,
5368 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5369 pubkeys: counterparty_pubkeys,
5370 selected_contest_delay: 67,
5371 }),
5372 funding_outpoint: Some(funding_outpoint),
5373 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5374 };
5375 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5378 let best_block = BestBlock::from_network(Network::Testnet);
5379 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5380 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5381 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5382 &channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5383 best_block, dummy_key, channel_id);
5384
5385 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
5386 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5387
5388 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5389 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5390 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
5391 preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
5392 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
5393 preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
5394 for &(ref preimage, ref hash) in preimages.iter() {
5395 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
5396 monitor.provide_payment_preimage_unsafe_legacy(
5397 hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
5398 );
5399 }
5400
5401 let mut secret = [0; 32];
5403 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
5404 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
5405 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
5406 test_preimages_exist!(&preimages[0..10], monitor);
5407 test_preimages_exist!(&preimages[15..20], monitor);
5408
5409 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
5410 preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
5411
5412 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
5414 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
5415 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
5416 test_preimages_exist!(&preimages[0..10], monitor);
5417 test_preimages_exist!(&preimages[17..20], monitor);
5418
5419 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
5420 preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
5421
5422 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
5425 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5426 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5427 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5428 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
5429 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
5430 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
5431 test_preimages_exist!(&preimages[0..10], monitor);
5432 test_preimages_exist!(&preimages[18..20], monitor);
5433
5434 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
5436 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5437 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
5438 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5439 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
5440 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
5441 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
5442 test_preimages_exist!(&preimages[0..5], monitor);
5443 }
5444
5445 #[test]
5446 fn test_claim_txn_weight_computation() {
5447 let secp_ctx = Secp256k1::new();
5451 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5452 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
5453
5454 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
5455 macro_rules! sign_input {
5456 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
5457 let htlc = HTLCOutputInCommitment {
5458 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
5459 amount_msat: 0,
5460 cltv_expiry: 2 << 16,
5461 payment_hash: PaymentHash([1; 32]),
5462 transaction_output_index: Some($idx as u32),
5463 };
5464 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)) };
5465 let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
5466 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
5467 let mut ser_sig = sig.serialize_der().to_vec();
5468 ser_sig.push(EcdsaSighashType::All as u8);
5469 $sum_actual_sigs += ser_sig.len() as u64;
5470 let witness = $sighash_parts.witness_mut($idx).unwrap();
5471 witness.push(ser_sig);
5472 if *$weight == WEIGHT_REVOKED_OUTPUT {
5473 witness.push(vec!(1));
5474 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
5475 witness.push(pubkey.clone().serialize().to_vec());
5476 } else if *$weight == weight_received_htlc($opt_anchors) {
5477 witness.push(vec![0]);
5478 } else {
5479 witness.push(PaymentPreimage([1; 32]).0.to_vec());
5480 }
5481 witness.push(redeem_script.into_bytes());
5482 let witness = witness.to_vec();
5483 println!("witness[0] {}", witness[0].len());
5484 println!("witness[1] {}", witness[1].len());
5485 println!("witness[2] {}", witness[2].len());
5486 }
5487 }
5488
5489 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
5490 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
5491
5492 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5494 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5495 let mut sum_actual_sigs = 0;
5496 for i in 0..4 {
5497 claim_tx.input.push(TxIn {
5498 previous_output: BitcoinOutPoint {
5499 txid,
5500 vout: i,
5501 },
5502 script_sig: ScriptBuf::new(),
5503 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5504 witness: Witness::new(),
5505 });
5506 }
5507 claim_tx.output.push(TxOut {
5508 script_pubkey: script_pubkey.clone(),
5509 value: Amount::ZERO,
5510 });
5511 let base_weight = claim_tx.weight().to_wu();
5512 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)];
5513 let mut inputs_total_weight = 2; {
5515 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5516 for (idx, inp) in inputs_weight.iter().enumerate() {
5517 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5518 inputs_total_weight += inp;
5519 }
5520 }
5521 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5522 }
5523
5524 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5526 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5527 let mut sum_actual_sigs = 0;
5528 for i in 0..4 {
5529 claim_tx.input.push(TxIn {
5530 previous_output: BitcoinOutPoint {
5531 txid,
5532 vout: i,
5533 },
5534 script_sig: ScriptBuf::new(),
5535 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5536 witness: Witness::new(),
5537 });
5538 }
5539 claim_tx.output.push(TxOut {
5540 script_pubkey: script_pubkey.clone(),
5541 value: Amount::ZERO,
5542 });
5543 let base_weight = claim_tx.weight().to_wu();
5544 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)];
5545 let mut inputs_total_weight = 2; {
5547 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5548 for (idx, inp) in inputs_weight.iter().enumerate() {
5549 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5550 inputs_total_weight += inp;
5551 }
5552 }
5553 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5554 }
5555
5556 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5558 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5559 let mut sum_actual_sigs = 0;
5560 claim_tx.input.push(TxIn {
5561 previous_output: BitcoinOutPoint {
5562 txid,
5563 vout: 0,
5564 },
5565 script_sig: ScriptBuf::new(),
5566 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5567 witness: Witness::new(),
5568 });
5569 claim_tx.output.push(TxOut {
5570 script_pubkey: script_pubkey.clone(),
5571 value: Amount::ZERO,
5572 });
5573 let base_weight = claim_tx.weight().to_wu();
5574 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5575 let mut inputs_total_weight = 2; {
5577 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5578 for (idx, inp) in inputs_weight.iter().enumerate() {
5579 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5580 inputs_total_weight += inp;
5581 }
5582 }
5583 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5584 }
5585 }
5586
5587 #[test]
5588 fn test_with_channel_monitor_impl_logger() {
5589 let secp_ctx = Secp256k1::new();
5590 let logger = Arc::new(TestLogger::new());
5591
5592 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5593
5594 let keys = InMemorySigner::new(
5595 &secp_ctx,
5596 SecretKey::from_slice(&[41; 32]).unwrap(),
5597 SecretKey::from_slice(&[41; 32]).unwrap(),
5598 SecretKey::from_slice(&[41; 32]).unwrap(),
5599 SecretKey::from_slice(&[41; 32]).unwrap(),
5600 SecretKey::from_slice(&[41; 32]).unwrap(),
5601 [41; 32],
5602 0,
5603 [0; 32],
5604 [0; 32],
5605 );
5606
5607 let counterparty_pubkeys = ChannelPublicKeys {
5608 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5609 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5610 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5611 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5612 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5613 };
5614 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5615 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5616 let channel_parameters = ChannelTransactionParameters {
5617 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5618 holder_selected_contest_delay: 66,
5619 is_outbound_from_holder: true,
5620 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5621 pubkeys: counterparty_pubkeys,
5622 selected_contest_delay: 67,
5623 }),
5624 funding_outpoint: Some(funding_outpoint),
5625 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5626 };
5627 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5628 let best_block = BestBlock::from_network(Network::Testnet);
5629 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5630 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5631 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5632 &channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5633 best_block, dummy_key, channel_id);
5634
5635 let chan_id = monitor.inner.lock().unwrap().channel_id();
5636 let payment_hash = PaymentHash([1; 32]);
5637 let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
5638 log_error!(context_logger, "This is an error");
5639 log_warn!(context_logger, "This is an error");
5640 log_debug!(context_logger, "This is an error");
5641 log_trace!(context_logger, "This is an error");
5642 log_gossip!(context_logger, "This is an error");
5643 log_info!(context_logger, "This is an error");
5644 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5645 }
5646 }