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_info = self.funding_spend_confirmed
3012 .map(|txid| (txid, None))
3013 .or_else(|| {
3014 self.onchain_events_awaiting_threshold_conf.iter().find_map(|event| match event.event {
3015 OnchainEvent::FundingSpendConfirmation { .. } => Some((event.txid, Some(event.height))),
3016 _ => None,
3017 })
3018 });
3019 let (confirmed_spend_txid, confirmed_spend_height) =
3020 if let Some((txid, height)) = confirmed_spend_info {
3021 (txid, height)
3022 } else {
3023 return;
3024 };
3025
3026 macro_rules! claim_htlcs {
3029 ($commitment_number: expr, $txid: expr, $htlcs: expr) => {
3030 let (htlc_claim_reqs, _) = self.get_counterparty_output_claim_info($commitment_number, $txid, None, $htlcs, confirmed_spend_height);
3031 let conf_target = self.closure_conf_target();
3032 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);
3033 }
3034 }
3035 if let Some(txid) = self.current_counterparty_commitment_txid {
3036 if txid == confirmed_spend_txid {
3037 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3038 claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3039 } else {
3040 debug_assert!(false);
3041 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3042 }
3043 return;
3044 }
3045 }
3046 if let Some(txid) = self.prev_counterparty_commitment_txid {
3047 if txid == confirmed_spend_txid {
3048 if let Some(commitment_number) = self.counterparty_commitment_txn_on_chain.get(&txid) {
3049 claim_htlcs!(*commitment_number, txid, self.counterparty_claimable_outpoints.get(&txid));
3050 } else {
3051 debug_assert!(false);
3052 log_error!(logger, "Detected counterparty commitment tx on-chain without tracking commitment number");
3053 }
3054 return;
3055 }
3056 }
3057
3058 if self.broadcasted_holder_revokable_script.is_some() {
3064 let holder_commitment_tx = if self.current_holder_commitment_tx.txid == confirmed_spend_txid {
3065 Some(&self.current_holder_commitment_tx)
3066 } else if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3067 if prev_holder_commitment_tx.txid == confirmed_spend_txid {
3068 Some(prev_holder_commitment_tx)
3069 } else {
3070 None
3071 }
3072 } else {
3073 None
3074 };
3075 if let Some(holder_commitment_tx) = holder_commitment_tx {
3076 let (claim_reqs, _) = self.get_broadcasted_holder_claims(&holder_commitment_tx, self.best_block.height);
3080 let conf_target = self.closure_conf_target();
3081 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);
3082 }
3083 }
3084 }
3085
3086 fn generate_claimable_outpoints_and_watch_outputs(&mut self, reason: ClosureReason) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
3087 let funding_outp = HolderFundingOutput::build(
3088 self.funding_redeemscript.clone(),
3089 self.channel_value_satoshis,
3090 self.onchain_tx_handler.channel_type_features().clone()
3091 );
3092 let commitment_package = PackageTemplate::build_package(
3093 self.funding_info.0.txid.clone(), self.funding_info.0.index as u32,
3094 PackageSolvingData::HolderFundingOutput(funding_outp),
3095 self.best_block.height,
3096 );
3097 let mut claimable_outpoints = vec![commitment_package];
3098 let event = MonitorEvent::HolderForceClosedWithInfo {
3099 reason,
3100 outpoint: self.funding_info.0,
3101 channel_id: self.channel_id,
3102 };
3103 self.pending_monitor_events.push(event);
3104
3105 self.holder_tx_signed = true;
3109 let mut watch_outputs = Vec::new();
3110 if !self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3114 let (mut new_outpoints, _) = self.get_broadcasted_holder_claims(
3118 &self.current_holder_commitment_tx, self.best_block.height,
3119 );
3120 let unsigned_commitment_tx = self.onchain_tx_handler.get_unsigned_holder_commitment_tx();
3121 let new_outputs = self.get_broadcasted_holder_watch_outputs(
3122 &self.current_holder_commitment_tx, &unsigned_commitment_tx
3123 );
3124 if !new_outputs.is_empty() {
3125 watch_outputs.push((self.current_holder_commitment_tx.txid.clone(), new_outputs));
3126 }
3127 claimable_outpoints.append(&mut new_outpoints);
3128 }
3129 (claimable_outpoints, watch_outputs)
3130 }
3131
3132 pub(crate) fn queue_latest_holder_commitment_txn_for_broadcast<B: Deref, F: Deref, L: Deref>(
3133 &mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &WithChannelMonitor<L>
3134 )
3135 where
3136 B::Target: BroadcasterInterface,
3137 F::Target: FeeEstimator,
3138 L::Target: Logger,
3139 {
3140 let (claimable_outpoints, _) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) });
3141 let conf_target = self.closure_conf_target();
3142 self.onchain_tx_handler.update_claims_view_from_requests(
3143 claimable_outpoints, self.best_block.height, self.best_block.height, broadcaster,
3144 conf_target, fee_estimator, logger,
3145 );
3146 }
3147
3148 fn update_monitor<B: Deref, F: Deref, L: Deref>(
3149 &mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
3150 ) -> Result<(), ()>
3151 where B::Target: BroadcasterInterface,
3152 F::Target: FeeEstimator,
3153 L::Target: Logger,
3154 {
3155 if self.latest_update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID && updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3156 log_info!(logger, "Applying pre-0.1 post-force-closed update to monitor {} with {} change(s).",
3157 log_funding_info!(self), updates.updates.len());
3158 } else if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3159 log_info!(logger, "Applying pre-0.1 force close update to monitor {} with {} change(s).",
3160 log_funding_info!(self), updates.updates.len());
3161 } else {
3162 log_info!(logger, "Applying update to monitor {}, bringing update_id from {} to {} with {} change(s).",
3163 log_funding_info!(self), self.latest_update_id, updates.update_id, updates.updates.len());
3164 }
3165
3166 if updates.counterparty_node_id.is_some() {
3167 if self.counterparty_node_id.is_none() {
3168 self.counterparty_node_id = updates.counterparty_node_id;
3169 } else {
3170 debug_assert_eq!(self.counterparty_node_id, updates.counterparty_node_id);
3171 }
3172 }
3173
3174 if updates.update_id == LEGACY_CLOSED_CHANNEL_UPDATE_ID || self.lockdown_from_offchain {
3183 assert_eq!(updates.updates.len(), 1);
3184 match updates.updates[0] {
3185 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3186 ChannelMonitorUpdateStep::PaymentPreimage { .. } =>
3189 debug_assert!(self.lockdown_from_offchain),
3190 _ => {
3191 log_error!(logger, "Attempted to apply post-force-close ChannelMonitorUpdate of type {}", updates.updates[0].variant_name());
3192 panic!("Attempted to apply post-force-close ChannelMonitorUpdate that wasn't providing a payment preimage");
3193 },
3194 }
3195 }
3196 if updates.update_id != LEGACY_CLOSED_CHANNEL_UPDATE_ID {
3197 if self.latest_update_id + 1 != updates.update_id {
3198 panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
3199 }
3200 }
3201 let mut ret = Ok(());
3202 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
3203 for update in updates.updates.iter() {
3204 match update {
3205 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
3206 log_trace!(logger, "Updating ChannelMonitor with latest holder commitment transaction info");
3207 if self.lockdown_from_offchain { panic!(); }
3208 self.provide_latest_holder_commitment_tx(commitment_tx.clone(), htlc_outputs.clone(), &claimed_htlcs, nondust_htlc_sources.clone());
3209 }
3210 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid, htlc_outputs, commitment_number, their_per_commitment_point, .. } => {
3211 log_trace!(logger, "Updating ChannelMonitor with latest counterparty commitment transaction info");
3212 self.provide_latest_counterparty_commitment_tx(*commitment_txid, htlc_outputs.clone(), *commitment_number, *their_per_commitment_point, logger)
3213 },
3214 ChannelMonitorUpdateStep::PaymentPreimage { payment_preimage, payment_info } => {
3215 log_trace!(logger, "Updating ChannelMonitor with payment preimage");
3216 self.provide_payment_preimage(&PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array()), &payment_preimage, payment_info, broadcaster, &bounded_fee_estimator, logger)
3217 },
3218 ChannelMonitorUpdateStep::CommitmentSecret { idx, secret } => {
3219 log_trace!(logger, "Updating ChannelMonitor with commitment secret");
3220 if let Err(e) = self.provide_secret(*idx, *secret) {
3221 debug_assert!(false, "Latest counterparty commitment secret was invalid");
3222 log_error!(logger, "Providing latest counterparty commitment secret failed/was refused:");
3223 log_error!(logger, " {}", e);
3224 ret = Err(());
3225 }
3226 },
3227 ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
3228 log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
3229 self.lockdown_from_offchain = true;
3230 if *should_broadcast {
3231 let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
3235 self.onchain_events_awaiting_threshold_conf.iter().any(
3236 |event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
3237 if detected_funding_spend {
3238 log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
3239 continue;
3240 }
3241 self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
3242 } else if !self.holder_tx_signed {
3243 log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
3244 log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
3245 log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
3246 } else {
3247 log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
3251 }
3252 },
3253 ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
3254 log_trace!(logger, "Updating ChannelMonitor with shutdown script");
3255 if let Some(shutdown_script) = self.shutdown_script.replace(scriptpubkey.clone()) {
3256 panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
3257 }
3258 },
3259 }
3260 }
3261
3262 #[cfg(debug_assertions)] {
3263 self.counterparty_commitment_txs_from_update(updates);
3264 }
3265
3266 self.latest_update_id = updates.update_id;
3267
3268 let mut is_pre_close_update = false;
3272 for update in updates.updates.iter() {
3273 match update {
3274 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { .. }
3275 |ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. }
3276 |ChannelMonitorUpdateStep::ShutdownScript { .. }
3277 |ChannelMonitorUpdateStep::CommitmentSecret { .. } =>
3278 is_pre_close_update = true,
3279 ChannelMonitorUpdateStep::PaymentPreimage { .. } => {},
3284 ChannelMonitorUpdateStep::ChannelForceClosed { .. } => {},
3285 }
3286 }
3287
3288 if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
3289 log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
3290 Err(())
3291 } else { ret }
3292 }
3293
3294 fn no_further_updates_allowed(&self) -> bool {
3295 self.funding_spend_seen || self.lockdown_from_offchain || self.holder_tx_signed
3296 }
3297
3298 fn get_latest_update_id(&self) -> u64 {
3299 self.latest_update_id
3300 }
3301
3302 fn get_funding_txo(&self) -> &(OutPoint, ScriptBuf) {
3303 &self.funding_info
3304 }
3305
3306 pub fn channel_id(&self) -> ChannelId {
3307 self.channel_id
3308 }
3309
3310 fn get_outputs_to_watch(&self) -> &HashMap<Txid, Vec<(u32, ScriptBuf)>> {
3311 for txid in self.counterparty_commitment_txn_on_chain.keys() {
3315 self.outputs_to_watch.get(txid).expect("Counterparty commitment txn which have been broadcast should have outputs registered");
3316 }
3317 &self.outputs_to_watch
3318 }
3319
3320 fn get_and_clear_pending_monitor_events(&mut self) -> Vec<MonitorEvent> {
3321 let mut ret = Vec::new();
3322 mem::swap(&mut ret, &mut self.pending_monitor_events);
3323 ret
3324 }
3325
3326 pub(super) fn get_repeated_events(&mut self) -> Vec<Event> {
3330 let pending_claim_events = self.onchain_tx_handler.get_and_clear_pending_claim_events();
3331 let mut ret = Vec::with_capacity(pending_claim_events.len());
3332 for (claim_id, claim_event) in pending_claim_events {
3333 match claim_event {
3334 ClaimEvent::BumpCommitment {
3335 package_target_feerate_sat_per_1000_weight, commitment_tx, anchor_output_idx,
3336 } => {
3337 let channel_id = self.channel_id;
3338 let counterparty_node_id = self.counterparty_node_id.unwrap();
3342 let commitment_txid = commitment_tx.compute_txid();
3343 debug_assert_eq!(self.current_holder_commitment_tx.txid, commitment_txid);
3344 let pending_htlcs = self.current_holder_commitment_tx.non_dust_htlcs();
3345 let commitment_tx_fee_satoshis = self.channel_value_satoshis -
3346 commitment_tx.output.iter().fold(0u64, |sum, output| sum + output.value.to_sat());
3347 ret.push(Event::BumpTransaction(BumpTransactionEvent::ChannelClose {
3348 channel_id,
3349 counterparty_node_id,
3350 claim_id,
3351 package_target_feerate_sat_per_1000_weight,
3352 commitment_tx,
3353 commitment_tx_fee_satoshis,
3354 anchor_descriptor: AnchorDescriptor {
3355 channel_derivation_parameters: ChannelDerivationParameters {
3356 keys_id: self.channel_keys_id,
3357 value_satoshis: self.channel_value_satoshis,
3358 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3359 },
3360 outpoint: BitcoinOutPoint {
3361 txid: commitment_txid,
3362 vout: anchor_output_idx,
3363 },
3364 },
3365 pending_htlcs,
3366 }));
3367 },
3368 ClaimEvent::BumpHTLC {
3369 target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
3370 } => {
3371 let channel_id = self.channel_id;
3372 let counterparty_node_id = self.counterparty_node_id.unwrap();
3376 let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
3377 for htlc in htlcs {
3378 htlc_descriptors.push(HTLCDescriptor {
3379 channel_derivation_parameters: ChannelDerivationParameters {
3380 keys_id: self.channel_keys_id,
3381 value_satoshis: self.channel_value_satoshis,
3382 transaction_parameters: self.onchain_tx_handler.channel_transaction_parameters.clone(),
3383 },
3384 commitment_txid: htlc.commitment_txid,
3385 per_commitment_number: htlc.per_commitment_number,
3386 per_commitment_point: htlc.per_commitment_point,
3387 feerate_per_kw: 0,
3388 htlc: htlc.htlc,
3389 preimage: htlc.preimage,
3390 counterparty_sig: htlc.counterparty_sig,
3391 });
3392 }
3393 ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
3394 channel_id,
3395 counterparty_node_id,
3396 claim_id,
3397 target_feerate_sat_per_1000_weight,
3398 htlc_descriptors,
3399 tx_lock_time,
3400 }));
3401 }
3402 }
3403 }
3404 ret
3405 }
3406
3407 fn initial_counterparty_commitment_tx(&mut self) -> Option<CommitmentTransaction> {
3408 let (their_per_commitment_point, feerate_per_kw, to_broadcaster_value,
3409 to_countersignatory_value) = self.initial_counterparty_commitment_info?;
3410 let htlc_outputs = vec![];
3411
3412 let commitment_tx = self.build_counterparty_commitment_tx(INITIAL_COMMITMENT_NUMBER,
3413 &their_per_commitment_point, to_broadcaster_value, to_countersignatory_value,
3414 feerate_per_kw, htlc_outputs);
3415 Some(commitment_tx)
3416 }
3417
3418 fn build_counterparty_commitment_tx(
3419 &self, commitment_number: u64, their_per_commitment_point: &PublicKey,
3420 to_broadcaster_value: u64, to_countersignatory_value: u64, feerate_per_kw: u32,
3421 mut nondust_htlcs: Vec<(HTLCOutputInCommitment, Option<Box<HTLCSource>>)>
3422 ) -> CommitmentTransaction {
3423 let broadcaster_keys = &self.onchain_tx_handler.channel_transaction_parameters
3424 .counterparty_parameters.as_ref().unwrap().pubkeys;
3425 let countersignatory_keys =
3426 &self.onchain_tx_handler.channel_transaction_parameters.holder_pubkeys;
3427
3428 let broadcaster_funding_key = broadcaster_keys.funding_pubkey;
3429 let countersignatory_funding_key = countersignatory_keys.funding_pubkey;
3430 let keys = TxCreationKeys::from_channel_static_keys(&their_per_commitment_point,
3431 &broadcaster_keys, &countersignatory_keys, &self.onchain_tx_handler.secp_ctx);
3432 let channel_parameters =
3433 &self.onchain_tx_handler.channel_transaction_parameters.as_counterparty_broadcastable();
3434
3435 CommitmentTransaction::new_with_auxiliary_htlc_data(commitment_number,
3436 to_broadcaster_value, to_countersignatory_value, broadcaster_funding_key,
3437 countersignatory_funding_key, keys, feerate_per_kw, &mut nondust_htlcs,
3438 channel_parameters)
3439 }
3440
3441 fn counterparty_commitment_txs_from_update(&self, update: &ChannelMonitorUpdate) -> Vec<CommitmentTransaction> {
3442 update.updates.iter().filter_map(|update| {
3443 match update {
3444 &ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { commitment_txid,
3445 ref htlc_outputs, commitment_number, their_per_commitment_point,
3446 feerate_per_kw: Some(feerate_per_kw),
3447 to_broadcaster_value_sat: Some(to_broadcaster_value),
3448 to_countersignatory_value_sat: Some(to_countersignatory_value) } => {
3449
3450 let nondust_htlcs = htlc_outputs.iter().filter_map(|(htlc, _)| {
3451 htlc.transaction_output_index.map(|_| (htlc.clone(), None))
3452 }).collect::<Vec<_>>();
3453
3454 let commitment_tx = self.build_counterparty_commitment_tx(commitment_number,
3455 &their_per_commitment_point, to_broadcaster_value,
3456 to_countersignatory_value, feerate_per_kw, nondust_htlcs);
3457
3458 debug_assert_eq!(commitment_tx.trust().txid(), commitment_txid);
3459
3460 Some(commitment_tx)
3461 },
3462 _ => None,
3463 }
3464 }).collect()
3465 }
3466
3467 fn sign_to_local_justice_tx(
3468 &self, mut justice_tx: Transaction, input_idx: usize, value: u64, commitment_number: u64
3469 ) -> Result<Transaction, ()> {
3470 let secret = self.get_secret(commitment_number).ok_or(())?;
3471 let per_commitment_key = SecretKey::from_slice(&secret).map_err(|_| ())?;
3472 let their_per_commitment_point = PublicKey::from_secret_key(
3473 &self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3474
3475 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3476 &self.holder_revocation_basepoint, &their_per_commitment_point);
3477 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx,
3478 &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &their_per_commitment_point);
3479 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3480 self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3481
3482 let sig = self.onchain_tx_handler.signer.sign_justice_revoked_output(
3483 &justice_tx, input_idx, value, &per_commitment_key, &self.onchain_tx_handler.secp_ctx)?;
3484 justice_tx.input[input_idx].witness.push_ecdsa_signature(&BitcoinSignature::sighash_all(sig));
3485 justice_tx.input[input_idx].witness.push(&[1u8]);
3486 justice_tx.input[input_idx].witness.push(revokeable_redeemscript.as_bytes());
3487 Ok(justice_tx)
3488 }
3489
3490 fn get_secret(&self, idx: u64) -> Option<[u8; 32]> {
3492 self.commitment_secrets.get_secret(idx)
3493 }
3494
3495 fn get_min_seen_secret(&self) -> u64 {
3496 self.commitment_secrets.get_min_seen_secret()
3497 }
3498
3499 fn get_cur_counterparty_commitment_number(&self) -> u64 {
3500 self.current_counterparty_commitment_number
3501 }
3502
3503 fn get_cur_holder_commitment_number(&self) -> u64 {
3504 self.current_holder_commitment_number
3505 }
3506
3507 fn check_spend_counterparty_transaction<L: Deref>(&mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &L)
3515 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo)
3516 where L::Target: Logger {
3517 let mut claimable_outpoints = Vec::new();
3520 let mut to_counterparty_output_info = None;
3521
3522 let commitment_txid = tx.compute_txid(); let per_commitment_option = self.counterparty_claimable_outpoints.get(&commitment_txid);
3524
3525 macro_rules! ignore_error {
3526 ( $thing : expr ) => {
3527 match $thing {
3528 Ok(a) => a,
3529 Err(_) => return (claimable_outpoints, to_counterparty_output_info)
3530 }
3531 };
3532 }
3533
3534 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);
3535 if commitment_number >= self.get_min_seen_secret() {
3536 let secret = self.get_secret(commitment_number).unwrap();
3537 let per_commitment_key = ignore_error!(SecretKey::from_slice(&secret));
3538 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3539 let revocation_pubkey = RevocationKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point,);
3540 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));
3541
3542 let revokeable_redeemscript = chan_utils::get_revokeable_redeemscript(&revocation_pubkey, self.counterparty_commitment_params.on_counterparty_tx_csv, &delayed_key);
3543 let revokeable_p2wsh = revokeable_redeemscript.to_p2wsh();
3544
3545 for (idx, outp) in tx.output.iter().enumerate() {
3547 if outp.script_pubkey == revokeable_p2wsh {
3548 let revk_outp = RevokedOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, outp.value, self.counterparty_commitment_params.on_counterparty_tx_csv, self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx(), height);
3549 let justice_package = PackageTemplate::build_package(
3550 commitment_txid, idx as u32,
3551 PackageSolvingData::RevokedOutput(revk_outp),
3552 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3553 );
3554 claimable_outpoints.push(justice_package);
3555 to_counterparty_output_info =
3556 Some((idx.try_into().expect("Txn can't have more than 2^32 outputs"), outp.value));
3557 }
3558 }
3559
3560 if let Some(per_commitment_claimable_data) = per_commitment_option {
3562 for (htlc, _) in per_commitment_claimable_data {
3563 if let Some(transaction_output_index) = htlc.transaction_output_index {
3564 if transaction_output_index as usize >= tx.output.len() ||
3565 tx.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3566 return (claimable_outpoints, to_counterparty_output_info);
3568 }
3569 let revk_htlc_outp = RevokedHTLCOutput::build(per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key, self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key, htlc.amount_msat / 1000, htlc.clone(), &self.onchain_tx_handler.channel_transaction_parameters.channel_type_features, height);
3570 let counterparty_spendable_height = if htlc.offered {
3571 htlc.cltv_expiry
3572 } else {
3573 height
3574 };
3575 let justice_package = PackageTemplate::build_package(
3576 commitment_txid,
3577 transaction_output_index,
3578 PackageSolvingData::RevokedHTLCOutput(revk_htlc_outp),
3579 counterparty_spendable_height,
3580 );
3581 claimable_outpoints.push(justice_package);
3582 }
3583 }
3584 }
3585
3586 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());
3590 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3591
3592 if let Some(per_commitment_claimable_data) = per_commitment_option {
3593 fail_unbroadcast_htlcs!(self, "revoked_counterparty", commitment_txid, tx, height,
3594 block_hash, per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3595 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3596 ), logger);
3597 } else {
3598 debug_assert!(cfg!(fuzzing), "We should have per-commitment option for any recognized old commitment txn");
3603 fail_unbroadcast_htlcs!(self, "revoked counterparty", commitment_txid, tx, height,
3604 block_hash, [].iter().map(|reference| *reference), logger);
3605 }
3606 }
3607 } else if let Some(per_commitment_claimable_data) = per_commitment_option {
3608 self.counterparty_commitment_txn_on_chain.insert(commitment_txid, commitment_number);
3616
3617 log_info!(logger, "Got broadcast of non-revoked counterparty commitment transaction {}", commitment_txid);
3618 fail_unbroadcast_htlcs!(self, "counterparty", commitment_txid, tx, height, block_hash,
3619 per_commitment_claimable_data.iter().map(|(htlc, htlc_source)|
3620 (htlc, htlc_source.as_ref().map(|htlc_source| htlc_source.as_ref()))
3621 ), logger);
3622 let (htlc_claim_reqs, counterparty_output_info) =
3623 self.get_counterparty_output_claim_info(commitment_number, commitment_txid, Some(tx), per_commitment_option, Some(height));
3624 to_counterparty_output_info = counterparty_output_info;
3625 for req in htlc_claim_reqs {
3626 claimable_outpoints.push(req);
3627 }
3628
3629 }
3630 (claimable_outpoints, to_counterparty_output_info)
3631 }
3632
3633 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>>)>>, confirmation_height: Option<u32>)
3635 -> (Vec<PackageTemplate>, CommitmentTxCounterpartyOutputInfo) {
3636 let mut claimable_outpoints = Vec::new();
3637 let mut to_counterparty_output_info: CommitmentTxCounterpartyOutputInfo = None;
3638
3639 let per_commitment_claimable_data = match per_commitment_option {
3640 Some(outputs) => outputs,
3641 None => return (claimable_outpoints, to_counterparty_output_info),
3642 };
3643 let per_commitment_points = match self.their_cur_per_commitment_points {
3644 Some(points) => points,
3645 None => return (claimable_outpoints, to_counterparty_output_info),
3646 };
3647
3648 let per_commitment_point =
3649 if per_commitment_points.0 == commitment_number { &per_commitment_points.1 }
3652 else if let Some(point) = per_commitment_points.2.as_ref() {
3653 if per_commitment_points.0 == commitment_number + 1 {
3657 point
3658 } else { return (claimable_outpoints, to_counterparty_output_info); }
3659 } else { return (claimable_outpoints, to_counterparty_output_info); };
3660
3661 if let Some(transaction) = tx {
3662 let revocation_pubkey = RevocationKey::from_basepoint(
3663 &self.onchain_tx_handler.secp_ctx, &self.holder_revocation_basepoint, &per_commitment_point);
3664
3665 let delayed_key = DelayedPaymentKey::from_basepoint(&self.onchain_tx_handler.secp_ctx, &self.counterparty_commitment_params.counterparty_delayed_payment_base_key, &per_commitment_point);
3666
3667 let revokeable_p2wsh = chan_utils::get_revokeable_redeemscript(&revocation_pubkey,
3668 self.counterparty_commitment_params.on_counterparty_tx_csv,
3669 &delayed_key).to_p2wsh();
3670 for (idx, outp) in transaction.output.iter().enumerate() {
3671 if outp.script_pubkey == revokeable_p2wsh {
3672 to_counterparty_output_info =
3673 Some((idx.try_into().expect("Can't have > 2^32 outputs"), outp.value));
3674 }
3675 }
3676 }
3677
3678 for &(ref htlc, _) in per_commitment_claimable_data.iter() {
3679 if let Some(transaction_output_index) = htlc.transaction_output_index {
3680 if let Some(transaction) = tx {
3681 if transaction_output_index as usize >= transaction.output.len() ||
3682 transaction.output[transaction_output_index as usize].value != htlc.to_bitcoin_amount() {
3683 return (claimable_outpoints, to_counterparty_output_info);
3685 }
3686 }
3687 let preimage = if htlc.offered { if let Some((p, _)) = self.payment_preimages.get(&htlc.payment_hash) { Some(*p) } else { None } } else { None };
3688 if preimage.is_some() || !htlc.offered {
3689 let counterparty_htlc_outp = if htlc.offered {
3690 PackageSolvingData::CounterpartyOfferedHTLCOutput(
3691 CounterpartyOfferedHTLCOutput::build(*per_commitment_point,
3692 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3693 self.counterparty_commitment_params.counterparty_htlc_base_key,
3694 preimage.unwrap(), htlc.clone(), self.onchain_tx_handler.channel_type_features().clone(),
3695 confirmation_height))
3696 } else {
3697 PackageSolvingData::CounterpartyReceivedHTLCOutput(
3698 CounterpartyReceivedHTLCOutput::build(*per_commitment_point,
3699 self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3700 self.counterparty_commitment_params.counterparty_htlc_base_key,
3701 htlc.clone(), self.onchain_tx_handler.channel_type_features().clone(),
3702 confirmation_height))
3703 };
3704 let counterparty_package = PackageTemplate::build_package(commitment_txid, transaction_output_index, counterparty_htlc_outp, htlc.cltv_expiry);
3705 claimable_outpoints.push(counterparty_package);
3706 }
3707 }
3708 }
3709
3710 (claimable_outpoints, to_counterparty_output_info)
3711 }
3712
3713 fn check_spend_counterparty_htlc<L: Deref>(
3715 &mut self, tx: &Transaction, commitment_number: u64, commitment_txid: &Txid, height: u32, logger: &L
3716 ) -> (Vec<PackageTemplate>, Option<TransactionOutputs>) where L::Target: Logger {
3717 let secret = if let Some(secret) = self.get_secret(commitment_number) { secret } else { return (Vec::new(), None); };
3718 let per_commitment_key = match SecretKey::from_slice(&secret) {
3719 Ok(key) => key,
3720 Err(_) => return (Vec::new(), None)
3721 };
3722 let per_commitment_point = PublicKey::from_secret_key(&self.onchain_tx_handler.secp_ctx, &per_commitment_key);
3723
3724 let htlc_txid = tx.compute_txid();
3725 let mut claimable_outpoints = vec![];
3726 let mut outputs_to_watch = None;
3727 for (idx, input) in tx.input.iter().enumerate() {
3738 if input.previous_output.txid == *commitment_txid && input.witness.len() == 5 && tx.output.get(idx).is_some() {
3739 log_error!(logger, "Got broadcast of revoked counterparty HTLC transaction, spending {}:{}", htlc_txid, idx);
3740 let revk_outp = RevokedOutput::build(
3741 per_commitment_point, self.counterparty_commitment_params.counterparty_delayed_payment_base_key,
3742 self.counterparty_commitment_params.counterparty_htlc_base_key, per_commitment_key,
3743 tx.output[idx].value, self.counterparty_commitment_params.on_counterparty_tx_csv,
3744 false, height,
3745 );
3746 let justice_package = PackageTemplate::build_package(
3747 htlc_txid, idx as u32, PackageSolvingData::RevokedOutput(revk_outp),
3748 height + self.counterparty_commitment_params.on_counterparty_tx_csv as u32,
3749 );
3750 claimable_outpoints.push(justice_package);
3751 if outputs_to_watch.is_none() {
3752 outputs_to_watch = Some((htlc_txid, vec![]));
3753 }
3754 outputs_to_watch.as_mut().unwrap().1.push((idx as u32, tx.output[idx].clone()));
3755 }
3756 }
3757 (claimable_outpoints, outputs_to_watch)
3758 }
3759
3760 fn get_broadcasted_holder_claims(&self, holder_tx: &HolderSignedTx, conf_height: u32) -> (Vec<PackageTemplate>, Option<(ScriptBuf, PublicKey, RevocationKey)>) {
3764 let mut claim_requests = Vec::with_capacity(holder_tx.htlc_outputs.len());
3765
3766 let redeemscript = chan_utils::get_revokeable_redeemscript(&holder_tx.revocation_key, self.on_holder_tx_csv, &holder_tx.delayed_payment_key);
3767 let broadcasted_holder_revokable_script = Some((redeemscript.to_p2wsh(), holder_tx.per_commitment_point.clone(), holder_tx.revocation_key.clone()));
3768
3769 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3770 if let Some(transaction_output_index) = htlc.transaction_output_index {
3771 let (htlc_output, counterparty_spendable_height) = if htlc.offered {
3772 let htlc_output = HolderHTLCOutput::build_offered(
3773 htlc.amount_msat, htlc.cltv_expiry, self.onchain_tx_handler.channel_type_features().clone(), conf_height
3774 );
3775 (htlc_output, conf_height)
3776 } else {
3777 let payment_preimage = if let Some((preimage, _)) = self.payment_preimages.get(&htlc.payment_hash) {
3778 preimage.clone()
3779 } else {
3780 continue;
3782 };
3783 let htlc_output = HolderHTLCOutput::build_accepted(
3784 payment_preimage, htlc.amount_msat, self.onchain_tx_handler.channel_type_features().clone(), conf_height
3785 );
3786 (htlc_output, htlc.cltv_expiry)
3787 };
3788 let htlc_package = PackageTemplate::build_package(
3789 holder_tx.txid, transaction_output_index,
3790 PackageSolvingData::HolderHTLCOutput(htlc_output),
3791 counterparty_spendable_height,
3792 );
3793 claim_requests.push(htlc_package);
3794 }
3795 }
3796
3797 (claim_requests, broadcasted_holder_revokable_script)
3798 }
3799
3800 fn get_broadcasted_holder_watch_outputs(&self, holder_tx: &HolderSignedTx, commitment_tx: &Transaction) -> Vec<(u32, TxOut)> {
3802 let mut watch_outputs = Vec::with_capacity(holder_tx.htlc_outputs.len());
3803 for &(ref htlc, _, _) in holder_tx.htlc_outputs.iter() {
3804 if let Some(transaction_output_index) = htlc.transaction_output_index {
3805 watch_outputs.push((transaction_output_index, commitment_tx.output[transaction_output_index as usize].clone()));
3806 }
3807 }
3808 watch_outputs
3809 }
3810
3811 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 {
3816 let commitment_txid = tx.compute_txid();
3817 let mut claim_requests = Vec::new();
3818 let mut watch_outputs = Vec::new();
3819
3820 macro_rules! append_onchain_update {
3821 ($updates: expr, $to_watch: expr) => {
3822 claim_requests = $updates.0;
3823 self.broadcasted_holder_revokable_script = $updates.1;
3824 watch_outputs.append(&mut $to_watch);
3825 }
3826 }
3827
3828 let mut is_holder_tx = false;
3830
3831 if self.current_holder_commitment_tx.txid == commitment_txid {
3832 is_holder_tx = true;
3833 log_info!(logger, "Got broadcast of latest holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3834 let res = self.get_broadcasted_holder_claims(&self.current_holder_commitment_tx, height);
3835 let mut to_watch = self.get_broadcasted_holder_watch_outputs(&self.current_holder_commitment_tx, tx);
3836 append_onchain_update!(res, to_watch);
3837 fail_unbroadcast_htlcs!(self, "latest holder", commitment_txid, tx, height,
3838 block_hash, self.current_holder_commitment_tx.htlc_outputs.iter()
3839 .map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())), logger);
3840 } else if let &Some(ref holder_tx) = &self.prev_holder_signed_commitment_tx {
3841 if holder_tx.txid == commitment_txid {
3842 is_holder_tx = true;
3843 log_info!(logger, "Got broadcast of previous holder commitment tx {}, searching for available HTLCs to claim", commitment_txid);
3844 let res = self.get_broadcasted_holder_claims(holder_tx, height);
3845 let mut to_watch = self.get_broadcasted_holder_watch_outputs(holder_tx, tx);
3846 append_onchain_update!(res, to_watch);
3847 fail_unbroadcast_htlcs!(self, "previous holder", commitment_txid, tx, height, block_hash,
3848 holder_tx.htlc_outputs.iter().map(|(htlc, _, htlc_source)| (htlc, htlc_source.as_ref())),
3849 logger);
3850 }
3851 }
3852
3853 if is_holder_tx {
3854 Some((claim_requests, (commitment_txid, watch_outputs)))
3855 } else {
3856 None
3857 }
3858 }
3859
3860 pub fn cancel_prev_commitment_claims<L: Deref>(
3863 &mut self, logger: &L, confirmed_commitment_txid: &Txid
3864 ) where L::Target: Logger {
3865 for (counterparty_commitment_txid, _) in &self.counterparty_commitment_txn_on_chain {
3866 if counterparty_commitment_txid == confirmed_commitment_txid {
3868 continue;
3869 }
3870 for (htlc, _) in self.counterparty_claimable_outpoints.get(counterparty_commitment_txid).unwrap_or(&vec![]) {
3873 log_trace!(logger, "Canceling claims for previously confirmed counterparty commitment {}",
3874 counterparty_commitment_txid);
3875 let mut outpoint = BitcoinOutPoint { txid: *counterparty_commitment_txid, vout: 0 };
3876 if let Some(vout) = htlc.transaction_output_index {
3877 outpoint.vout = vout;
3878 self.onchain_tx_handler.abandon_claim(&outpoint);
3879 }
3880 }
3881 }
3882 if self.current_holder_commitment_tx.txid != *confirmed_commitment_txid {
3886 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3887 self.current_holder_commitment_tx.txid);
3888 let mut outpoint = BitcoinOutPoint { txid: self.current_holder_commitment_tx.txid, vout: 0 };
3889 for (htlc, _, _) in &self.current_holder_commitment_tx.htlc_outputs {
3890 if let Some(vout) = htlc.transaction_output_index {
3891 outpoint.vout = vout;
3892 self.onchain_tx_handler.abandon_claim(&outpoint);
3893 }
3894 }
3895 }
3896 if let Some(prev_holder_commitment_tx) = &self.prev_holder_signed_commitment_tx {
3897 if prev_holder_commitment_tx.txid != *confirmed_commitment_txid {
3898 log_trace!(logger, "Canceling claims for previously broadcast holder commitment {}",
3899 prev_holder_commitment_tx.txid);
3900 let mut outpoint = BitcoinOutPoint { txid: prev_holder_commitment_tx.txid, vout: 0 };
3901 for (htlc, _, _) in &prev_holder_commitment_tx.htlc_outputs {
3902 if let Some(vout) = htlc.transaction_output_index {
3903 outpoint.vout = vout;
3904 self.onchain_tx_handler.abandon_claim(&outpoint);
3905 }
3906 }
3907 }
3908 }
3909 }
3910
3911 #[cfg(any(test,feature = "unsafe_revoked_tx_signing"))]
3912 fn unsafe_get_latest_holder_commitment_txn<L: Deref>(
3914 &mut self, logger: &WithChannelMonitor<L>
3915 ) -> Vec<Transaction> where L::Target: Logger {
3916 log_debug!(logger, "Getting signed copy of latest holder commitment transaction!");
3917 let commitment_tx = self.onchain_tx_handler.get_fully_signed_copy_holder_tx(&self.funding_redeemscript);
3918 let txid = commitment_tx.compute_txid();
3919 let mut holder_transactions = vec![commitment_tx];
3920 if self.onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() {
3923 return holder_transactions;
3924 }
3925 for htlc in self.current_holder_commitment_tx.htlc_outputs.iter() {
3926 if let Some(vout) = htlc.0.transaction_output_index {
3927 let preimage = if !htlc.0.offered {
3928 if let Some((preimage, _)) = self.payment_preimages.get(&htlc.0.payment_hash) { Some(preimage.clone()) } else {
3929 continue;
3931 }
3932 } else { None };
3933 if let Some(htlc_tx) = self.onchain_tx_handler.get_maybe_signed_htlc_tx(
3934 &::bitcoin::OutPoint { txid, vout }, &preimage
3935 ) {
3936 if htlc_tx.is_fully_signed() {
3937 holder_transactions.push(htlc_tx.0);
3938 }
3939 }
3940 }
3941 }
3942 holder_transactions
3943 }
3944
3945 fn block_connected<B: Deref, F: Deref, L: Deref>(
3946 &mut self, header: &Header, txdata: &TransactionData, height: u32, broadcaster: B,
3947 fee_estimator: F, logger: &WithChannelMonitor<L>,
3948 ) -> Vec<TransactionOutputs>
3949 where B::Target: BroadcasterInterface,
3950 F::Target: FeeEstimator,
3951 L::Target: Logger,
3952 {
3953 let block_hash = header.block_hash();
3954 self.best_block = BestBlock::new(block_hash, height);
3955
3956 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
3957 self.transactions_confirmed(header, txdata, height, broadcaster, &bounded_fee_estimator, logger)
3958 }
3959
3960 fn best_block_updated<B: Deref, F: Deref, L: Deref>(
3961 &mut self,
3962 header: &Header,
3963 height: u32,
3964 broadcaster: B,
3965 fee_estimator: &LowerBoundedFeeEstimator<F>,
3966 logger: &WithChannelMonitor<L>,
3967 ) -> Vec<TransactionOutputs>
3968 where
3969 B::Target: BroadcasterInterface,
3970 F::Target: FeeEstimator,
3971 L::Target: Logger,
3972 {
3973 let block_hash = header.block_hash();
3974
3975 if height > self.best_block.height {
3976 self.best_block = BestBlock::new(block_hash, height);
3977 log_trace!(logger, "Connecting new block {} at height {}", block_hash, height);
3978 self.block_confirmed(height, block_hash, vec![], vec![], vec![], &broadcaster, &fee_estimator, logger)
3979 } else if block_hash != self.best_block.block_hash {
3980 self.best_block = BestBlock::new(block_hash, height);
3981 log_trace!(logger, "Best block re-orged, replaced with new block {} at height {}", block_hash, height);
3982 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height <= height);
3983 let conf_target = self.closure_conf_target();
3984 self.onchain_tx_handler.block_disconnected(height + 1, broadcaster, conf_target, fee_estimator, logger);
3985 Vec::new()
3986 } else { Vec::new() }
3987 }
3988
3989 fn transactions_confirmed<B: Deref, F: Deref, L: Deref>(
3990 &mut self,
3991 header: &Header,
3992 txdata: &TransactionData,
3993 height: u32,
3994 broadcaster: B,
3995 fee_estimator: &LowerBoundedFeeEstimator<F>,
3996 logger: &WithChannelMonitor<L>,
3997 ) -> Vec<TransactionOutputs>
3998 where
3999 B::Target: BroadcasterInterface,
4000 F::Target: FeeEstimator,
4001 L::Target: Logger,
4002 {
4003 let txn_matched = self.filter_block(txdata);
4004 for tx in &txn_matched {
4005 let mut output_val = Amount::ZERO;
4006 for out in tx.output.iter() {
4007 if out.value > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4008 output_val += out.value;
4009 if output_val > Amount::MAX_MONEY { panic!("Value-overflowing transaction provided to block connected"); }
4010 }
4011 }
4012
4013 let block_hash = header.block_hash();
4014
4015 let mut watch_outputs = Vec::new();
4016 let mut claimable_outpoints = Vec::new();
4017 'tx_iter: for tx in &txn_matched {
4018 let txid = tx.compute_txid();
4019 log_trace!(logger, "Transaction {} confirmed in block {}", txid , block_hash);
4020 if Some(txid) == self.funding_spend_confirmed {
4022 log_debug!(logger, "Skipping redundant processing of funding-spend tx {} as it was previously confirmed", txid);
4023 continue 'tx_iter;
4024 }
4025 for ev in self.onchain_events_awaiting_threshold_conf.iter() {
4026 if ev.txid == txid {
4027 if let Some(conf_hash) = ev.block_hash {
4028 assert_eq!(header.block_hash(), conf_hash,
4029 "Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
4030 This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
4031 }
4032 log_debug!(logger, "Skipping redundant processing of confirming tx {} as it was previously confirmed", txid);
4033 continue 'tx_iter;
4034 }
4035 }
4036 for htlc in self.htlcs_resolved_on_chain.iter() {
4037 if Some(txid) == htlc.resolving_txid {
4038 log_debug!(logger, "Skipping redundant processing of HTLC resolution tx {} as it was previously confirmed", txid);
4039 continue 'tx_iter;
4040 }
4041 }
4042 for spendable_txid in self.spendable_txids_confirmed.iter() {
4043 if txid == *spendable_txid {
4044 log_debug!(logger, "Skipping redundant processing of spendable tx {} as it was previously confirmed", txid);
4045 continue 'tx_iter;
4046 }
4047 }
4048
4049 if tx.input.len() == 1 {
4050 let prevout = &tx.input[0].previous_output;
4055 if prevout.txid == self.funding_info.0.txid && prevout.vout == self.funding_info.0.index as u32 {
4056 let mut balance_spendable_csv = None;
4057 log_info!(logger, "Channel {} closed by funding output spend in txid {}.",
4058 &self.channel_id(), txid);
4059 self.funding_spend_seen = true;
4060 let mut commitment_tx_to_counterparty_output = None;
4061 if (tx.input[0].sequence.0 >> 8*3) as u8 == 0x80 && (tx.lock_time.to_consensus_u32() >> 8*3) as u8 == 0x20 {
4062 if let Some((mut new_outpoints, new_outputs)) = self.check_spend_holder_transaction(&tx, height, &block_hash, &logger) {
4063 if !new_outputs.1.is_empty() {
4064 watch_outputs.push(new_outputs);
4065 }
4066
4067 claimable_outpoints.append(&mut new_outpoints);
4068 balance_spendable_csv = Some(self.on_holder_tx_csv);
4069 } else {
4070 let mut new_watch_outputs = Vec::new();
4071 for (idx, outp) in tx.output.iter().enumerate() {
4072 new_watch_outputs.push((idx as u32, outp.clone()));
4073 }
4074 watch_outputs.push((txid, new_watch_outputs));
4075
4076 let (mut new_outpoints, counterparty_output_idx_sats) =
4077 self.check_spend_counterparty_transaction(&tx, height, &block_hash, &logger);
4078 commitment_tx_to_counterparty_output = counterparty_output_idx_sats;
4079
4080 claimable_outpoints.append(&mut new_outpoints);
4081 }
4082 }
4083 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4084 txid,
4085 transaction: Some((*tx).clone()),
4086 height,
4087 block_hash: Some(block_hash),
4088 event: OnchainEvent::FundingSpendConfirmation {
4089 on_local_output_csv: balance_spendable_csv,
4090 commitment_tx_to_counterparty_output,
4091 },
4092 });
4093 self.cancel_prev_commitment_claims(&logger, &txid);
4097 }
4098 }
4099 if tx.input.len() >= 1 {
4100 for tx_input in &tx.input {
4104 let commitment_txid = tx_input.previous_output.txid;
4105 if let Some(&commitment_number) = self.counterparty_commitment_txn_on_chain.get(&commitment_txid) {
4106 let (mut new_outpoints, new_outputs_option) = self.check_spend_counterparty_htlc(
4107 &tx, commitment_number, &commitment_txid, height, &logger
4108 );
4109 claimable_outpoints.append(&mut new_outpoints);
4110 if let Some(new_outputs) = new_outputs_option {
4111 watch_outputs.push(new_outputs);
4112 }
4113 break;
4118 }
4119 }
4120 self.is_resolving_htlc_output(&tx, height, &block_hash, logger);
4121
4122 self.check_tx_and_push_spendable_outputs(&tx, height, &block_hash, logger);
4123 }
4124 }
4125
4126 if height > self.best_block.height {
4127 self.best_block = BestBlock::new(block_hash, height);
4128 }
4129
4130 self.block_confirmed(height, block_hash, txn_matched, watch_outputs, claimable_outpoints, &broadcaster, &fee_estimator, logger)
4131 }
4132
4133 fn block_confirmed<B: Deref, F: Deref, L: Deref>(
4142 &mut self,
4143 conf_height: u32,
4144 conf_hash: BlockHash,
4145 txn_matched: Vec<&Transaction>,
4146 mut watch_outputs: Vec<TransactionOutputs>,
4147 mut claimable_outpoints: Vec<PackageTemplate>,
4148 broadcaster: &B,
4149 fee_estimator: &LowerBoundedFeeEstimator<F>,
4150 logger: &WithChannelMonitor<L>,
4151 ) -> Vec<TransactionOutputs>
4152 where
4153 B::Target: BroadcasterInterface,
4154 F::Target: FeeEstimator,
4155 L::Target: Logger,
4156 {
4157 log_trace!(logger, "Processing {} matched transactions for block at height {}.", txn_matched.len(), conf_height);
4158 debug_assert!(self.best_block.height >= conf_height);
4159
4160 let should_broadcast = self.should_broadcast_holder_commitment_txn(logger);
4161 if should_broadcast {
4162 let (mut new_outpoints, mut new_outputs) = self.generate_claimable_outpoints_and_watch_outputs(ClosureReason::HTLCsTimedOut);
4163 claimable_outpoints.append(&mut new_outpoints);
4164 watch_outputs.append(&mut new_outputs);
4165 }
4166
4167 let (onchain_events_reaching_threshold_conf, onchain_events_awaiting_threshold_conf): (Vec<_>, Vec<_>) =
4169 self.onchain_events_awaiting_threshold_conf.drain(..).partition(
4170 |entry| entry.has_reached_confirmation_threshold(&self.best_block));
4171 self.onchain_events_awaiting_threshold_conf = onchain_events_awaiting_threshold_conf;
4172
4173 #[cfg(debug_assertions)]
4175 let unmatured_htlcs: Vec<_> = self.onchain_events_awaiting_threshold_conf
4176 .iter()
4177 .filter_map(|entry| match &entry.event {
4178 OnchainEvent::HTLCUpdate { source, .. } => Some(source),
4179 _ => None,
4180 })
4181 .collect();
4182 #[cfg(debug_assertions)]
4183 let mut matured_htlcs = Vec::new();
4184
4185 for entry in onchain_events_reaching_threshold_conf {
4187 match entry.event {
4188 OnchainEvent::HTLCUpdate { source, payment_hash, htlc_value_satoshis, commitment_tx_output_idx } => {
4189 #[cfg(debug_assertions)]
4191 {
4192 debug_assert!(
4193 !unmatured_htlcs.contains(&&source),
4194 "An unmature 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 debug_assert!(
4198 !matured_htlcs.contains(&source),
4199 "A matured HTLC transaction conflicts with a maturing one; failed to \
4200 call either transaction_unconfirmed for the conflicting transaction \
4201 or block_disconnected for a block containing it.");
4202 matured_htlcs.push(source.clone());
4203 }
4204
4205 log_debug!(logger, "HTLC {} failure update in {} has got enough confirmations to be passed upstream",
4206 &payment_hash, entry.txid);
4207 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4208 payment_hash,
4209 payment_preimage: None,
4210 source,
4211 htlc_value_satoshis,
4212 }));
4213 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4214 commitment_tx_output_idx,
4215 resolving_txid: Some(entry.txid),
4216 resolving_tx: entry.transaction,
4217 payment_preimage: None,
4218 });
4219 },
4220 OnchainEvent::MaturingOutput { descriptor } => {
4221 log_debug!(logger, "Descriptor {} has got enough confirmations to be passed upstream", log_spendable!(descriptor));
4222 self.pending_events.push(Event::SpendableOutputs {
4223 outputs: vec![descriptor],
4224 channel_id: Some(self.channel_id()),
4225 });
4226 self.spendable_txids_confirmed.push(entry.txid);
4227 },
4228 OnchainEvent::HTLCSpendConfirmation { commitment_tx_output_idx, preimage, .. } => {
4229 self.htlcs_resolved_on_chain.push(IrrevocablyResolvedHTLC {
4230 commitment_tx_output_idx: Some(commitment_tx_output_idx),
4231 resolving_txid: Some(entry.txid),
4232 resolving_tx: entry.transaction,
4233 payment_preimage: preimage,
4234 });
4235 },
4236 OnchainEvent::FundingSpendConfirmation { commitment_tx_to_counterparty_output, .. } => {
4237 self.funding_spend_confirmed = Some(entry.txid);
4238 self.confirmed_commitment_tx_counterparty_output = commitment_tx_to_counterparty_output;
4239 },
4240 }
4241 }
4242
4243 if self.no_further_updates_allowed() {
4244 let current_holder_htlcs = self.current_holder_commitment_tx.htlc_outputs.iter()
4251 .map(|&(ref a, _, ref b)| (a, b.as_ref()));
4252
4253 let current_counterparty_htlcs = if let Some(txid) = self.current_counterparty_commitment_txid {
4254 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4255 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4256 } else { None }
4257 } else { None }.into_iter().flatten();
4258
4259 let prev_counterparty_htlcs = if let Some(txid) = self.prev_counterparty_commitment_txid {
4260 if let Some(htlc_outputs) = self.counterparty_claimable_outpoints.get(&txid) {
4261 Some(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))))
4262 } else { None }
4263 } else { None }.into_iter().flatten();
4264
4265 let htlcs = current_holder_htlcs
4266 .chain(current_counterparty_htlcs)
4267 .chain(prev_counterparty_htlcs);
4268
4269 let height = self.best_block.height;
4270 for (htlc, source_opt) in htlcs {
4271 let source = match source_opt {
4273 Some(source) => source,
4274 None => continue,
4275 };
4276 let inbound_htlc_expiry = match source.inbound_htlc_expiry() {
4277 Some(cltv_expiry) => cltv_expiry,
4278 None => continue,
4279 };
4280 let max_expiry_height = height.saturating_add(LATENCY_GRACE_PERIOD_BLOCKS);
4281 if inbound_htlc_expiry > max_expiry_height {
4282 continue;
4283 }
4284 let duplicate_event = self.pending_monitor_events.iter().any(
4285 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4286 upd.source == *source
4287 } else { false });
4288 if duplicate_event {
4289 continue;
4290 }
4291 if !self.failed_back_htlc_ids.insert(SentHTLCId::from_source(source)) {
4292 continue;
4293 }
4294 if !duplicate_event {
4295 log_error!(logger, "Failing back HTLC {} upstream to preserve the \
4296 channel as the forward HTLC hasn't resolved and our backward HTLC \
4297 expires soon at {}", log_bytes!(htlc.payment_hash.0), inbound_htlc_expiry);
4298 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4299 source: source.clone(),
4300 payment_preimage: None,
4301 payment_hash: htlc.payment_hash,
4302 htlc_value_satoshis: Some(htlc.amount_msat / 1000),
4303 }));
4304 }
4305 }
4306 }
4307
4308 let conf_target = self.closure_conf_target();
4309 self.onchain_tx_handler.update_claims_view_from_requests(claimable_outpoints, conf_height, self.best_block.height, broadcaster, conf_target, fee_estimator, logger);
4310 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);
4311
4312 watch_outputs.retain(|&(ref txid, ref txouts)| {
4315 let idx_and_scripts = txouts.iter().map(|o| (o.0, o.1.script_pubkey.clone())).collect();
4316 self.outputs_to_watch.insert(txid.clone(), idx_and_scripts).is_none()
4317 });
4318 #[cfg(test)]
4319 {
4320 for tx in &txn_matched {
4324 if let Some(outputs) = self.get_outputs_to_watch().get(&tx.compute_txid()) {
4325 for idx_and_script in outputs.iter() {
4326 assert!((idx_and_script.0 as usize) < tx.output.len());
4327 assert_eq!(tx.output[idx_and_script.0 as usize].script_pubkey, idx_and_script.1);
4328 }
4329 }
4330 }
4331 }
4332 watch_outputs
4333 }
4334
4335 fn block_disconnected<B: Deref, F: Deref, L: Deref>(
4336 &mut self, header: &Header, height: u32, broadcaster: B, fee_estimator: F, logger: &WithChannelMonitor<L>
4337 ) where B::Target: BroadcasterInterface,
4338 F::Target: FeeEstimator,
4339 L::Target: Logger,
4340 {
4341 log_trace!(logger, "Block {} at height {} disconnected", header.block_hash(), height);
4342
4343 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| entry.height < height);
4347
4348 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(fee_estimator);
4349 let conf_target = self.closure_conf_target();
4350 self.onchain_tx_handler.block_disconnected(height, broadcaster, conf_target, &bounded_fee_estimator, logger);
4351
4352 self.best_block = BestBlock::new(header.prev_blockhash, height - 1);
4353 }
4354
4355 fn transaction_unconfirmed<B: Deref, F: Deref, L: Deref>(
4356 &mut self,
4357 txid: &Txid,
4358 broadcaster: B,
4359 fee_estimator: &LowerBoundedFeeEstimator<F>,
4360 logger: &WithChannelMonitor<L>,
4361 ) where
4362 B::Target: BroadcasterInterface,
4363 F::Target: FeeEstimator,
4364 L::Target: Logger,
4365 {
4366 let mut removed_height = None;
4367 for entry in self.onchain_events_awaiting_threshold_conf.iter() {
4368 if entry.txid == *txid {
4369 removed_height = Some(entry.height);
4370 break;
4371 }
4372 }
4373
4374 if let Some(removed_height) = removed_height {
4375 log_info!(logger, "transaction_unconfirmed of txid {} implies height {} was reorg'd out", txid, removed_height);
4376 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| if entry.height >= removed_height {
4377 log_info!(logger, "Transaction {} reorg'd out", entry.txid);
4378 false
4379 } else { true });
4380 }
4381
4382 debug_assert!(!self.onchain_events_awaiting_threshold_conf.iter().any(|ref entry| entry.txid == *txid));
4383
4384 let conf_target = self.closure_conf_target();
4385 self.onchain_tx_handler.transaction_unconfirmed(txid, broadcaster, conf_target, fee_estimator, logger);
4386 }
4387
4388 fn filter_block<'a>(&self, txdata: &TransactionData<'a>) -> Vec<&'a Transaction> {
4391 let mut matched_txn = new_hash_set();
4392 txdata.iter().filter(|&&(_, tx)| {
4393 let mut matches = self.spends_watched_output(tx);
4394 for input in tx.input.iter() {
4395 if matches { break; }
4396 if matched_txn.contains(&input.previous_output.txid) {
4397 matches = true;
4398 }
4399 }
4400 if matches {
4401 matched_txn.insert(tx.compute_txid());
4402 }
4403 matches
4404 }).map(|(_, tx)| *tx).collect()
4405 }
4406
4407 fn spends_watched_output(&self, tx: &Transaction) -> bool {
4409 for input in tx.input.iter() {
4410 if let Some(outputs) = self.get_outputs_to_watch().get(&input.previous_output.txid) {
4411 for (idx, _script_pubkey) in outputs.iter() {
4412 if *idx == input.previous_output.vout {
4413 #[cfg(test)]
4414 {
4415 if _script_pubkey.is_p2wsh() {
4419 if input.witness.last().unwrap().to_vec() == deliberately_bogus_accepted_htlc_witness_program() {
4420 return true;
4424 }
4425
4426 assert_eq!(&bitcoin::Address::p2wsh(&ScriptBuf::from(input.witness.last().unwrap().to_vec()), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4427 } else if _script_pubkey.is_p2wpkh() {
4428 assert_eq!(&bitcoin::Address::p2wpkh(&bitcoin::CompressedPublicKey(bitcoin::PublicKey::from_slice(&input.witness.last().unwrap()).unwrap().inner), bitcoin::Network::Bitcoin).script_pubkey(), _script_pubkey);
4429 } else { panic!(); }
4430 }
4431 return true;
4432 }
4433 }
4434 }
4435 }
4436
4437 false
4438 }
4439
4440 fn should_broadcast_holder_commitment_txn<L: Deref>(
4441 &self, logger: &WithChannelMonitor<L>
4442 ) -> bool where L::Target: Logger {
4443 if self.funding_spend_confirmed.is_some() ||
4446 self.onchain_events_awaiting_threshold_conf.iter().find(|event| match event.event {
4447 OnchainEvent::FundingSpendConfirmation { .. } => true,
4448 _ => false,
4449 }).is_some()
4450 {
4451 return false;
4452 }
4453 let height = self.best_block.height;
4464 macro_rules! scan_commitment {
4465 ($htlcs: expr, $holder_tx: expr) => {
4466 for ref htlc in $htlcs {
4467 let htlc_outbound = $holder_tx == htlc.offered;
4491 if ( htlc_outbound && htlc.cltv_expiry + LATENCY_GRACE_PERIOD_BLOCKS <= height) ||
4492 (!htlc_outbound && htlc.cltv_expiry <= height + CLTV_CLAIM_BUFFER && self.payment_preimages.contains_key(&htlc.payment_hash)) {
4493 log_info!(logger, "Force-closing channel due to {} HTLC timeout, HTLC expiry is {}", if htlc_outbound { "outbound" } else { "inbound "}, htlc.cltv_expiry);
4494 return true;
4495 }
4496 }
4497 }
4498 }
4499
4500 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, _)| a), true);
4501
4502 if let Some(ref txid) = self.current_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 if let Some(ref txid) = self.prev_counterparty_commitment_txid {
4508 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(txid) {
4509 scan_commitment!(htlc_outputs.iter().map(|&(ref a, _)| a), false);
4510 }
4511 }
4512
4513 false
4514 }
4515
4516 fn is_resolving_htlc_output<L: Deref>(
4519 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4520 ) where L::Target: Logger {
4521 'outer_loop: for input in &tx.input {
4522 let mut payment_data = None;
4523 let htlc_claim = HTLCClaim::from_witness(&input.witness);
4524 let revocation_sig_claim = htlc_claim == Some(HTLCClaim::Revocation);
4525 let accepted_preimage_claim = htlc_claim == Some(HTLCClaim::AcceptedPreimage);
4526 #[cfg(not(fuzzing))]
4527 let accepted_timeout_claim = htlc_claim == Some(HTLCClaim::AcceptedTimeout);
4528 let offered_preimage_claim = htlc_claim == Some(HTLCClaim::OfferedPreimage);
4529 #[cfg(not(fuzzing))]
4530 let offered_timeout_claim = htlc_claim == Some(HTLCClaim::OfferedTimeout);
4531
4532 let mut payment_preimage = PaymentPreimage([0; 32]);
4533 if offered_preimage_claim || accepted_preimage_claim {
4534 payment_preimage.0.copy_from_slice(input.witness.second_to_last().unwrap());
4535 }
4536
4537 macro_rules! log_claim {
4538 ($tx_info: expr, $holder_tx: expr, $htlc: expr, $source_avail: expr) => {
4539 let outbound_htlc = $holder_tx == $htlc.offered;
4540 #[cfg(not(fuzzing))] debug_assert!(!$htlc.offered || offered_preimage_claim || offered_timeout_claim || revocation_sig_claim);
4544 #[cfg(not(fuzzing))] debug_assert!($htlc.offered || accepted_preimage_claim || accepted_timeout_claim || revocation_sig_claim);
4546 #[cfg(not(fuzzing))] debug_assert_eq!(accepted_preimage_claim as u8 + accepted_timeout_claim as u8 +
4550 offered_preimage_claim as u8 + offered_timeout_claim as u8 +
4551 revocation_sig_claim as u8, 1);
4552 if ($holder_tx && revocation_sig_claim) ||
4553 (outbound_htlc && !$source_avail && (accepted_preimage_claim || offered_preimage_claim)) {
4554 log_error!(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 { "preimage claim after we'd passed the HTLC resolution back. We can likely claim the HTLC output with a revocation claim" });
4558 } else {
4559 log_info!(logger, "Input spending {} ({}:{}) in {} resolves {} HTLC with payment hash {} with {}",
4560 $tx_info, input.previous_output.txid, input.previous_output.vout, tx.compute_txid(),
4561 if outbound_htlc { "outbound" } else { "inbound" }, &$htlc.payment_hash,
4562 if revocation_sig_claim { "revocation sig" } else if accepted_preimage_claim || offered_preimage_claim { "preimage" } else { "timeout" });
4563 }
4564 }
4565 }
4566
4567 macro_rules! check_htlc_valid_counterparty {
4568 ($htlc_output: expr, $per_commitment_data: expr) => {
4569 for &(ref pending_htlc, ref pending_source) in $per_commitment_data {
4570 if pending_htlc.payment_hash == $htlc_output.payment_hash && pending_htlc.amount_msat == $htlc_output.amount_msat {
4571 if let &Some(ref source) = pending_source {
4572 log_claim!("revoked counterparty commitment tx", false, pending_htlc, true);
4573 payment_data = Some(((**source).clone(), $htlc_output.payment_hash, $htlc_output.amount_msat));
4574 break;
4575 }
4576 }
4577 }
4578 }
4579 }
4580
4581 macro_rules! scan_commitment {
4582 ($htlcs: expr, $tx_info: expr, $holder_tx: expr) => {
4583 for (ref htlc_output, source_option) in $htlcs {
4584 if Some(input.previous_output.vout) == htlc_output.transaction_output_index {
4585 if let Some(ref source) = source_option {
4586 log_claim!($tx_info, $holder_tx, htlc_output, true);
4587 payment_data = Some(((*source).clone(), htlc_output.payment_hash, htlc_output.amount_msat));
4593 } else if !$holder_tx {
4594 if let Some(current_counterparty_commitment_txid) = &self.current_counterparty_commitment_txid {
4595 check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(current_counterparty_commitment_txid).unwrap());
4596 }
4597 if payment_data.is_none() {
4598 if let Some(prev_counterparty_commitment_txid) = &self.prev_counterparty_commitment_txid {
4599 check_htlc_valid_counterparty!(htlc_output, self.counterparty_claimable_outpoints.get(prev_counterparty_commitment_txid).unwrap());
4600 }
4601 }
4602 }
4603 if payment_data.is_none() {
4604 log_claim!($tx_info, $holder_tx, htlc_output, false);
4605 let outbound_htlc = $holder_tx == htlc_output.offered;
4606 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4607 txid: tx.compute_txid(), height, block_hash: Some(*block_hash), transaction: Some(tx.clone()),
4608 event: OnchainEvent::HTLCSpendConfirmation {
4609 commitment_tx_output_idx: input.previous_output.vout,
4610 preimage: if accepted_preimage_claim || offered_preimage_claim {
4611 Some(payment_preimage) } else { None },
4612 on_to_local_output_csv: if accepted_preimage_claim && !outbound_htlc {
4617 Some(self.on_holder_tx_csv) } else { None },
4618 },
4619 });
4620 continue 'outer_loop;
4621 }
4622 }
4623 }
4624 }
4625 }
4626
4627 if input.previous_output.txid == self.current_holder_commitment_tx.txid {
4628 scan_commitment!(self.current_holder_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4629 "our latest holder commitment tx", true);
4630 }
4631 if let Some(ref prev_holder_signed_commitment_tx) = self.prev_holder_signed_commitment_tx {
4632 if input.previous_output.txid == prev_holder_signed_commitment_tx.txid {
4633 scan_commitment!(prev_holder_signed_commitment_tx.htlc_outputs.iter().map(|&(ref a, _, ref b)| (a, b.as_ref())),
4634 "our previous holder commitment tx", true);
4635 }
4636 }
4637 if let Some(ref htlc_outputs) = self.counterparty_claimable_outpoints.get(&input.previous_output.txid) {
4638 scan_commitment!(htlc_outputs.iter().map(|&(ref a, ref b)| (a, b.as_ref().map(|boxed| &**boxed))),
4639 "counterparty commitment tx", false);
4640 }
4641
4642 if let Some((source, payment_hash, amount_msat)) = payment_data {
4645 if accepted_preimage_claim {
4646 if !self.pending_monitor_events.iter().any(
4647 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
4648 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4649 txid: tx.compute_txid(),
4650 height,
4651 block_hash: Some(*block_hash),
4652 transaction: Some(tx.clone()),
4653 event: OnchainEvent::HTLCSpendConfirmation {
4654 commitment_tx_output_idx: input.previous_output.vout,
4655 preimage: Some(payment_preimage),
4656 on_to_local_output_csv: None,
4657 },
4658 });
4659 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4660 source,
4661 payment_preimage: Some(payment_preimage),
4662 payment_hash,
4663 htlc_value_satoshis: Some(amount_msat / 1000),
4664 }));
4665 }
4666 } else if offered_preimage_claim {
4667 if !self.pending_monitor_events.iter().any(
4668 |update| if let &MonitorEvent::HTLCEvent(ref upd) = update {
4669 upd.source == source
4670 } else { false }) {
4671 self.onchain_events_awaiting_threshold_conf.push(OnchainEventEntry {
4672 txid: tx.compute_txid(),
4673 transaction: Some(tx.clone()),
4674 height,
4675 block_hash: Some(*block_hash),
4676 event: OnchainEvent::HTLCSpendConfirmation {
4677 commitment_tx_output_idx: input.previous_output.vout,
4678 preimage: Some(payment_preimage),
4679 on_to_local_output_csv: None,
4680 },
4681 });
4682 self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
4683 source,
4684 payment_preimage: Some(payment_preimage),
4685 payment_hash,
4686 htlc_value_satoshis: Some(amount_msat / 1000),
4687 }));
4688 }
4689 } else {
4690 self.onchain_events_awaiting_threshold_conf.retain(|ref entry| {
4691 if entry.height != height { return true; }
4692 match entry.event {
4693 OnchainEvent::HTLCUpdate { source: ref htlc_source, .. } => {
4694 *htlc_source != source
4695 },
4696 _ => true,
4697 }
4698 });
4699 let entry = OnchainEventEntry {
4700 txid: tx.compute_txid(),
4701 transaction: Some(tx.clone()),
4702 height,
4703 block_hash: Some(*block_hash),
4704 event: OnchainEvent::HTLCUpdate {
4705 source,
4706 payment_hash,
4707 htlc_value_satoshis: Some(amount_msat / 1000),
4708 commitment_tx_output_idx: Some(input.previous_output.vout),
4709 },
4710 };
4711 log_info!(logger, "Failing HTLC with payment_hash {} timeout by a spend tx, waiting for confirmation (at height {})", &payment_hash, entry.confirmation_threshold());
4712 self.onchain_events_awaiting_threshold_conf.push(entry);
4713 }
4714 }
4715 }
4716 }
4717
4718 fn get_spendable_outputs(&self, tx: &Transaction) -> Vec<SpendableOutputDescriptor> {
4719 let mut spendable_outputs = Vec::new();
4720 for (i, outp) in tx.output.iter().enumerate() {
4721 if outp.script_pubkey == self.destination_script {
4722 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4723 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4724 output: outp.clone(),
4725 channel_keys_id: Some(self.channel_keys_id),
4726 });
4727 }
4728 if let Some(ref broadcasted_holder_revokable_script) = self.broadcasted_holder_revokable_script {
4729 if broadcasted_holder_revokable_script.0 == outp.script_pubkey {
4730 spendable_outputs.push(SpendableOutputDescriptor::DelayedPaymentOutput(DelayedPaymentOutputDescriptor {
4731 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4732 per_commitment_point: broadcasted_holder_revokable_script.1,
4733 to_self_delay: self.on_holder_tx_csv,
4734 output: outp.clone(),
4735 revocation_pubkey: broadcasted_holder_revokable_script.2,
4736 channel_keys_id: self.channel_keys_id,
4737 channel_value_satoshis: self.channel_value_satoshis,
4738 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4739 }));
4740 }
4741 }
4742 if self.counterparty_payment_script == outp.script_pubkey {
4743 spendable_outputs.push(SpendableOutputDescriptor::StaticPaymentOutput(StaticPaymentOutputDescriptor {
4744 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4745 output: outp.clone(),
4746 channel_keys_id: self.channel_keys_id,
4747 channel_value_satoshis: self.channel_value_satoshis,
4748 channel_transaction_parameters: Some(self.onchain_tx_handler.channel_transaction_parameters.clone()),
4749 }));
4750 }
4751 if self.shutdown_script.as_ref() == Some(&outp.script_pubkey) {
4752 spendable_outputs.push(SpendableOutputDescriptor::StaticOutput {
4753 outpoint: OutPoint { txid: tx.compute_txid(), index: i as u16 },
4754 output: outp.clone(),
4755 channel_keys_id: Some(self.channel_keys_id),
4756 });
4757 }
4758 }
4759 spendable_outputs
4760 }
4761
4762 fn check_tx_and_push_spendable_outputs<L: Deref>(
4765 &mut self, tx: &Transaction, height: u32, block_hash: &BlockHash, logger: &WithChannelMonitor<L>,
4766 ) where L::Target: Logger {
4767 for spendable_output in self.get_spendable_outputs(tx) {
4768 let entry = OnchainEventEntry {
4769 txid: tx.compute_txid(),
4770 transaction: Some(tx.clone()),
4771 height,
4772 block_hash: Some(*block_hash),
4773 event: OnchainEvent::MaturingOutput { descriptor: spendable_output.clone() },
4774 };
4775 log_info!(logger, "Received spendable output {}, spendable at height {}", log_spendable!(spendable_output), entry.confirmation_threshold());
4776 self.onchain_events_awaiting_threshold_conf.push(entry);
4777 }
4778 }
4779}
4780
4781impl<Signer: EcdsaChannelSigner, T: Deref, F: Deref, L: Deref> chain::Listen for (ChannelMonitor<Signer>, T, F, L)
4782where
4783 T::Target: BroadcasterInterface,
4784 F::Target: FeeEstimator,
4785 L::Target: Logger,
4786{
4787 fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
4788 self.0.block_connected(header, txdata, height, &*self.1, &*self.2, &self.3);
4789 }
4790
4791 fn block_disconnected(&self, header: &Header, height: u32) {
4792 self.0.block_disconnected(header, height, &*self.1, &*self.2, &self.3);
4793 }
4794}
4795
4796impl<Signer: EcdsaChannelSigner, M, T: Deref, F: Deref, L: Deref> chain::Confirm for (M, T, F, L)
4797where
4798 M: Deref<Target = ChannelMonitor<Signer>>,
4799 T::Target: BroadcasterInterface,
4800 F::Target: FeeEstimator,
4801 L::Target: Logger,
4802{
4803 fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
4804 self.0.transactions_confirmed(header, txdata, height, &*self.1, &*self.2, &self.3);
4805 }
4806
4807 fn transaction_unconfirmed(&self, txid: &Txid) {
4808 self.0.transaction_unconfirmed(txid, &*self.1, &*self.2, &self.3);
4809 }
4810
4811 fn best_block_updated(&self, header: &Header, height: u32) {
4812 self.0.best_block_updated(header, height, &*self.1, &*self.2, &self.3);
4813 }
4814
4815 fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
4816 self.0.get_relevant_txids()
4817 }
4818}
4819
4820const MAX_ALLOC_SIZE: usize = 64*1024;
4821
4822impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP)>
4823 for (BlockHash, ChannelMonitor<SP::EcdsaSigner>) {
4824 fn read<R: io::Read>(reader: &mut R, args: (&'a ES, &'b SP)) -> Result<Self, DecodeError> {
4825 macro_rules! unwrap_obj {
4826 ($key: expr) => {
4827 match $key {
4828 Ok(res) => res,
4829 Err(_) => return Err(DecodeError::InvalidValue),
4830 }
4831 }
4832 }
4833
4834 let (entropy_source, signer_provider) = args;
4835
4836 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
4837
4838 let latest_update_id: u64 = Readable::read(reader)?;
4839 let commitment_transaction_number_obscure_factor = <U48 as Readable>::read(reader)?.0;
4840
4841 let destination_script = Readable::read(reader)?;
4842 let broadcasted_holder_revokable_script = match <u8 as Readable>::read(reader)? {
4843 0 => {
4844 let revokable_address = Readable::read(reader)?;
4845 let per_commitment_point = Readable::read(reader)?;
4846 let revokable_script = Readable::read(reader)?;
4847 Some((revokable_address, per_commitment_point, revokable_script))
4848 },
4849 1 => { None },
4850 _ => return Err(DecodeError::InvalidValue),
4851 };
4852 let mut counterparty_payment_script: ScriptBuf = Readable::read(reader)?;
4853 let shutdown_script = {
4854 let script = <ScriptBuf as Readable>::read(reader)?;
4855 if script.is_empty() { None } else { Some(script) }
4856 };
4857
4858 let channel_keys_id = Readable::read(reader)?;
4859 let holder_revocation_basepoint = Readable::read(reader)?;
4860 let outpoint = OutPoint {
4863 txid: Readable::read(reader)?,
4864 index: Readable::read(reader)?,
4865 };
4866 let funding_info = (outpoint, Readable::read(reader)?);
4867 let current_counterparty_commitment_txid = Readable::read(reader)?;
4868 let prev_counterparty_commitment_txid = Readable::read(reader)?;
4869
4870 let counterparty_commitment_params = Readable::read(reader)?;
4871 let funding_redeemscript = Readable::read(reader)?;
4872 let channel_value_satoshis = Readable::read(reader)?;
4873
4874 let their_cur_per_commitment_points = {
4875 let first_idx = <U48 as Readable>::read(reader)?.0;
4876 if first_idx == 0 {
4877 None
4878 } else {
4879 let first_point = Readable::read(reader)?;
4880 let second_point_slice: [u8; 33] = Readable::read(reader)?;
4881 if second_point_slice[0..32] == [0; 32] && second_point_slice[32] == 0 {
4882 Some((first_idx, first_point, None))
4883 } else {
4884 Some((first_idx, first_point, Some(unwrap_obj!(PublicKey::from_slice(&second_point_slice)))))
4885 }
4886 }
4887 };
4888
4889 let on_holder_tx_csv: u16 = Readable::read(reader)?;
4890
4891 let commitment_secrets = Readable::read(reader)?;
4892
4893 macro_rules! read_htlc_in_commitment {
4894 () => {
4895 {
4896 let offered: bool = Readable::read(reader)?;
4897 let amount_msat: u64 = Readable::read(reader)?;
4898 let cltv_expiry: u32 = Readable::read(reader)?;
4899 let payment_hash: PaymentHash = Readable::read(reader)?;
4900 let transaction_output_index: Option<u32> = Readable::read(reader)?;
4901
4902 HTLCOutputInCommitment {
4903 offered, amount_msat, cltv_expiry, payment_hash, transaction_output_index
4904 }
4905 }
4906 }
4907 }
4908
4909 let counterparty_claimable_outpoints_len: u64 = Readable::read(reader)?;
4910 let mut counterparty_claimable_outpoints = hash_map_with_capacity(cmp::min(counterparty_claimable_outpoints_len as usize, MAX_ALLOC_SIZE / 64));
4911 for _ in 0..counterparty_claimable_outpoints_len {
4912 let txid: Txid = Readable::read(reader)?;
4913 let htlcs_count: u64 = Readable::read(reader)?;
4914 let mut htlcs = Vec::with_capacity(cmp::min(htlcs_count as usize, MAX_ALLOC_SIZE / 32));
4915 for _ in 0..htlcs_count {
4916 htlcs.push((read_htlc_in_commitment!(), <Option<HTLCSource> as Readable>::read(reader)?.map(|o: HTLCSource| Box::new(o))));
4917 }
4918 if counterparty_claimable_outpoints.insert(txid, htlcs).is_some() {
4919 return Err(DecodeError::InvalidValue);
4920 }
4921 }
4922
4923 let counterparty_commitment_txn_on_chain_len: u64 = Readable::read(reader)?;
4924 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));
4925 for _ in 0..counterparty_commitment_txn_on_chain_len {
4926 let txid: Txid = Readable::read(reader)?;
4927 let commitment_number = <U48 as Readable>::read(reader)?.0;
4928 if counterparty_commitment_txn_on_chain.insert(txid, commitment_number).is_some() {
4929 return Err(DecodeError::InvalidValue);
4930 }
4931 }
4932
4933 let counterparty_hash_commitment_number_len: u64 = Readable::read(reader)?;
4934 let mut counterparty_hash_commitment_number = hash_map_with_capacity(cmp::min(counterparty_hash_commitment_number_len as usize, MAX_ALLOC_SIZE / 32));
4935 for _ in 0..counterparty_hash_commitment_number_len {
4936 let payment_hash: PaymentHash = Readable::read(reader)?;
4937 let commitment_number = <U48 as Readable>::read(reader)?.0;
4938 if counterparty_hash_commitment_number.insert(payment_hash, commitment_number).is_some() {
4939 return Err(DecodeError::InvalidValue);
4940 }
4941 }
4942
4943 let mut prev_holder_signed_commitment_tx: Option<HolderSignedTx> =
4944 match <u8 as Readable>::read(reader)? {
4945 0 => None,
4946 1 => Some(Readable::read(reader)?),
4947 _ => return Err(DecodeError::InvalidValue),
4948 };
4949 let mut current_holder_commitment_tx: HolderSignedTx = Readable::read(reader)?;
4950
4951 let current_counterparty_commitment_number = <U48 as Readable>::read(reader)?.0;
4952 let current_holder_commitment_number = <U48 as Readable>::read(reader)?.0;
4953
4954 let payment_preimages_len: u64 = Readable::read(reader)?;
4955 let mut payment_preimages = hash_map_with_capacity(cmp::min(payment_preimages_len as usize, MAX_ALLOC_SIZE / 32));
4956 for _ in 0..payment_preimages_len {
4957 let preimage: PaymentPreimage = Readable::read(reader)?;
4958 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
4959 if payment_preimages.insert(hash, (preimage, Vec::new())).is_some() {
4960 return Err(DecodeError::InvalidValue);
4961 }
4962 }
4963
4964 let pending_monitor_events_len: u64 = Readable::read(reader)?;
4965 let mut pending_monitor_events = Some(
4966 Vec::with_capacity(cmp::min(pending_monitor_events_len as usize, MAX_ALLOC_SIZE / (32 + 8*3))));
4967 for _ in 0..pending_monitor_events_len {
4968 let ev = match <u8 as Readable>::read(reader)? {
4969 0 => MonitorEvent::HTLCEvent(Readable::read(reader)?),
4970 1 => MonitorEvent::HolderForceClosed(funding_info.0),
4971 _ => return Err(DecodeError::InvalidValue)
4972 };
4973 pending_monitor_events.as_mut().unwrap().push(ev);
4974 }
4975
4976 let pending_events_len: u64 = Readable::read(reader)?;
4977 let mut pending_events = Vec::with_capacity(cmp::min(pending_events_len as usize, MAX_ALLOC_SIZE / mem::size_of::<Event>()));
4978 for _ in 0..pending_events_len {
4979 if let Some(event) = MaybeReadable::read(reader)? {
4980 pending_events.push(event);
4981 }
4982 }
4983
4984 let best_block = BestBlock::new(Readable::read(reader)?, Readable::read(reader)?);
4985
4986 let waiting_threshold_conf_len: u64 = Readable::read(reader)?;
4987 let mut onchain_events_awaiting_threshold_conf = Vec::with_capacity(cmp::min(waiting_threshold_conf_len as usize, MAX_ALLOC_SIZE / 128));
4988 for _ in 0..waiting_threshold_conf_len {
4989 if let Some(val) = MaybeReadable::read(reader)? {
4990 onchain_events_awaiting_threshold_conf.push(val);
4991 }
4992 }
4993
4994 let outputs_to_watch_len: u64 = Readable::read(reader)?;
4995 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>>())));
4996 for _ in 0..outputs_to_watch_len {
4997 let txid = Readable::read(reader)?;
4998 let outputs_len: u64 = Readable::read(reader)?;
4999 let mut outputs = Vec::with_capacity(cmp::min(outputs_len as usize, MAX_ALLOC_SIZE / (mem::size_of::<u32>() + mem::size_of::<ScriptBuf>())));
5000 for _ in 0..outputs_len {
5001 outputs.push((Readable::read(reader)?, Readable::read(reader)?));
5002 }
5003 if outputs_to_watch.insert(txid, outputs).is_some() {
5004 return Err(DecodeError::InvalidValue);
5005 }
5006 }
5007 let onchain_tx_handler: OnchainTxHandler<SP::EcdsaSigner> = ReadableArgs::read(
5008 reader, (entropy_source, signer_provider, channel_value_satoshis, channel_keys_id)
5009 )?;
5010
5011 let lockdown_from_offchain = Readable::read(reader)?;
5012 let holder_tx_signed = Readable::read(reader)?;
5013
5014 if let Some(prev_commitment_tx) = prev_holder_signed_commitment_tx.as_mut() {
5015 let prev_holder_value = onchain_tx_handler.get_prev_holder_commitment_to_self_value();
5016 if prev_holder_value.is_none() { return Err(DecodeError::InvalidValue); }
5017 if prev_commitment_tx.to_self_value_sat == u64::MAX {
5018 prev_commitment_tx.to_self_value_sat = prev_holder_value.unwrap();
5019 } else if prev_commitment_tx.to_self_value_sat != prev_holder_value.unwrap() {
5020 return Err(DecodeError::InvalidValue);
5021 }
5022 }
5023
5024 let cur_holder_value = onchain_tx_handler.get_cur_holder_commitment_to_self_value();
5025 if current_holder_commitment_tx.to_self_value_sat == u64::MAX {
5026 current_holder_commitment_tx.to_self_value_sat = cur_holder_value;
5027 } else if current_holder_commitment_tx.to_self_value_sat != cur_holder_value {
5028 return Err(DecodeError::InvalidValue);
5029 }
5030
5031 let mut funding_spend_confirmed = None;
5032 let mut htlcs_resolved_on_chain = Some(Vec::new());
5033 let mut funding_spend_seen = Some(false);
5034 let mut counterparty_node_id = None;
5035 let mut confirmed_commitment_tx_counterparty_output = None;
5036 let mut spendable_txids_confirmed = Some(Vec::new());
5037 let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
5038 let mut initial_counterparty_commitment_info = None;
5039 let mut balances_empty_height = None;
5040 let mut channel_id = None;
5041 let mut holder_pays_commitment_tx_fee = None;
5042 let mut payment_preimages_with_info: Option<HashMap<_, _>> = None;
5043 read_tlv_fields!(reader, {
5044 (1, funding_spend_confirmed, option),
5045 (3, htlcs_resolved_on_chain, optional_vec),
5046 (5, pending_monitor_events, optional_vec),
5047 (7, funding_spend_seen, option),
5048 (9, counterparty_node_id, option),
5049 (11, confirmed_commitment_tx_counterparty_output, option),
5050 (13, spendable_txids_confirmed, optional_vec),
5051 (15, counterparty_fulfilled_htlcs, option),
5052 (17, initial_counterparty_commitment_info, option),
5053 (19, channel_id, option),
5054 (21, balances_empty_height, option),
5055 (23, holder_pays_commitment_tx_fee, option),
5056 (25, payment_preimages_with_info, option),
5057 });
5058 if let Some(payment_preimages_with_info) = payment_preimages_with_info {
5059 if payment_preimages_with_info.len() != payment_preimages.len() {
5060 return Err(DecodeError::InvalidValue);
5061 }
5062 for (payment_hash, (payment_preimage, _)) in payment_preimages.iter() {
5063 let new_preimage = payment_preimages_with_info.get(payment_hash).map(|(p, _)| p);
5068 if new_preimage != Some(payment_preimage) {
5069 return Err(DecodeError::InvalidValue);
5070 }
5071 }
5072 payment_preimages = payment_preimages_with_info;
5073 }
5074
5075 if let Some(ref mut pending_monitor_events) = pending_monitor_events {
5078 if pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosed(_))) &&
5079 pending_monitor_events.iter().any(|e| matches!(e, MonitorEvent::HolderForceClosedWithInfo { .. }))
5080 {
5081 pending_monitor_events.retain(|e| !matches!(e, MonitorEvent::HolderForceClosed(_)));
5082 }
5083 }
5084
5085 if onchain_tx_handler.channel_type_features().supports_anchors_zero_fee_htlc_tx() &&
5089 counterparty_payment_script.is_p2wpkh()
5090 {
5091 let payment_point = onchain_tx_handler.channel_transaction_parameters.holder_pubkeys.payment_point;
5092 counterparty_payment_script =
5093 chan_utils::get_to_countersignatory_with_anchors_redeemscript(&payment_point).to_p2wsh();
5094 }
5095
5096 Ok((best_block.block_hash, ChannelMonitor::from_impl(ChannelMonitorImpl {
5097 latest_update_id,
5098 commitment_transaction_number_obscure_factor,
5099
5100 destination_script,
5101 broadcasted_holder_revokable_script,
5102 counterparty_payment_script,
5103 shutdown_script,
5104
5105 channel_keys_id,
5106 holder_revocation_basepoint,
5107 channel_id: channel_id.unwrap_or(ChannelId::v1_from_funding_outpoint(outpoint)),
5108 funding_info,
5109 current_counterparty_commitment_txid,
5110 prev_counterparty_commitment_txid,
5111
5112 counterparty_commitment_params,
5113 funding_redeemscript,
5114 channel_value_satoshis,
5115 their_cur_per_commitment_points,
5116
5117 on_holder_tx_csv,
5118
5119 commitment_secrets,
5120 counterparty_claimable_outpoints,
5121 counterparty_commitment_txn_on_chain,
5122 counterparty_hash_commitment_number,
5123 counterparty_fulfilled_htlcs: counterparty_fulfilled_htlcs.unwrap(),
5124
5125 prev_holder_signed_commitment_tx,
5126 current_holder_commitment_tx,
5127 current_counterparty_commitment_number,
5128 current_holder_commitment_number,
5129
5130 payment_preimages,
5131 pending_monitor_events: pending_monitor_events.unwrap(),
5132 pending_events,
5133 is_processing_pending_events: false,
5134
5135 onchain_events_awaiting_threshold_conf,
5136 outputs_to_watch,
5137
5138 onchain_tx_handler,
5139
5140 lockdown_from_offchain,
5141 holder_tx_signed,
5142 holder_pays_commitment_tx_fee,
5143 funding_spend_seen: funding_spend_seen.unwrap(),
5144 funding_spend_confirmed,
5145 confirmed_commitment_tx_counterparty_output,
5146 htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
5147 spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
5148
5149 best_block,
5150 counterparty_node_id,
5151 initial_counterparty_commitment_info,
5152 balances_empty_height,
5153 failed_back_htlc_ids: new_hash_set(),
5154 })))
5155 }
5156}
5157
5158#[cfg(test)]
5159mod tests {
5160 use bitcoin::amount::Amount;
5161 use bitcoin::locktime::absolute::LockTime;
5162 use bitcoin::script::{ScriptBuf, Builder};
5163 use bitcoin::opcodes;
5164 use bitcoin::transaction::{Transaction, TxIn, TxOut, Version};
5165 use bitcoin::transaction::OutPoint as BitcoinOutPoint;
5166 use bitcoin::sighash;
5167 use bitcoin::sighash::EcdsaSighashType;
5168 use bitcoin::hashes::Hash;
5169 use bitcoin::hashes::sha256::Hash as Sha256;
5170 use bitcoin::hex::FromHex;
5171 use bitcoin::hash_types::{BlockHash, Txid};
5172 use bitcoin::network::Network;
5173 use bitcoin::secp256k1::{SecretKey,PublicKey};
5174 use bitcoin::secp256k1::Secp256k1;
5175 use bitcoin::{Sequence, Witness};
5176
5177 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
5178
5179 use super::ChannelMonitorUpdateStep;
5180 use crate::{check_added_monitors, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash};
5181 use crate::chain::{BestBlock, Confirm};
5182 use crate::chain::channelmonitor::{ChannelMonitor, WithChannelMonitor};
5183 use crate::chain::package::{weight_offered_htlc, weight_received_htlc, weight_revoked_offered_htlc, weight_revoked_received_htlc, WEIGHT_REVOKED_OUTPUT};
5184 use crate::chain::transaction::OutPoint;
5185 use crate::sign::InMemorySigner;
5186 use crate::ln::types::ChannelId;
5187 use crate::types::payment::{PaymentPreimage, PaymentHash};
5188 use crate::ln::channel_keys::{DelayedPaymentBasepoint, DelayedPaymentKey, HtlcBasepoint, RevocationBasepoint, RevocationKey};
5189 use crate::ln::chan_utils::{self,HTLCOutputInCommitment, ChannelPublicKeys, ChannelTransactionParameters, HolderCommitmentTransaction, CounterpartyChannelTransactionParameters};
5190 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
5191 use crate::ln::functional_test_utils::*;
5192 use crate::ln::script::ShutdownScript;
5193 use crate::util::test_utils::{TestLogger, TestBroadcaster, TestFeeEstimator};
5194 use crate::util::ser::{ReadableArgs, Writeable};
5195 use crate::util::logger::Logger;
5196 use crate::sync::Arc;
5197 use crate::io;
5198 use crate::types::features::ChannelTypeFeatures;
5199
5200 #[allow(unused_imports)]
5201 use crate::prelude::*;
5202
5203 use std::str::FromStr;
5204
5205 fn do_test_funding_spend_refuses_updates(use_local_txn: bool) {
5206 let chanmon_cfgs = create_chanmon_cfgs(3);
5218 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5219 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5220 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5221 let channel = create_announced_chan_between_nodes(&nodes, 0, 1);
5222 create_announced_chan_between_nodes(&nodes, 1, 2);
5223
5224 send_payment(&nodes[0], &[&nodes[1]], 10_000_000);
5226
5227 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5229 let payment_preimage_2 = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000).0;
5230
5231 let local_txn = get_local_commitment_txn!(nodes[1], channel.2);
5232 assert_eq!(local_txn.len(), 1);
5233 let remote_txn = get_local_commitment_txn!(nodes[0], channel.2);
5234 assert_eq!(remote_txn.len(), 3); check_spends!(remote_txn[1], remote_txn[0]);
5236 check_spends!(remote_txn[2], remote_txn[0]);
5237 let broadcast_tx = if use_local_txn { &local_txn[0] } else { &remote_txn[0] };
5238
5239 let new_header = create_dummy_header(nodes[0].best_block_info().0, 0);
5242 let conf_height = nodes[0].best_block_info().1 + 1;
5243 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(&new_header,
5244 &[(0, broadcast_tx)], conf_height);
5245
5246 let (_, pre_update_monitor) = <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
5247 &mut io::Cursor::new(&get_monitor!(nodes[1], channel.2).encode()),
5248 (&nodes[1].keys_manager.backing, &nodes[1].keys_manager.backing)).unwrap();
5249
5250 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
5253 nodes[1].node.send_payment_with_route(route, payment_hash,
5254 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
5255 ).unwrap();
5256 check_added_monitors!(nodes[1], 1);
5257
5258 let monitor_updates = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
5262 let mut replay_update = monitor_updates.get(&channel.2).unwrap().iter().rev().next().unwrap().clone();
5263 assert_eq!(replay_update.updates.len(), 1);
5264 if let ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo { .. } = replay_update.updates[0] {
5265 } else { panic!(); }
5266 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5267 payment_preimage: payment_preimage_1, payment_info: None,
5268 });
5269 replay_update.updates.push(ChannelMonitorUpdateStep::PaymentPreimage {
5270 payment_preimage: payment_preimage_2, payment_info: None,
5271 });
5272
5273 let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
5274 assert!(
5275 pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
5276 .is_err());
5277 let txn_broadcasted = broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5280 assert!(txn_broadcasted.len() >= 2);
5281 let htlc_txn = txn_broadcasted.iter().filter(|tx| {
5282 assert_eq!(tx.input.len(), 1);
5283 tx.input[0].previous_output.txid == broadcast_tx.compute_txid()
5284 }).collect::<Vec<_>>();
5285 assert_eq!(htlc_txn.len(), 2);
5286 check_spends!(htlc_txn[0], broadcast_tx);
5287 check_spends!(htlc_txn[1], broadcast_tx);
5288 }
5289 #[test]
5290 fn test_funding_spend_refuses_updates() {
5291 do_test_funding_spend_refuses_updates(true);
5292 do_test_funding_spend_refuses_updates(false);
5293 }
5294
5295 #[test]
5296 fn test_prune_preimages() {
5297 let secp_ctx = Secp256k1::new();
5298 let logger = Arc::new(TestLogger::new());
5299 let broadcaster = Arc::new(TestBroadcaster::new(Network::Testnet));
5300 let fee_estimator = TestFeeEstimator::new(253);
5301
5302 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5303
5304 let mut preimages = Vec::new();
5305 {
5306 for i in 0..20 {
5307 let preimage = PaymentPreimage([i; 32]);
5308 let hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
5309 preimages.push((preimage, hash));
5310 }
5311 }
5312
5313 macro_rules! preimages_slice_to_htlcs {
5314 ($preimages_slice: expr) => {
5315 {
5316 let mut res = Vec::new();
5317 for (idx, preimage) in $preimages_slice.iter().enumerate() {
5318 res.push((HTLCOutputInCommitment {
5319 offered: true,
5320 amount_msat: 0,
5321 cltv_expiry: 0,
5322 payment_hash: preimage.1.clone(),
5323 transaction_output_index: Some(idx as u32),
5324 }, ()));
5325 }
5326 res
5327 }
5328 }
5329 }
5330 macro_rules! preimages_slice_to_htlc_outputs {
5331 ($preimages_slice: expr) => {
5332 preimages_slice_to_htlcs!($preimages_slice).into_iter().map(|(htlc, _)| (htlc, None)).collect()
5333 }
5334 }
5335 let dummy_sig = crate::crypto::utils::sign(&secp_ctx,
5336 &bitcoin::secp256k1::Message::from_digest([42; 32]),
5337 &SecretKey::from_slice(&[42; 32]).unwrap());
5338
5339 macro_rules! test_preimages_exist {
5340 ($preimages_slice: expr, $monitor: expr) => {
5341 for preimage in $preimages_slice {
5342 assert!($monitor.inner.lock().unwrap().payment_preimages.contains_key(&preimage.1));
5343 }
5344 }
5345 }
5346
5347 let keys = InMemorySigner::new(
5348 &secp_ctx,
5349 SecretKey::from_slice(&[41; 32]).unwrap(),
5350 SecretKey::from_slice(&[41; 32]).unwrap(),
5351 SecretKey::from_slice(&[41; 32]).unwrap(),
5352 SecretKey::from_slice(&[41; 32]).unwrap(),
5353 SecretKey::from_slice(&[41; 32]).unwrap(),
5354 [41; 32],
5355 0,
5356 [0; 32],
5357 [0; 32],
5358 );
5359
5360 let counterparty_pubkeys = ChannelPublicKeys {
5361 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5362 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5363 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5364 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5365 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap()))
5366 };
5367 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5368 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5369 let channel_parameters = ChannelTransactionParameters {
5370 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5371 holder_selected_contest_delay: 66,
5372 is_outbound_from_holder: true,
5373 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5374 pubkeys: counterparty_pubkeys,
5375 selected_contest_delay: 67,
5376 }),
5377 funding_outpoint: Some(funding_outpoint),
5378 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5379 };
5380 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5383 let best_block = BestBlock::from_network(Network::Testnet);
5384 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5385 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5386 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5387 &channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5388 best_block, dummy_key, channel_id);
5389
5390 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..10]);
5391 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5392
5393 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5394 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5395 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"1").to_byte_array()),
5396 preimages_slice_to_htlc_outputs!(preimages[5..15]), 281474976710655, dummy_key, &logger);
5397 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"2").to_byte_array()),
5398 preimages_slice_to_htlc_outputs!(preimages[15..20]), 281474976710654, dummy_key, &logger);
5399 for &(ref preimage, ref hash) in preimages.iter() {
5400 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
5401 monitor.provide_payment_preimage_unsafe_legacy(
5402 hash, preimage, &broadcaster, &bounded_fee_estimator, &logger
5403 );
5404 }
5405
5406 let mut secret = [0; 32];
5408 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap());
5409 monitor.provide_secret(281474976710655, secret.clone()).unwrap();
5410 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 15);
5411 test_preimages_exist!(&preimages[0..10], monitor);
5412 test_preimages_exist!(&preimages[15..20], monitor);
5413
5414 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"3").to_byte_array()),
5415 preimages_slice_to_htlc_outputs!(preimages[17..20]), 281474976710653, dummy_key, &logger);
5416
5417 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("c7518c8ae4660ed02894df8976fa1a3659c1a8b4b5bec0c4b872abeba4cb8964").unwrap());
5419 monitor.provide_secret(281474976710654, secret.clone()).unwrap();
5420 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 13);
5421 test_preimages_exist!(&preimages[0..10], monitor);
5422 test_preimages_exist!(&preimages[17..20], monitor);
5423
5424 monitor.provide_latest_counterparty_commitment_tx(Txid::from_byte_array(Sha256::hash(b"4").to_byte_array()),
5425 preimages_slice_to_htlc_outputs!(preimages[18..20]), 281474976710652, dummy_key, &logger);
5426
5427 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..5]);
5430 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5431 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx.clone(),
5432 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5433 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("2273e227a5b7449b6e70f1fb4652864038b1cbf9cd7c043a7d6456b7fc275ad8").unwrap());
5434 monitor.provide_secret(281474976710653, secret.clone()).unwrap();
5435 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 12);
5436 test_preimages_exist!(&preimages[0..10], monitor);
5437 test_preimages_exist!(&preimages[18..20], monitor);
5438
5439 let mut htlcs = preimages_slice_to_htlcs!(preimages[0..3]);
5441 let dummy_commitment_tx = HolderCommitmentTransaction::dummy(&mut htlcs);
5442 monitor.provide_latest_holder_commitment_tx(dummy_commitment_tx,
5443 htlcs.into_iter().map(|(htlc, _)| (htlc, Some(dummy_sig), None)).collect());
5444 secret[0..32].clone_from_slice(&<Vec<u8>>::from_hex("27cddaa5624534cb6cb9d7da077cf2b22ab21e9b506fd4998a51d54502e99116").unwrap());
5445 monitor.provide_secret(281474976710652, secret.clone()).unwrap();
5446 assert_eq!(monitor.inner.lock().unwrap().payment_preimages.len(), 5);
5447 test_preimages_exist!(&preimages[0..5], monitor);
5448 }
5449
5450 #[test]
5451 fn test_claim_txn_weight_computation() {
5452 let secp_ctx = Secp256k1::new();
5456 let privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5457 let pubkey = PublicKey::from_secret_key(&secp_ctx, &privkey);
5458
5459 use crate::ln::channel_keys::{HtlcKey, HtlcBasepoint};
5460 macro_rules! sign_input {
5461 ($sighash_parts: expr, $idx: expr, $amount: expr, $weight: expr, $sum_actual_sigs: expr, $opt_anchors: expr) => {
5462 let htlc = HTLCOutputInCommitment {
5463 offered: if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_offered_htlc($opt_anchors) { true } else { false },
5464 amount_msat: 0,
5465 cltv_expiry: 2 << 16,
5466 payment_hash: PaymentHash([1; 32]),
5467 transaction_output_index: Some($idx as u32),
5468 };
5469 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)) };
5470 let sighash = hash_to_message!(&$sighash_parts.p2wsh_signature_hash($idx, &redeem_script, $amount, EcdsaSighashType::All).unwrap()[..]);
5471 let sig = secp_ctx.sign_ecdsa(&sighash, &privkey);
5472 let mut ser_sig = sig.serialize_der().to_vec();
5473 ser_sig.push(EcdsaSighashType::All as u8);
5474 $sum_actual_sigs += ser_sig.len() as u64;
5475 let witness = $sighash_parts.witness_mut($idx).unwrap();
5476 witness.push(ser_sig);
5477 if *$weight == WEIGHT_REVOKED_OUTPUT {
5478 witness.push(vec!(1));
5479 } else if *$weight == weight_revoked_offered_htlc($opt_anchors) || *$weight == weight_revoked_received_htlc($opt_anchors) {
5480 witness.push(pubkey.clone().serialize().to_vec());
5481 } else if *$weight == weight_received_htlc($opt_anchors) {
5482 witness.push(vec![0]);
5483 } else {
5484 witness.push(PaymentPreimage([1; 32]).0.to_vec());
5485 }
5486 witness.push(redeem_script.into_bytes());
5487 let witness = witness.to_vec();
5488 println!("witness[0] {}", witness[0].len());
5489 println!("witness[1] {}", witness[1].len());
5490 println!("witness[2] {}", witness[2].len());
5491 }
5492 }
5493
5494 let script_pubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script();
5495 let txid = Txid::from_str("56944c5d3f98413ef45cf54545538103cc9f298e0575820ad3591376e2e0f65d").unwrap();
5496
5497 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5499 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5500 let mut sum_actual_sigs = 0;
5501 for i in 0..4 {
5502 claim_tx.input.push(TxIn {
5503 previous_output: BitcoinOutPoint {
5504 txid,
5505 vout: i,
5506 },
5507 script_sig: ScriptBuf::new(),
5508 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5509 witness: Witness::new(),
5510 });
5511 }
5512 claim_tx.output.push(TxOut {
5513 script_pubkey: script_pubkey.clone(),
5514 value: Amount::ZERO,
5515 });
5516 let base_weight = claim_tx.weight().to_wu();
5517 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)];
5518 let mut inputs_total_weight = 2; {
5520 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5521 for (idx, inp) in inputs_weight.iter().enumerate() {
5522 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5523 inputs_total_weight += inp;
5524 }
5525 }
5526 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5527 }
5528
5529 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5531 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5532 let mut sum_actual_sigs = 0;
5533 for i in 0..4 {
5534 claim_tx.input.push(TxIn {
5535 previous_output: BitcoinOutPoint {
5536 txid,
5537 vout: i,
5538 },
5539 script_sig: ScriptBuf::new(),
5540 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5541 witness: Witness::new(),
5542 });
5543 }
5544 claim_tx.output.push(TxOut {
5545 script_pubkey: script_pubkey.clone(),
5546 value: Amount::ZERO,
5547 });
5548 let base_weight = claim_tx.weight().to_wu();
5549 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)];
5550 let mut inputs_total_weight = 2; {
5552 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5553 for (idx, inp) in inputs_weight.iter().enumerate() {
5554 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5555 inputs_total_weight += inp;
5556 }
5557 }
5558 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5559 }
5560
5561 for channel_type_features in [ChannelTypeFeatures::only_static_remote_key(), ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies()].iter() {
5563 let mut claim_tx = Transaction { version: Version(0), lock_time: LockTime::ZERO, input: Vec::new(), output: Vec::new() };
5564 let mut sum_actual_sigs = 0;
5565 claim_tx.input.push(TxIn {
5566 previous_output: BitcoinOutPoint {
5567 txid,
5568 vout: 0,
5569 },
5570 script_sig: ScriptBuf::new(),
5571 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
5572 witness: Witness::new(),
5573 });
5574 claim_tx.output.push(TxOut {
5575 script_pubkey: script_pubkey.clone(),
5576 value: Amount::ZERO,
5577 });
5578 let base_weight = claim_tx.weight().to_wu();
5579 let inputs_weight = vec![WEIGHT_REVOKED_OUTPUT];
5580 let mut inputs_total_weight = 2; {
5582 let mut sighash_parts = sighash::SighashCache::new(&mut claim_tx);
5583 for (idx, inp) in inputs_weight.iter().enumerate() {
5584 sign_input!(sighash_parts, idx, Amount::ZERO, inp, sum_actual_sigs, channel_type_features);
5585 inputs_total_weight += inp;
5586 }
5587 }
5588 assert_eq!(base_weight + inputs_total_weight, claim_tx.weight().to_wu() + (73 * inputs_weight.len() as u64 - sum_actual_sigs));
5589 }
5590 }
5591
5592 #[test]
5593 fn test_with_channel_monitor_impl_logger() {
5594 let secp_ctx = Secp256k1::new();
5595 let logger = Arc::new(TestLogger::new());
5596
5597 let dummy_key = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5598
5599 let keys = InMemorySigner::new(
5600 &secp_ctx,
5601 SecretKey::from_slice(&[41; 32]).unwrap(),
5602 SecretKey::from_slice(&[41; 32]).unwrap(),
5603 SecretKey::from_slice(&[41; 32]).unwrap(),
5604 SecretKey::from_slice(&[41; 32]).unwrap(),
5605 SecretKey::from_slice(&[41; 32]).unwrap(),
5606 [41; 32],
5607 0,
5608 [0; 32],
5609 [0; 32],
5610 );
5611
5612 let counterparty_pubkeys = ChannelPublicKeys {
5613 funding_pubkey: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[44; 32]).unwrap()),
5614 revocation_basepoint: RevocationBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[45; 32]).unwrap())),
5615 payment_point: PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[46; 32]).unwrap()),
5616 delayed_payment_basepoint: DelayedPaymentBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[47; 32]).unwrap())),
5617 htlc_basepoint: HtlcBasepoint::from(PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[48; 32]).unwrap())),
5618 };
5619 let funding_outpoint = OutPoint { txid: Txid::all_zeros(), index: u16::MAX };
5620 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
5621 let channel_parameters = ChannelTransactionParameters {
5622 holder_pubkeys: keys.holder_channel_pubkeys.clone(),
5623 holder_selected_contest_delay: 66,
5624 is_outbound_from_holder: true,
5625 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
5626 pubkeys: counterparty_pubkeys,
5627 selected_contest_delay: 67,
5628 }),
5629 funding_outpoint: Some(funding_outpoint),
5630 channel_type_features: ChannelTypeFeatures::only_static_remote_key()
5631 };
5632 let shutdown_pubkey = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
5633 let best_block = BestBlock::from_network(Network::Testnet);
5634 let monitor = ChannelMonitor::new(Secp256k1::new(), keys,
5635 Some(ShutdownScript::new_p2wpkh_from_pubkey(shutdown_pubkey).into_inner()), 0, &ScriptBuf::new(),
5636 (OutPoint { txid: Txid::from_slice(&[43; 32]).unwrap(), index: 0 }, ScriptBuf::new()),
5637 &channel_parameters, true, ScriptBuf::new(), 46, 0, HolderCommitmentTransaction::dummy(&mut Vec::new()),
5638 best_block, dummy_key, channel_id);
5639
5640 let chan_id = monitor.inner.lock().unwrap().channel_id();
5641 let payment_hash = PaymentHash([1; 32]);
5642 let context_logger = WithChannelMonitor::from(&logger, &monitor, Some(payment_hash));
5643 log_error!(context_logger, "This is an error");
5644 log_warn!(context_logger, "This is an error");
5645 log_debug!(context_logger, "This is an error");
5646 log_trace!(context_logger, "This is an error");
5647 log_gossip!(context_logger, "This is an error");
5648 log_info!(context_logger, "This is an error");
5649 logger.assert_log_context_contains("lightning::chain::channelmonitor::tests", Some(dummy_key), Some(chan_id), 6);
5650 }
5651 }