1use bitcoin::absolute::LockTime;
11use bitcoin::amount::{Amount, SignedAmount};
12use bitcoin::consensus::encode;
13use bitcoin::constants::ChainHash;
14use bitcoin::script::{Builder, Script, ScriptBuf};
15use bitcoin::sighash::EcdsaSighashType;
16use bitcoin::transaction::{Transaction, TxOut};
17use bitcoin::Witness;
18
19use bitcoin::hash_types::{BlockHash, Txid};
20use bitcoin::hashes::sha256::Hash as Sha256;
21use bitcoin::hashes::sha256d::Hash as Sha256d;
22use bitcoin::hashes::Hash;
23
24use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
25use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1};
26use bitcoin::secp256k1::{PublicKey, SecretKey};
27use bitcoin::{secp256k1, sighash, FeeRate, Sequence, TxIn};
28
29use crate::blinded_path::message::BlindedMessagePath;
30use crate::chain::chaininterface::{
31 ChannelFunding, ConfirmationTarget, FeeEstimator, FundingCandidate, FundingPurpose,
32 LowerBoundedFeeEstimator, TransactionType,
33};
34use crate::chain::channelmonitor::{
35 ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, CommitmentHTLCData,
36 LATENCY_GRACE_PERIOD_BLOCKS,
37};
38use crate::chain::package::verify_channel_type_features;
39use crate::chain::transaction::{OutPoint, TransactionData};
40use crate::chain::BlockLocator;
41use crate::events::{
42 ClosureReason, FailedSpliceContribution, FundingInfo, NegotiationFailureReason,
43};
44use crate::ln::chan_utils;
45use crate::ln::chan_utils::{
46 get_commitment_transaction_number_obscure_factor, max_htlcs, second_stage_tx_fees_sat,
47 selected_commitment_sat_per_1000_weight, ChannelPublicKeys, ChannelTransactionParameters,
48 ClosingTransaction, CommitmentTransaction, CounterpartyChannelTransactionParameters,
49 CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction,
50 EMPTY_SCRIPT_SIG_WEIGHT, FUNDING_TRANSACTION_WITNESS_WEIGHT,
51};
52use crate::ln::channel_state::{
53 ChannelShutdownState, ConfirmedSpliceCandidate, CounterpartyForwardingInfo, InboundHTLCDetails,
54 InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails, SpliceCandidateDetails,
55 SpliceCandidateStatus, SpliceDetails,
56};
57use crate::ln::channelmanager::{
58 self, BlindedFailure, ChannelReadyOrder, FundingConfirmedMessage, HTLCFailureMsg,
59 HTLCPreviousHopData, HTLCSource, OpenChannelMessage, PaymentClaimDetails, PendingHTLCInfo,
60 PendingHTLCStatus, RAACommitmentOrder, SentHTLCId, TrustedChannelFeatures, TxSignaturesOrder,
61 BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA,
62};
63use crate::ln::funding::{
64 FeeRateAdjustmentError, FundingContribution, FundingTemplate, PendingFundingComponents,
65};
66use crate::ln::interactivetxs::{
67 AbortReason, HandleTxCompleteValue, InteractiveTxConstructor, InteractiveTxConstructorArgs,
68 InteractiveTxMessageSend, InteractiveTxSigningSession, SharedOwnedInput, SharedOwnedOutput,
69};
70use crate::ln::msgs;
71use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError, OnionErrorPacket};
72use crate::ln::onion_utils::{
73 AttributionData, HTLCFailReason, LocalHTLCFailureReason, HOLD_TIME_UNIT_MILLIS,
74};
75use crate::ln::script::{self, ShutdownScript};
76use crate::ln::types::ChannelId;
77use crate::offers::static_invoice::StaticInvoice;
78use crate::routing::gossip::NodeId;
79use crate::sign::ecdsa::EcdsaChannelSigner;
80use crate::sign::tx_builder::{
81 ChannelConstraints, ChannelStats, HTLCAmountDirection, SpecTxBuilder, TxBuilder,
82};
83use crate::sign::{ChannelSigner, EntropySource, NodeSigner, Recipient, SignerProvider};
84use crate::types::features::{ChannelTypeFeatures, InitFeatures};
85use crate::types::payment::{PaymentHash, PaymentPreimage};
86use crate::util::config::{
87 ChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, LegacyChannelConfig,
88 MaxDustHTLCExposure, UserConfig,
89};
90use crate::util::errors::APIError;
91use crate::util::logger::{Logger, Record, WithContext};
92use crate::util::scid_utils::{block_from_scid, scid_from_parts};
93use crate::util::ser::{Iterable, Readable, ReadableArgs, RequiredWrapper, Writeable, Writer};
94use crate::util::wallet_utils::{ConfirmedUtxo, Input};
95use crate::{impl_readable_for_vec, impl_writeable_for_vec};
96
97use alloc::collections::{btree_map, BTreeMap};
98
99use crate::io;
100use crate::prelude::*;
101#[cfg(any(test, fuzzing, debug_assertions))]
102use crate::sync::Mutex;
103use core::time::Duration;
104use core::{cmp, fmt, mem};
105
106use super::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint};
107
108#[cfg(any(test, feature = "_test_utils"))]
109#[allow(unused)]
110pub struct ChannelValueStat {
111 pub value_to_self_msat: u64,
112 pub channel_value_msat: u64,
113 pub channel_reserve_msat: u64,
114 pub pending_outbound_htlcs_amount_msat: u64,
115 pub pending_inbound_htlcs_amount_msat: u64,
116 pub holding_cell_outbound_amount_msat: u64,
117 pub counterparty_max_htlc_value_in_flight_msat: u64, pub counterparty_dust_limit_msat: u64,
119}
120
121pub struct AvailableBalances {
122 pub inbound_capacity_msat: u64,
124 pub outbound_capacity_msat: u64,
126 pub next_outbound_htlc_limit_msat: u64,
128 pub next_outbound_htlc_minimum_msat: u64,
130 pub dust_exposure_msat: u64,
139 pub next_splice_out_maximum_sat: u64,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq)]
144enum FeeUpdateState {
145 RemoteAnnounced,
147 AwaitingRemoteRevokeToAnnounce,
148 Outbound,
156}
157
158#[derive(Clone, Copy, PartialEq, Eq)]
159enum NextCommitmentView {
160 ValidatingPeerUpdate,
161 ValidatingOwnUpdate,
162}
163
164struct NextCommitmentProjection {
165 next_value_to_self_msat: u64,
166 next_commitment_htlcs: Vec<HTLCAmountDirection>,
167}
168
169#[derive(Debug)]
170enum InboundHTLCRemovalReason {
171 FailRelay(msgs::OnionErrorPacket),
172 FailMalformed { sha256_of_onion: [u8; 32], failure_code: u16 },
173 Fulfill { preimage: PaymentPreimage, attribution_data: Option<AttributionData> },
174}
175
176#[cfg_attr(test, derive(Debug))]
178#[derive(Clone)]
179enum InboundHTLCResolution {
180 Resolved { pending_htlc_status: PendingHTLCStatus },
186 Pending { update_add_htlc: msgs::UpdateAddHTLC },
190}
191
192impl_writeable_tlv_based_enum!(InboundHTLCResolution,
193 (0, Resolved) => {
194 (0, pending_htlc_status, required),
195 },
196 (2, Pending) => {
197 (0, update_add_htlc, required),
198 },
199);
200
201#[cfg_attr(test, derive(Debug))]
202enum InboundHTLCState {
203 RemoteAnnounced(InboundHTLCResolution),
206 AwaitingRemoteRevokeToAnnounce(InboundHTLCResolution),
236 AwaitingAnnouncedRemoteRevoke(InboundHTLCResolution),
242 Committed {
245 update_add_htlc: InboundUpdateAdd,
249 },
250 LocalRemoved(InboundHTLCRemovalReason),
261}
262
263impl From<&InboundHTLCState> for Option<InboundHTLCStateDetails> {
264 fn from(state: &InboundHTLCState) -> Option<InboundHTLCStateDetails> {
265 match state {
266 InboundHTLCState::RemoteAnnounced(_) => None,
267 InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) => {
268 Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToAdd)
269 },
270 InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => {
271 Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToAdd)
272 },
273 InboundHTLCState::Committed { .. } => Some(InboundHTLCStateDetails::Committed),
274 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(_)) => {
275 Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFail)
276 },
277 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailMalformed { .. }) => {
278 Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFail)
279 },
280 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill { .. }) => {
281 Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFulfill)
282 },
283 }
284 }
285}
286
287impl fmt::Display for InboundHTLCState {
288 #[rustfmt::skip]
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 match self {
291 InboundHTLCState::RemoteAnnounced(_) => write!(f, "RemoteAnnounced"),
292 InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) => write!(f, "AwaitingRemoteRevokeToAnnounce"),
293 InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => write!(f, "AwaitingAnnouncedRemoteRevoke"),
294 InboundHTLCState::Committed { .. } => write!(f, "Committed"),
295 InboundHTLCState::LocalRemoved(_) => write!(f, "LocalRemoved"),
296 }
297 }
298}
299
300impl InboundHTLCState {
301 fn included_in_commitment(&self, generated_by_local: bool) -> bool {
302 match self {
303 InboundHTLCState::RemoteAnnounced(_) => !generated_by_local,
304 InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) => !generated_by_local,
305 InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => true,
306 InboundHTLCState::Committed { .. } => true,
307 InboundHTLCState::LocalRemoved(_) => !generated_by_local,
308 }
309 }
310
311 fn preimage(&self) -> Option<PaymentPreimage> {
312 match self {
313 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill {
314 preimage, ..
315 }) => Some(*preimage),
316 _ => None,
317 }
318 }
319
320 fn should_hold_htlc(&self) -> bool {
325 match self {
326 InboundHTLCState::RemoteAnnounced(res)
327 | InboundHTLCState::AwaitingRemoteRevokeToAnnounce(res)
328 | InboundHTLCState::AwaitingAnnouncedRemoteRevoke(res) => match res {
329 InboundHTLCResolution::Pending { update_add_htlc } => {
330 update_add_htlc.hold_htlc.is_some()
331 },
332 InboundHTLCResolution::Resolved { .. } => false,
333 },
334 InboundHTLCState::Committed { .. } | InboundHTLCState::LocalRemoved(_) => false,
335 }
336 }
337}
338
339#[derive(Debug, Copy, Clone)]
344pub(super) struct OutboundHop {
345 pub(super) amt_msat: u64,
347 pub(super) channel_id: ChannelId,
349 pub(super) node_id: PublicKey,
351 pub(super) funding_txo: OutPoint,
353 pub(super) user_channel_id: u128,
355}
356
357impl_writeable_tlv_based!(OutboundHop, {
358 (0, amt_msat, required),
359 (2, channel_id, required),
360 (4, node_id, required),
361 (6, funding_txo, required),
362 (8, user_channel_id, required),
363});
364
365#[derive(Debug, Clone)]
372enum InboundUpdateAdd {
373 WithOnion { update_add_htlc: msgs::UpdateAddHTLC },
375 Forwarded {
381 incoming_packet_shared_secret: [u8; 32],
382 phantom_shared_secret: Option<[u8; 32]>,
383 trampoline_shared_secret: Option<[u8; 32]>,
384 blinded_failure: Option<BlindedFailure>,
385 outbound_hop: OutboundHop,
386 },
387 Legacy,
389}
390
391impl_writeable_tlv_based_enum_upgradable!(InboundUpdateAdd,
392 (0, WithOnion) => {
393 (0, update_add_htlc, required),
394 },
395 (2, Legacy) => {},
396 (4, Forwarded) => {
397 (0, incoming_packet_shared_secret, required),
398 (2, outbound_hop, required),
399 (4, phantom_shared_secret, option),
400 (6, trampoline_shared_secret, option),
401 (8, blinded_failure, option),
402 },
403);
404
405impl_writeable_for_vec!(&InboundUpdateAdd);
406impl_readable_for_vec!(InboundUpdateAdd);
407
408#[cfg_attr(test, derive(Debug))]
409struct InboundHTLCOutput {
410 htlc_id: u64,
411 amount_msat: u64,
412 cltv_expiry: u32,
413 payment_hash: PaymentHash,
414 state: InboundHTLCState,
415}
416
417#[derive(Debug)]
418#[cfg_attr(test, derive(Clone, PartialEq))]
419enum OutboundHTLCState {
420 LocalAnnounced(Box<msgs::OnionPacket>),
433 Committed,
434 RemoteRemoved(OutboundHTLCOutcome),
437 AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome),
443 AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome),
449}
450
451impl From<&OutboundHTLCState> for OutboundHTLCStateDetails {
452 fn from(state: &OutboundHTLCState) -> OutboundHTLCStateDetails {
453 match state {
454 OutboundHTLCState::LocalAnnounced(_) => {
455 OutboundHTLCStateDetails::AwaitingRemoteRevokeToAdd
456 },
457 OutboundHTLCState::Committed => OutboundHTLCStateDetails::Committed,
458 OutboundHTLCState::RemoteRemoved(_) => OutboundHTLCStateDetails::Committed,
461 OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Success {
462 ..
463 }) => OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveSuccess,
464 OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Failure(_)) => {
465 OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFailure
466 },
467 OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Success {
468 ..
469 }) => OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveSuccess,
470 OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Failure(_)) => {
471 OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFailure
472 },
473 }
474 }
475}
476
477impl fmt::Display for OutboundHTLCState {
478 #[rustfmt::skip]
479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
480 match self {
481 OutboundHTLCState::LocalAnnounced(_) => write!(f, "LocalAnnounced"),
482 OutboundHTLCState::Committed => write!(f, "Committed"),
483 OutboundHTLCState::RemoteRemoved(_) => write!(f, "RemoteRemoved"),
484 OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) => write!(f, "AwaitingRemoteRevokeToRemove"),
485 OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) => write!(f, "AwaitingRemovedRemoteRevoke"),
486 }
487 }
488}
489
490impl OutboundHTLCState {
491 fn included_in_commitment(&self, generated_by_local: bool) -> bool {
492 match self {
493 OutboundHTLCState::LocalAnnounced(_) => generated_by_local,
494 OutboundHTLCState::Committed => true,
495 OutboundHTLCState::RemoteRemoved(_) => generated_by_local,
496 OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) => generated_by_local,
497 OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) => false,
498 }
499 }
500
501 fn preimage(&self) -> Option<PaymentPreimage> {
502 match self {
503 OutboundHTLCState::RemoteRemoved(OutboundHTLCOutcome::Success { preimage, .. })
504 | OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Success {
505 preimage,
506 ..
507 })
508 | OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Success {
509 preimage,
510 ..
511 }) => Some(*preimage),
512 _ => None,
513 }
514 }
515}
516
517#[derive(Clone, Debug)]
518#[cfg_attr(test, derive(PartialEq))]
519enum OutboundHTLCOutcome {
520 Success {
523 preimage: PaymentPreimage,
524 attribution_data: Option<AttributionData>,
525 },
526 Failure(HTLCFailReason),
527}
528
529impl<'a> Into<Option<&'a HTLCFailReason>> for &'a OutboundHTLCOutcome {
530 fn into(self) -> Option<&'a HTLCFailReason> {
531 match self {
532 OutboundHTLCOutcome::Success { .. } => None,
533 OutboundHTLCOutcome::Failure(ref r) => Some(r),
534 }
535 }
536}
537
538#[derive(Debug)]
539#[cfg_attr(test, derive(Clone, PartialEq))]
540struct OutboundHTLCOutput {
541 htlc_id: u64,
542 amount_msat: u64,
543 cltv_expiry: u32,
544 payment_hash: PaymentHash,
545 state: OutboundHTLCState,
546 source: HTLCSource,
547 blinding_point: Option<PublicKey>,
548 skimmed_fee_msat: Option<u64>,
549 send_timestamp: Option<Duration>,
550 hold_htlc: Option<()>,
551 accountable: bool,
552}
553
554#[derive(Debug)]
556#[cfg_attr(test, derive(Clone, PartialEq))]
557enum HTLCUpdateAwaitingACK {
558 AddHTLC {
559 amount_msat: u64,
562 cltv_expiry: u32,
563 payment_hash: PaymentHash,
564 source: HTLCSource,
565 onion_routing_packet: msgs::OnionPacket,
566 skimmed_fee_msat: Option<u64>,
568 blinding_point: Option<PublicKey>,
569 hold_htlc: Option<()>,
570 accountable: bool,
571 },
572 ClaimHTLC {
573 payment_preimage: PaymentPreimage,
574 attribution_data: Option<AttributionData>,
575 htlc_id: u64,
576 },
577 FailHTLC {
578 htlc_id: u64,
579 err_packet: msgs::OnionErrorPacket,
580 },
581 FailMalformedHTLC {
582 htlc_id: u64,
583 failure_code: u16,
584 sha256_of_onion: [u8; 32],
585 },
586}
587
588macro_rules! define_state_flags {
589 ($flag_type_doc: expr, $flag_type: ident, [$(($flag_doc: expr, $flag: ident, $value: expr, $get: ident, $set: ident, $clear: ident)),*], $extra_flags: expr) => {
590 #[doc = $flag_type_doc]
591 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq)]
592 struct $flag_type(u32);
593
594 impl $flag_type {
595 $(
596 #[doc = $flag_doc]
597 const $flag: $flag_type = $flag_type($value);
598 )*
599
600 #[allow(unused)]
602 const ALL: $flag_type = Self($(Self::$flag.0 | )* $extra_flags);
603
604 #[allow(unused)]
605 fn new() -> Self { Self(0) }
606
607 #[allow(unused)]
608 fn from_u32(flags: u32) -> Result<Self, ()> {
609 if flags & !Self::ALL.0 != 0 {
610 Err(())
611 } else {
612 Ok($flag_type(flags))
613 }
614 }
615
616 #[allow(unused)]
617 fn is_empty(&self) -> bool { self.0 == 0 }
618 #[allow(unused)]
619 fn is_set(&self, flag: Self) -> bool { *self & flag == flag }
620 #[allow(unused)]
621 fn set(&mut self, flag: Self) { *self |= flag }
622 #[allow(unused)]
623 fn clear(&mut self, flag: Self) -> Self { self.0 &= !flag.0; *self }
624 }
625
626 $(
627 define_state_flags!($flag_type, Self::$flag, $get, $set, $clear);
628 )*
629
630 impl core::ops::BitOr for $flag_type {
631 type Output = Self;
632 fn bitor(self, rhs: Self) -> Self::Output { Self(self.0 | rhs.0) }
633 }
634 impl core::ops::BitOrAssign for $flag_type {
635 fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; }
636 }
637 impl core::ops::BitAnd for $flag_type {
638 type Output = Self;
639 fn bitand(self, rhs: Self) -> Self::Output { Self(self.0 & rhs.0) }
640 }
641 impl core::ops::BitAndAssign for $flag_type {
642 fn bitand_assign(&mut self, rhs: Self) { self.0 &= rhs.0; }
643 }
644 };
645 ($flag_type_doc: expr, $flag_type: ident, $flags: tt) => {
646 define_state_flags!($flag_type_doc, $flag_type, $flags, 0);
647 };
648 ($flag_type: ident, $flag: expr, $get: ident, $set: ident, $clear: ident) => {
649 impl $flag_type {
650 #[allow(unused)]
651 fn $get(&self) -> bool { self.is_set($flag_type::new() | $flag) }
652 #[allow(unused)]
653 fn $set(&mut self) { self.set($flag_type::new() | $flag) }
654 #[allow(unused)]
655 fn $clear(&mut self) -> Self { self.clear($flag_type::new() | $flag) }
656 }
657 };
658 ($flag_type_doc: expr, FUNDED_STATE, $flag_type: ident, $flags: tt) => {
659 define_state_flags!($flag_type_doc, $flag_type, $flags, FundedStateFlags::ALL.0);
660
661 define_state_flags!($flag_type, FundedStateFlags::PEER_DISCONNECTED,
662 is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected);
663 define_state_flags!($flag_type, FundedStateFlags::MONITOR_UPDATE_IN_PROGRESS,
664 is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress);
665 define_state_flags!($flag_type, FundedStateFlags::REMOTE_SHUTDOWN_SENT,
666 is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent);
667 define_state_flags!($flag_type, FundedStateFlags::LOCAL_SHUTDOWN_SENT,
668 is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent);
669
670 impl core::ops::BitOr<FundedStateFlags> for $flag_type {
671 type Output = Self;
672 fn bitor(self, rhs: FundedStateFlags) -> Self::Output { Self(self.0 | rhs.0) }
673 }
674 impl core::ops::BitOrAssign<FundedStateFlags> for $flag_type {
675 fn bitor_assign(&mut self, rhs: FundedStateFlags) { self.0 |= rhs.0; }
676 }
677 impl core::ops::BitAnd<FundedStateFlags> for $flag_type {
678 type Output = Self;
679 fn bitand(self, rhs: FundedStateFlags) -> Self::Output { Self(self.0 & rhs.0) }
680 }
681 impl core::ops::BitAndAssign<FundedStateFlags> for $flag_type {
682 fn bitand_assign(&mut self, rhs: FundedStateFlags) { self.0 &= rhs.0; }
683 }
684 impl PartialEq<FundedStateFlags> for $flag_type {
685 fn eq(&self, other: &FundedStateFlags) -> bool { self.0 == other.0 }
686 }
687 impl From<FundedStateFlags> for $flag_type {
688 fn from(flags: FundedStateFlags) -> Self { Self(flags.0) }
689 }
690 };
691}
692
693mod state_flags {
696 pub const OUR_INIT_SENT: u32 = 1 << 0;
697 pub const THEIR_INIT_SENT: u32 = 1 << 1;
698 pub const FUNDING_NEGOTIATED: u32 = 1 << 2;
699 pub const AWAITING_CHANNEL_READY: u32 = 1 << 3;
700 pub const THEIR_CHANNEL_READY: u32 = 1 << 4;
701 pub const OUR_CHANNEL_READY: u32 = 1 << 5;
702 pub const CHANNEL_READY: u32 = 1 << 6;
703 pub const PEER_DISCONNECTED: u32 = 1 << 7;
704 pub const MONITOR_UPDATE_IN_PROGRESS: u32 = 1 << 8;
705 pub const AWAITING_REMOTE_REVOKE: u32 = 1 << 9;
706 pub const REMOTE_SHUTDOWN_SENT: u32 = 1 << 10;
707 pub const LOCAL_SHUTDOWN_SENT: u32 = 1 << 11;
708 pub const SHUTDOWN_COMPLETE: u32 = 1 << 12;
709 pub const WAITING_FOR_BATCH: u32 = 1 << 13;
710 pub const LOCAL_STFU_SENT: u32 = 1 << 14;
711 pub const REMOTE_STFU_SENT: u32 = 1 << 15;
712 pub const QUIESCENT: u32 = 1 << 16;
713}
714
715define_state_flags!(
716 "Flags that apply to all [`ChannelState`] variants in which the channel is funded.",
717 FundedStateFlags, [
718 ("Indicates the remote side is considered \"disconnected\" and no updates are allowed \
719 until after we've done a `channel_reestablish` dance.", PEER_DISCONNECTED, state_flags::PEER_DISCONNECTED,
720 is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected),
721 ("Indicates the user has told us a `ChannelMonitor` update is pending async persistence \
722 somewhere and we should pause sending any outbound messages until they've managed to \
723 complete it.", MONITOR_UPDATE_IN_PROGRESS, state_flags::MONITOR_UPDATE_IN_PROGRESS,
724 is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress),
725 ("Indicates we received a `shutdown` message from the remote end. If set, they may not add \
726 any new HTLCs to the channel, and we are expected to respond with our own `shutdown` \
727 message when possible.", REMOTE_SHUTDOWN_SENT, state_flags::REMOTE_SHUTDOWN_SENT,
728 is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent),
729 ("Indicates we sent a `shutdown` message. At this point, we may not add any new HTLCs to \
730 the channel.", LOCAL_SHUTDOWN_SENT, state_flags::LOCAL_SHUTDOWN_SENT,
731 is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent)
732 ]
733);
734
735define_state_flags!(
736 "Flags that only apply to [`ChannelState::NegotiatingFunding`].",
737 NegotiatingFundingFlags, [
738 ("Indicates we have (or are prepared to) send our `open_channel`/`accept_channel` message.",
739 OUR_INIT_SENT, state_flags::OUR_INIT_SENT, is_our_init_sent, set_our_init_sent, clear_our_init_sent),
740 ("Indicates we have received their `open_channel`/`accept_channel` message.",
741 THEIR_INIT_SENT, state_flags::THEIR_INIT_SENT, is_their_init_sent, set_their_init_sent, clear_their_init_sent)
742 ]
743);
744
745define_state_flags!(
746 "Flags that only apply to [`ChannelState::FundingNegotiated`].",
747 FUNDED_STATE,
748 FundingNegotiatedFlags,
749 []
750);
751
752define_state_flags!(
753 "Flags that only apply to [`ChannelState::AwaitingChannelReady`].",
754 FUNDED_STATE, AwaitingChannelReadyFlags, [
755 ("Indicates they sent us a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \
756 `OUR_CHANNEL_READY` are set, our state moves on to `ChannelReady`.",
757 THEIR_CHANNEL_READY, state_flags::THEIR_CHANNEL_READY,
758 is_their_channel_ready, set_their_channel_ready, clear_their_channel_ready),
759 ("Indicates we sent them a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \
760 `OUR_CHANNEL_READY` are set, our state moves on to `ChannelReady`.",
761 OUR_CHANNEL_READY, state_flags::OUR_CHANNEL_READY,
762 is_our_channel_ready, set_our_channel_ready, clear_our_channel_ready),
763 ("Indicates the channel was funded in a batch and the broadcast of the funding transaction \
764 is being held until all channels in the batch have received `funding_signed` and have \
765 their monitors persisted.", WAITING_FOR_BATCH, state_flags::WAITING_FOR_BATCH,
766 is_waiting_for_batch, set_waiting_for_batch, clear_waiting_for_batch)
767 ]
768);
769
770define_state_flags!(
771 "Flags that only apply to [`ChannelState::ChannelReady`].",
772 FUNDED_STATE, ChannelReadyFlags, [
773 ("Indicates that we have sent a `commitment_signed` but are awaiting the responding \
774 `revoke_and_ack` message. During this period, we can't generate new `commitment_signed` \
775 messages as we'd be unable to determine which HTLCs they included in their `revoke_and_ack` \
776 implicit ACK, so instead we have to hold them away temporarily to be sent later.",
777 AWAITING_REMOTE_REVOKE, state_flags::AWAITING_REMOTE_REVOKE,
778 is_awaiting_remote_revoke, set_awaiting_remote_revoke, clear_awaiting_remote_revoke),
779 ("Indicates we have sent a `stfu` message to the counterparty. This message can only be sent \
780 if `REMOTE_STFU_SENT` is set, or a `QuiescentAction` is pending. Shutdown requests are \
781 rejected if this flag is set.",
782 LOCAL_STFU_SENT, state_flags::LOCAL_STFU_SENT,
783 is_local_stfu_sent, set_local_stfu_sent, clear_local_stfu_sent),
784 ("Indicates we have received a `stfu` message from the counterparty. Shutdown requests are \
785 rejected if this flag is set.",
786 REMOTE_STFU_SENT, state_flags::REMOTE_STFU_SENT,
787 is_remote_stfu_sent, set_remote_stfu_sent, clear_remote_stfu_sent),
788 ("Indicates the quiescence handshake has completed and the channel is now quiescent. \
789 Updates are not allowed while this flag is set, and any outbound updates will go \
790 directly into the holding cell.",
791 QUIESCENT, state_flags::QUIESCENT,
792 is_quiescent, set_quiescent, clear_quiescent)
793 ]
794);
795
796#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq)]
799enum ChannelState {
800 NegotiatingFunding(NegotiatingFundingFlags),
802 FundingNegotiated(FundingNegotiatedFlags),
810 AwaitingChannelReady(AwaitingChannelReadyFlags),
813 ChannelReady(ChannelReadyFlags),
816 ShutdownComplete,
819}
820
821macro_rules! impl_state_flag {
822 ($get: ident, $set: ident, $clear: ident, [$($state: ident),+]) => {
823 #[allow(unused)]
824 fn $get(&self) -> bool {
825 match self {
826 $(
827 ChannelState::$state(flags) => flags.$get(),
828 )*
829 _ => false,
830 }
831 }
832 #[allow(unused)]
833 fn $set(&mut self) {
834 match self {
835 $(
836 ChannelState::$state(flags) => flags.$set(),
837 )*
838 _ => debug_assert!(false, "Attempted to set flag on unexpected ChannelState"),
839 }
840 }
841 #[allow(unused)]
842 fn $clear(&mut self) {
843 match self {
844 $(
845 ChannelState::$state(flags) => { let _ = flags.$clear(); },
846 )*
847 _ => debug_assert!(false, "Attempted to clear flag on unexpected ChannelState"),
848 }
849 }
850 };
851 ($get: ident, $set: ident, $clear: ident, FUNDED_STATES) => {
852 impl_state_flag!($get, $set, $clear, [FundingNegotiated, AwaitingChannelReady, ChannelReady]);
853 };
854 ($get: ident, $set: ident, $clear: ident, $state: ident) => {
855 impl_state_flag!($get, $set, $clear, [$state]);
856 };
857}
858
859impl ChannelState {
860 #[rustfmt::skip]
861 fn from_u32(state: u32) -> Result<Self, ()> {
862 match state {
863 state_flags::SHUTDOWN_COMPLETE => Ok(ChannelState::ShutdownComplete),
864 val => {
865 if val & state_flags::FUNDING_NEGOTIATED == state_flags::FUNDING_NEGOTIATED {
866 FundingNegotiatedFlags::from_u32(val & !state_flags::FUNDING_NEGOTIATED)
867 .map(|flags| ChannelState::FundingNegotiated(flags))
868 } else if val & state_flags::AWAITING_CHANNEL_READY == state_flags::AWAITING_CHANNEL_READY {
869 AwaitingChannelReadyFlags::from_u32(val & !state_flags::AWAITING_CHANNEL_READY)
870 .map(|flags| ChannelState::AwaitingChannelReady(flags))
871 } else if val & state_flags::CHANNEL_READY == state_flags::CHANNEL_READY {
872 ChannelReadyFlags::from_u32(val & !state_flags::CHANNEL_READY)
873 .map(|flags| ChannelState::ChannelReady(flags))
874 } else if let Ok(flags) = NegotiatingFundingFlags::from_u32(val) {
875 Ok(ChannelState::NegotiatingFunding(flags))
876 } else {
877 Err(())
878 }
879 },
880 }
881 }
882
883 fn to_u32(self) -> u32 {
884 match self {
885 ChannelState::NegotiatingFunding(flags) => flags.0,
886 ChannelState::FundingNegotiated(flags) => state_flags::FUNDING_NEGOTIATED | flags.0,
887 ChannelState::AwaitingChannelReady(flags) => {
888 state_flags::AWAITING_CHANNEL_READY | flags.0
889 },
890 ChannelState::ChannelReady(flags) => state_flags::CHANNEL_READY | flags.0,
891 ChannelState::ShutdownComplete => state_flags::SHUTDOWN_COMPLETE,
892 }
893 }
894
895 fn is_both_sides_shutdown(&self) -> bool {
896 self.is_local_shutdown_sent() && self.is_remote_shutdown_sent()
897 }
898
899 fn with_funded_state_flags_mask(&self) -> FundedStateFlags {
900 match self {
901 ChannelState::AwaitingChannelReady(flags) => {
902 FundedStateFlags((*flags & FundedStateFlags::ALL).0)
903 },
904 ChannelState::ChannelReady(flags) => {
905 FundedStateFlags((*flags & FundedStateFlags::ALL).0)
906 },
907 _ => FundedStateFlags::new(),
908 }
909 }
910
911 #[rustfmt::skip]
912 fn can_generate_new_commitment(&self) -> bool {
913 match self {
914 ChannelState::ChannelReady(flags) =>
915 !flags.is_set(ChannelReadyFlags::AWAITING_REMOTE_REVOKE) &&
916 !flags.is_set(ChannelReadyFlags::LOCAL_STFU_SENT) &&
917 !flags.is_set(ChannelReadyFlags::QUIESCENT) &&
918 !flags.is_set(FundedStateFlags::MONITOR_UPDATE_IN_PROGRESS.into()) &&
919 !flags.is_set(FundedStateFlags::PEER_DISCONNECTED.into()),
920 _ => {
921 debug_assert!(false, "Can only generate new commitment within ChannelReady");
922 false
923 },
924 }
925 }
926
927 impl_state_flag!(
928 is_peer_disconnected,
929 set_peer_disconnected,
930 clear_peer_disconnected,
931 FUNDED_STATES
932 );
933 impl_state_flag!(
934 is_monitor_update_in_progress,
935 set_monitor_update_in_progress,
936 clear_monitor_update_in_progress,
937 FUNDED_STATES
938 );
939 impl_state_flag!(
940 is_local_shutdown_sent,
941 set_local_shutdown_sent,
942 clear_local_shutdown_sent,
943 FUNDED_STATES
944 );
945 impl_state_flag!(
946 is_remote_shutdown_sent,
947 set_remote_shutdown_sent,
948 clear_remote_shutdown_sent,
949 FUNDED_STATES
950 );
951 impl_state_flag!(
952 is_our_channel_ready,
953 set_our_channel_ready,
954 clear_our_channel_ready,
955 AwaitingChannelReady
956 );
957 impl_state_flag!(
958 is_their_channel_ready,
959 set_their_channel_ready,
960 clear_their_channel_ready,
961 AwaitingChannelReady
962 );
963 impl_state_flag!(
964 is_waiting_for_batch,
965 set_waiting_for_batch,
966 clear_waiting_for_batch,
967 AwaitingChannelReady
968 );
969 impl_state_flag!(
970 is_awaiting_remote_revoke,
971 set_awaiting_remote_revoke,
972 clear_awaiting_remote_revoke,
973 ChannelReady
974 );
975 impl_state_flag!(is_local_stfu_sent, set_local_stfu_sent, clear_local_stfu_sent, ChannelReady);
976 impl_state_flag!(
977 is_remote_stfu_sent,
978 set_remote_stfu_sent,
979 clear_remote_stfu_sent,
980 ChannelReady
981 );
982 impl_state_flag!(is_quiescent, set_quiescent, clear_quiescent, ChannelReady);
983}
984
985pub const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
986
987pub const DEFAULT_MAX_HTLCS: u16 = 50;
988
989pub const ANCHOR_OUTPUT_VALUE_SATOSHI: u64 = 330;
990
991pub const MAX_IN_FLIGHT_PERCENT_LEGACY: u8 = 10;
996
997pub const MAX_FUNDING_SATOSHIS_NO_WUMBO: u64 = (1 << 24) - 1;
1001
1002pub const TOTAL_BITCOIN_SUPPLY_SATOSHIS: u64 = 21_000_000 * 1_0000_0000;
1004
1005pub const MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS: u64 = 546;
1011
1012pub const MAX_LEGACY_CHAN_DUST_LIMIT_SATOSHIS: u64 = MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS;
1014
1015pub const MAX_CHAN_DUST_LIMIT_SATOSHIS: u64 = 10_000;
1017
1018pub const MIN_CHAN_DUST_LIMIT_SATOSHIS: u64 = 354;
1026
1027pub const MIN_THEIR_CHAN_RESERVE_SATOSHIS: u64 = 1000;
1029
1030pub const MIN_CHANNEL_VALUE_SATOSHIS: u64 = 1000;
1032
1033pub(super) enum ChannelError {
1037 Ignore(String),
1038 Warn(String),
1039 WarnAndDisconnect(String),
1040 Abort(AbortReason),
1041 Close((String, ClosureReason)),
1042 SendError(String),
1043}
1044
1045impl fmt::Debug for ChannelError {
1046 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1047 match self {
1048 &ChannelError::Ignore(ref e) => write!(f, "Ignore: {}", e),
1049 &ChannelError::Warn(ref e) => write!(f, "Warn: {}", e),
1050 &ChannelError::WarnAndDisconnect(ref e) => {
1051 write!(f, "Disconnecting with warning: {}", e)
1052 },
1053 &ChannelError::Abort(ref reason) => write!(f, "Abort: {}", reason),
1054 &ChannelError::Close((ref e, _)) => write!(f, "Close: {}", e),
1055 &ChannelError::SendError(ref e) => write!(f, "Not Found: {}", e),
1056 }
1057 }
1058}
1059
1060impl fmt::Display for ChannelError {
1061 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1062 match self {
1063 &ChannelError::Ignore(ref e) => write!(f, "{}", e),
1064 &ChannelError::Warn(ref e) => write!(f, "{}", e),
1065 &ChannelError::WarnAndDisconnect(ref e) => write!(f, "{}", e),
1066 &ChannelError::Abort(ref reason) => write!(f, "{}", reason),
1067 &ChannelError::Close((ref e, _)) => write!(f, "{}", e),
1068 &ChannelError::SendError(ref e) => write!(f, "{}", e),
1069 }
1070 }
1071}
1072
1073impl ChannelError {
1074 pub(super) fn close(err: String) -> Self {
1075 ChannelError::Close((err.clone(), ClosureReason::ProcessingError { err }))
1076 }
1077}
1078
1079pub(super) struct WithChannelContext<'a, L: Logger> {
1080 pub logger: &'a L,
1081 pub peer_id: Option<PublicKey>,
1082 pub channel_id: Option<ChannelId>,
1083 pub payment_hash: Option<PaymentHash>,
1084}
1085
1086impl<'a, L: Logger> Logger for WithChannelContext<'a, L> {
1087 fn log(&self, mut record: Record) {
1088 record.peer_id = self.peer_id;
1089 record.channel_id = self.channel_id;
1090 record.payment_hash = self.payment_hash;
1091 self.logger.log(record)
1092 }
1093}
1094
1095impl<'a, 'b, L: Logger> WithChannelContext<'a, L> {
1096 pub(super) fn from<S: SignerProvider>(
1097 logger: &'a L, context: &'b ChannelContext<S>, payment_hash: Option<PaymentHash>,
1098 ) -> Self {
1099 WithChannelContext {
1100 logger,
1101 peer_id: Some(context.counterparty_node_id),
1102 channel_id: Some(context.channel_id),
1103 payment_hash,
1104 }
1105 }
1106}
1107
1108macro_rules! secp_check {
1109 ($res: expr, $err: expr) => {
1110 match $res {
1111 Ok(thing) => thing,
1112 Err(_) => return Err(ChannelError::close($err)),
1113 }
1114 };
1115}
1116
1117#[derive(Clone, Copy, PartialEq, Debug)]
1123pub(super) enum ChannelUpdateStatus {
1124 Enabled,
1126 DisabledStaged(u8),
1128 EnabledStaged(u8),
1130 Disabled,
1132}
1133
1134#[cfg_attr(test, derive(Debug))]
1136#[derive(PartialEq)]
1137pub enum AnnouncementSigsState {
1138 NotSent,
1141 MessageSent,
1144 Committed,
1150 PeerReceived,
1153}
1154
1155struct CommitmentData<'a> {
1157 tx: CommitmentTransaction,
1158 htlcs_included: Vec<(HTLCOutputInCommitment, Option<&'a HTLCSource>)>, outbound_htlc_preimages: Vec<PaymentPreimage>, inbound_htlc_preimages: Vec<PaymentPreimage>, }
1162
1163#[derive(Debug, PartialEq)]
1165pub(crate) struct CommitmentStats {
1166 pub commit_tx_fee_sat: u64,
1168 pub local_balance_before_fee_msat: u64,
1170 pub remote_balance_before_fee_msat: u64,
1172}
1173
1174enum UpdateFulfillFetch {
1177 NewClaim { monitor_update: ChannelMonitorUpdate, htlc_value_msat: u64, update_blocked: bool },
1178 DuplicateClaim {},
1179}
1180
1181pub enum UpdateFulfillCommitFetch {
1183 NewClaim {
1187 monitor_update: ChannelMonitorUpdate,
1189 htlc_value_msat: u64,
1191 },
1192 DuplicateClaim {},
1195}
1196
1197pub(super) struct InteractiveTxMsgError {
1199 pub(super) err: ChannelError,
1201 pub(super) splice_funding_failed: Option<SpliceFundingFailed>,
1204 pub(super) negotiation_failure_reason: Option<NegotiationFailureReason>,
1206}
1207
1208impl InteractiveTxMsgError {
1209 fn new(err: ChannelError, splice_funding_failed: Option<SpliceFundingFailed>) -> Self {
1210 Self { err, splice_funding_failed, negotiation_failure_reason: None }
1211 }
1212
1213 fn with_negotiation_failure_reason(mut self, reason: NegotiationFailureReason) -> Self {
1214 self.negotiation_failure_reason = Some(reason);
1215 self
1216 }
1217
1218 pub(super) fn into_parts(
1219 self,
1220 ) -> (ChannelError, Option<(SpliceFundingFailed, NegotiationFailureReason)>) {
1221 let Self { err, splice_funding_failed, negotiation_failure_reason } = self;
1222 let splice_failure = splice_funding_failed.map(|splice_funding_failed| {
1223 let reason =
1224 negotiation_failure_reason.unwrap_or_else(|| Self::reason_from_channel_error(&err));
1225 (splice_funding_failed, reason)
1226 });
1227 (err, splice_failure)
1228 }
1229
1230 fn reason_from_channel_error(err: &ChannelError) -> NegotiationFailureReason {
1231 NegotiationFailureReason::NegotiationError { msg: format!("{:?}", err) }
1232 }
1233}
1234
1235pub(super) struct MonitorRestoreUpdates {
1237 pub raa: Option<msgs::RevokeAndACK>,
1238 pub commitment_update: Option<msgs::CommitmentUpdate>,
1240 pub commitment_order: RAACommitmentOrder,
1241 pub accepted_htlcs: Vec<(PendingHTLCInfo, u64)>,
1242 pub failed_htlcs: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
1243 pub finalized_claimed_htlcs: Vec<(HTLCSource, Option<AttributionData>)>,
1244 pub pending_update_adds: Vec<msgs::UpdateAddHTLC>,
1247 pub funding_broadcastable: Option<Transaction>,
1248 pub channel_ready: Option<msgs::ChannelReady>,
1249 pub channel_ready_order: ChannelReadyOrder,
1250 pub announcement_sigs: Option<msgs::AnnouncementSignatures>,
1251 pub funding_tx_signed: Option<FundingTxSigned>,
1252 pub committed_outbound_htlc_sources: Vec<(HTLCPreviousHopData, u64)>,
1256 pub requires_channel_manager_persistence: bool,
1259}
1260
1261pub(super) struct SignerResumeUpdates {
1263 pub commitment_update: Option<msgs::CommitmentUpdate>,
1264 pub revoke_and_ack: Option<msgs::RevokeAndACK>,
1265 pub open_channel: Option<msgs::OpenChannel>,
1266 pub accept_channel: Option<msgs::AcceptChannel>,
1267 pub funding_created: Option<msgs::FundingCreated>,
1268 pub funding_signed: Option<msgs::FundingSigned>,
1269 pub funding_tx_signed: Option<FundingTxSigned>,
1270 pub channel_ready: Option<msgs::ChannelReady>,
1271 pub order: RAACommitmentOrder,
1272 pub closing_signed: Option<msgs::ClosingSigned>,
1273 pub signed_closing_tx: Option<Transaction>,
1274 pub shutdown_result: Option<ShutdownResult>,
1275}
1276
1277pub(super) struct ReestablishResponses {
1279 pub channel_ready: Option<msgs::ChannelReady>,
1280 pub channel_ready_order: ChannelReadyOrder,
1281 pub raa: Option<msgs::RevokeAndACK>,
1282 pub commitment_update: Option<msgs::CommitmentUpdate>,
1283 pub commitment_order: RAACommitmentOrder,
1284 pub announcement_sigs: Option<msgs::AnnouncementSignatures>,
1285 pub shutdown_msg: Option<msgs::Shutdown>,
1286 pub tx_signatures: Option<(TxSignaturesOrder, msgs::TxSignatures)>,
1287 pub tx_abort: Option<msgs::TxAbort>,
1288 pub splice_locked: Option<msgs::SpliceLocked>,
1289 pub inferred_splice_locked: Option<msgs::SpliceLocked>,
1290}
1291
1292pub(super) enum ReconnectionMsg {
1294 Reestablish(msgs::ChannelReestablish),
1295 Open(OpenChannelMessage),
1296 None,
1297}
1298
1299#[must_use]
1301pub(crate) struct ShutdownResult {
1302 pub(crate) closure_reason: ClosureReason,
1303 pub(crate) monitor_update: Option<(PublicKey, OutPoint, ChannelId, ChannelMonitorUpdate)>,
1305 pub(crate) dropped_outbound_htlcs: Vec<(HTLCSource, PaymentHash, PublicKey, ChannelId)>,
1307 pub(crate) unbroadcasted_batch_funding_txid: Option<Txid>,
1310 pub(crate) channel_id: ChannelId,
1311 pub(crate) user_channel_id: u128,
1312 pub(crate) channel_capacity_satoshis: u64,
1313 pub(crate) counterparty_node_id: PublicKey,
1314 pub(crate) is_manual_broadcast: bool,
1315 pub(crate) unbroadcasted_funding_tx: Option<Transaction>,
1316 pub(crate) channel_funding_txo: Option<OutPoint>,
1317 pub(crate) last_local_balance_msat: u64,
1318 pub(crate) splice_funding_failed: Vec<SpliceFundingFailed>,
1322 pub(crate) splice_funding_negotiated: Option<SpliceFundingNegotiated>,
1324}
1325
1326pub(crate) struct DisconnectResult {
1328 pub(crate) is_resumable: bool,
1329 pub(crate) splice_funding_failed: Option<SpliceFundingFailed>,
1332}
1333
1334#[derive(Debug, Copy, Clone)]
1338struct HolderCommitmentPoint {
1339 next_transaction_number: u64,
1340 current_point: Option<PublicKey>,
1341 next_point: PublicKey,
1342 pending_next_point: Option<PublicKey>,
1343
1344 previous_revoked_point: Option<PublicKey>,
1349 last_revoked_point: Option<PublicKey>,
1350}
1351
1352impl HolderCommitmentPoint {
1353 #[rustfmt::skip]
1354 pub fn new<S: ChannelSigner>(signer: &S, secp_ctx: &Secp256k1<secp256k1::All>) -> Option<Self> {
1355 Some(HolderCommitmentPoint {
1356 next_transaction_number: INITIAL_COMMITMENT_NUMBER,
1357 previous_revoked_point: None,
1358 last_revoked_point: None,
1359 current_point: None,
1360 next_point: signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, secp_ctx).ok()?,
1361 pending_next_point: signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, secp_ctx).ok(),
1362 })
1363 }
1364
1365 pub fn can_advance(&self) -> bool {
1366 self.pending_next_point.is_some()
1367 }
1368
1369 pub fn previous_revoked_point(&self) -> Option<PublicKey> {
1370 self.previous_revoked_point
1371 }
1372
1373 pub fn last_revoked_point(&self) -> Option<PublicKey> {
1374 self.last_revoked_point
1375 }
1376
1377 pub fn current_transaction_number(&self) -> u64 {
1378 self.next_transaction_number + 1
1379 }
1380
1381 pub fn current_point(&self) -> Option<PublicKey> {
1382 self.current_point
1383 }
1384
1385 pub fn next_transaction_number(&self) -> u64 {
1386 self.next_transaction_number
1387 }
1388
1389 pub fn next_point(&self) -> PublicKey {
1390 self.next_point
1391 }
1392
1393 pub fn try_resolve_pending<S: ChannelSigner, L: Logger>(
1396 &mut self, signer: &S, secp_ctx: &Secp256k1<secp256k1::All>, logger: &L,
1397 ) {
1398 if !self.can_advance() {
1399 let pending_next_point =
1400 signer.get_per_commitment_point(self.next_transaction_number - 1, secp_ctx);
1401 if let Ok(point) = pending_next_point {
1402 log_trace!(
1403 logger,
1404 "Retrieved per-commitment point {} for next advancement",
1405 self.next_transaction_number - 1
1406 );
1407 self.pending_next_point = Some(point);
1408 } else {
1409 log_trace!(
1410 logger,
1411 "Pending per-commitment point {} for next advancement",
1412 self.next_transaction_number - 1
1413 );
1414 }
1415 }
1416 }
1417
1418 pub fn advance<S: ChannelSigner, L: Logger>(
1429 &mut self, signer: &S, secp_ctx: &Secp256k1<secp256k1::All>, logger: &L,
1430 ) -> Result<(), ()> {
1431 if let Some(next_point) = self.pending_next_point {
1432 *self = Self {
1433 next_transaction_number: self.next_transaction_number - 1,
1434 previous_revoked_point: self.last_revoked_point,
1435 last_revoked_point: self.current_point,
1436 current_point: Some(self.next_point),
1437 next_point,
1438 pending_next_point: None,
1439 };
1440
1441 self.try_resolve_pending(signer, secp_ctx, logger);
1442 return Ok(());
1443 }
1444 Err(())
1445 }
1446}
1447
1448#[cfg(any(fuzzing, test, feature = "_test_utils"))]
1460pub const FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE: u64 = 2;
1461#[cfg(not(any(fuzzing, test, feature = "_test_utils")))]
1462pub(crate) const FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE: u64 = 2;
1463
1464pub(crate) const FUNDING_CONF_DEADLINE_BLOCKS: u32 = 2016;
1468
1469pub(crate) const CONCURRENT_INBOUND_HTLC_FEE_BUFFER: u32 = 2;
1479
1480pub(crate) const MIN_AFFORDABLE_HTLC_COUNT: usize = 4;
1484
1485pub(crate) const EXPIRE_PREV_CONFIG_TICKS: usize = 5;
1494
1495pub(crate) const DISCONNECT_PEER_AWAITING_RESPONSE_TICKS: usize = 2;
1500
1501pub(crate) const UNFUNDED_CHANNEL_AGE_LIMIT_TICKS: usize = 60;
1505
1506pub(crate) const COINBASE_MATURITY: u32 = 100;
1508
1509#[cfg(not(test))]
1527pub(crate) const CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY: u32 = 14 * 24 * 6 * 4;
1528
1529#[cfg(test)]
1533pub(crate) const CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY: u32 = 144;
1534
1535#[derive(Debug)]
1536struct PendingChannelMonitorUpdate {
1537 update: ChannelMonitorUpdate,
1538}
1539
1540impl_writeable_tlv_based!(PendingChannelMonitorUpdate, {
1541 (0, update, required),
1542});
1543
1544pub(super) struct Channel<SP: SignerProvider> {
1547 phase: ChannelPhase<SP>,
1548}
1549
1550enum ChannelPhase<SP: SignerProvider> {
1553 Undefined,
1554 UnfundedOutboundV1(OutboundV1Channel<SP>),
1555 UnfundedInboundV1(InboundV1Channel<SP>),
1556 UnfundedV2(PendingV2Channel<SP>),
1557 Funded(FundedChannel<SP>),
1558}
1559
1560impl<SP: SignerProvider> Channel<SP>
1561where
1562 SP::EcdsaSigner: ChannelSigner,
1563{
1564 pub fn context(&self) -> &ChannelContext<SP> {
1565 match &self.phase {
1566 ChannelPhase::Undefined => unreachable!(),
1567 ChannelPhase::Funded(chan) => &chan.context,
1568 ChannelPhase::UnfundedOutboundV1(chan) => &chan.context,
1569 ChannelPhase::UnfundedInboundV1(chan) => &chan.context,
1570 ChannelPhase::UnfundedV2(chan) => &chan.context,
1571 }
1572 }
1573
1574 pub fn context_mut(&mut self) -> &mut ChannelContext<SP> {
1575 match &mut self.phase {
1576 ChannelPhase::Undefined => unreachable!(),
1577 ChannelPhase::Funded(chan) => &mut chan.context,
1578 ChannelPhase::UnfundedOutboundV1(chan) => &mut chan.context,
1579 ChannelPhase::UnfundedInboundV1(chan) => &mut chan.context,
1580 ChannelPhase::UnfundedV2(chan) => &mut chan.context,
1581 }
1582 }
1583
1584 pub fn funding(&self) -> &FundingScope {
1585 match &self.phase {
1586 ChannelPhase::Undefined => unreachable!(),
1587 ChannelPhase::Funded(chan) => &chan.funding,
1588 ChannelPhase::UnfundedOutboundV1(chan) => &chan.funding,
1589 ChannelPhase::UnfundedInboundV1(chan) => &chan.funding,
1590 ChannelPhase::UnfundedV2(chan) => &chan.funding,
1591 }
1592 }
1593
1594 #[cfg(any(test, feature = "_externalize_tests"))]
1595 pub fn funding_mut(&mut self) -> &mut FundingScope {
1596 match &mut self.phase {
1597 ChannelPhase::Undefined => unreachable!(),
1598 ChannelPhase::Funded(chan) => &mut chan.funding,
1599 ChannelPhase::UnfundedOutboundV1(chan) => &mut chan.funding,
1600 ChannelPhase::UnfundedInboundV1(chan) => &mut chan.funding,
1601 ChannelPhase::UnfundedV2(chan) => &mut chan.funding,
1602 }
1603 }
1604
1605 pub fn funding_and_context_mut(&mut self) -> (&FundingScope, &mut ChannelContext<SP>) {
1606 match &mut self.phase {
1607 ChannelPhase::Undefined => unreachable!(),
1608 ChannelPhase::Funded(chan) => (&chan.funding, &mut chan.context),
1609 ChannelPhase::UnfundedOutboundV1(chan) => (&chan.funding, &mut chan.context),
1610 ChannelPhase::UnfundedInboundV1(chan) => (&chan.funding, &mut chan.context),
1611 ChannelPhase::UnfundedV2(chan) => (&chan.funding, &mut chan.context),
1612 }
1613 }
1614
1615 pub fn unfunded_context_mut(&mut self) -> Option<&mut UnfundedChannelContext> {
1616 match &mut self.phase {
1617 ChannelPhase::Undefined => unreachable!(),
1618 ChannelPhase::Funded(_) => {
1619 debug_assert!(false);
1620 None
1621 },
1622 ChannelPhase::UnfundedOutboundV1(chan) => Some(&mut chan.unfunded_context),
1623 ChannelPhase::UnfundedInboundV1(chan) => Some(&mut chan.unfunded_context),
1624 ChannelPhase::UnfundedV2(chan) => Some(&mut chan.unfunded_context),
1625 }
1626 }
1627
1628 pub fn is_funded(&self) -> bool {
1629 matches!(self.phase, ChannelPhase::Funded(_))
1630 }
1631
1632 pub fn as_funded(&self) -> Option<&FundedChannel<SP>> {
1633 if let ChannelPhase::Funded(channel) = &self.phase {
1634 Some(channel)
1635 } else {
1636 None
1637 }
1638 }
1639
1640 pub fn as_funded_mut(&mut self) -> Option<&mut FundedChannel<SP>> {
1641 if let ChannelPhase::Funded(channel) = &mut self.phase {
1642 Some(channel)
1643 } else {
1644 None
1645 }
1646 }
1647
1648 pub fn as_unfunded_outbound_v1_mut(&mut self) -> Option<&mut OutboundV1Channel<SP>> {
1649 if let ChannelPhase::UnfundedOutboundV1(channel) = &mut self.phase {
1650 Some(channel)
1651 } else {
1652 None
1653 }
1654 }
1655
1656 #[cfg(any(test, feature = "_externalize_tests"))]
1657 pub fn is_unfunded_v1(&self) -> bool {
1658 matches!(
1659 self.phase,
1660 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_)
1661 )
1662 }
1663
1664 pub fn ready_to_fund(&self) -> bool {
1668 if !self.funding().is_outbound() {
1669 return false;
1670 }
1671 match self.context().channel_state {
1672 ChannelState::NegotiatingFunding(flags) => {
1673 debug_assert!(matches!(self.phase, ChannelPhase::UnfundedOutboundV1(_)));
1674 flags.is_our_init_sent() && flags.is_their_init_sent()
1675 },
1676 _ => false,
1677 }
1678 }
1679
1680 pub fn into_unfunded_outbound_v1(self) -> Result<OutboundV1Channel<SP>, Self> {
1681 if let ChannelPhase::UnfundedOutboundV1(channel) = self.phase {
1682 Ok(channel)
1683 } else {
1684 Err(self)
1685 }
1686 }
1687
1688 pub fn into_unfunded_inbound_v1(self) -> Result<InboundV1Channel<SP>, Self> {
1689 if let ChannelPhase::UnfundedInboundV1(channel) = self.phase {
1690 Ok(channel)
1691 } else {
1692 Err(self)
1693 }
1694 }
1695
1696 pub fn as_unfunded_v2(&self) -> Option<&PendingV2Channel<SP>> {
1697 if let ChannelPhase::UnfundedV2(channel) = &self.phase {
1698 Some(channel)
1699 } else {
1700 None
1701 }
1702 }
1703
1704 #[rustfmt::skip]
1705 pub fn signer_maybe_unblocked<L: Logger, CBP>(
1706 &mut self, chain_hash: ChainHash, best_block_height: u32, logger: &L, path_for_release_htlc: CBP
1707 ) -> Result<Option<SignerResumeUpdates>, ChannelError> where CBP: Fn(u64) -> BlindedMessagePath {
1708 match &mut self.phase {
1709 ChannelPhase::Undefined => unreachable!(),
1710 ChannelPhase::Funded(chan) => chan.signer_maybe_unblocked(best_block_height, logger, path_for_release_htlc).map(|r| Some(r)),
1711 ChannelPhase::UnfundedOutboundV1(chan) => {
1712 let (open_channel, funding_created) = chan.signer_maybe_unblocked(chain_hash, logger);
1713 Ok(Some(SignerResumeUpdates {
1714 commitment_update: None,
1715 revoke_and_ack: None,
1716 open_channel,
1717 accept_channel: None,
1718 funding_created,
1719 funding_signed: None,
1720 funding_tx_signed: None,
1721 channel_ready: None,
1722 order: chan.context.resend_order.clone(),
1723 closing_signed: None,
1724 signed_closing_tx: None,
1725 shutdown_result: None,
1726 }))
1727 },
1728 ChannelPhase::UnfundedInboundV1(chan) => {
1729 let accept_channel = chan.signer_maybe_unblocked(logger);
1730 Ok(Some(SignerResumeUpdates {
1731 commitment_update: None,
1732 revoke_and_ack: None,
1733 open_channel: None,
1734 accept_channel,
1735 funding_created: None,
1736 funding_signed: None,
1737 funding_tx_signed: None,
1738 channel_ready: None,
1739 order: chan.context.resend_order.clone(),
1740 closing_signed: None,
1741 signed_closing_tx: None,
1742 shutdown_result: None,
1743 }))
1744 },
1745 ChannelPhase::UnfundedV2(_) => Ok(None),
1746 }
1747 }
1748
1749 pub fn peer_disconnected_is_resumable<L: Logger>(&mut self, logger: &L) -> DisconnectResult {
1753 let is_resumable = match &mut self.phase {
1754 ChannelPhase::Undefined => unreachable!(),
1755 ChannelPhase::Funded(chan) => {
1756 chan.remove_uncommitted_htlcs_and_mark_paused(logger).is_ok()
1757 },
1758 ChannelPhase::UnfundedOutboundV1(chan) => chan.is_resumable(),
1765 ChannelPhase::UnfundedInboundV1(_) => false,
1766 ChannelPhase::UnfundedV2(_) => false,
1767 };
1768
1769 let splice_funding_failed = if let ChannelPhase::Funded(chan) = &mut self.phase {
1770 if matches!(chan.context.channel_state, ChannelState::ChannelReady(_)) {
1772 chan.context.channel_state.clear_local_stfu_sent();
1773 chan.context.channel_state.clear_remote_stfu_sent();
1774 if chan.should_reset_pending_splice_state(true) {
1775 let (splice_funding_failed, splice_funding_negotiated) =
1778 chan.reset_pending_splice_state();
1779 debug_assert!(splice_funding_negotiated.is_none());
1780 debug_assert!(!chan.context.channel_state.is_quiescent());
1781 splice_funding_failed
1782 } else if !chan.has_pending_splice_awaiting_signatures() {
1783 chan.exit_quiescence();
1790 None
1791 } else {
1792 if let Some(FundingNegotiation::AwaitingSignatures {
1793 initial_commitment_signed_from_counterparty,
1794 ..
1795 }) = chan
1796 .pending_splice
1797 .as_mut()
1798 .and_then(|pending_splice| pending_splice.funding_negotiation.as_mut())
1799 {
1800 initial_commitment_signed_from_counterparty.take();
1801 }
1802 None
1803 }
1804 } else {
1805 None
1806 }
1807 } else {
1808 None
1809 };
1810
1811 DisconnectResult { is_resumable, splice_funding_failed }
1812 }
1813
1814 #[rustfmt::skip]
1817 pub fn peer_connected_get_handshake<L: Logger>(
1818 &mut self, chain_hash: ChainHash, logger: &L,
1819 ) -> ReconnectionMsg {
1820 match &mut self.phase {
1821 ChannelPhase::Undefined => unreachable!(),
1822 ChannelPhase::Funded(chan) =>
1823 ReconnectionMsg::Reestablish(chan.get_channel_reestablish(logger)),
1824 ChannelPhase::UnfundedOutboundV1(chan) => {
1825 chan.get_open_channel(chain_hash, logger)
1826 .map(|msg| ReconnectionMsg::Open(OpenChannelMessage::V1(msg)))
1827 .unwrap_or(ReconnectionMsg::None)
1828 },
1829 ChannelPhase::UnfundedInboundV1(_) => {
1830 debug_assert!(false);
1834 ReconnectionMsg::None
1835 },
1836 ChannelPhase::UnfundedV2(chan) => {
1837 if chan.funding.is_outbound() {
1838 ReconnectionMsg::Open(OpenChannelMessage::V2(
1839 chan.get_open_channel_v2(chain_hash)
1840 ))
1841 } else {
1842 debug_assert!(false);
1846 ReconnectionMsg::None
1847 }
1848 },
1849 }
1850 }
1851
1852 #[rustfmt::skip]
1853 pub fn maybe_handle_error_without_close<F: FeeEstimator, L: Logger>(
1854 &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
1855 user_config: &UserConfig, their_features: &InitFeatures,
1856 ) -> Result<Option<OpenChannelMessage>, ()> {
1857 match &mut self.phase {
1858 ChannelPhase::Undefined => unreachable!(),
1859 ChannelPhase::Funded(_) => Ok(None),
1860 ChannelPhase::UnfundedOutboundV1(chan) => {
1861 let logger = WithChannelContext::from(logger, &chan.context, None);
1862 chan.maybe_handle_error_without_close(
1863 chain_hash, fee_estimator, &&logger, user_config, their_features,
1864 )
1865 .map(|msg| Some(OpenChannelMessage::V1(msg)))
1866 },
1867 ChannelPhase::UnfundedInboundV1(_) => Ok(None),
1868 ChannelPhase::UnfundedV2(chan) => {
1869 if chan.funding.is_outbound() {
1870 chan.maybe_handle_error_without_close(
1871 chain_hash, fee_estimator, user_config, their_features,
1872 )
1873 .map(|msg| Some(OpenChannelMessage::V2(msg)))
1874 } else {
1875 Ok(None)
1876 }
1877 },
1878 }
1879 }
1880
1881 fn interactive_tx_constructor_mut(&mut self) -> Option<&mut InteractiveTxConstructor> {
1882 match &mut self.phase {
1883 ChannelPhase::UnfundedV2(chan) => chan.interactive_tx_constructor.as_mut(),
1884 ChannelPhase::Funded(chan) => chan.interactive_tx_constructor_mut(),
1885 _ => None,
1886 }
1887 }
1888
1889 fn interactive_tx_constructor_for_message(
1890 &mut self, msg_name: &str,
1891 ) -> Result<&mut InteractiveTxConstructor, InteractiveTxMsgError> {
1892 if matches!(
1893 &self.phase,
1894 ChannelPhase::Funded(chan) if !chan.context.channel_state.is_quiescent()
1895 ) {
1896 return Err(InteractiveTxMsgError::new(
1897 ChannelError::Ignore(format!("Ignoring unexpected {msg_name} while not quiescent")),
1898 None,
1899 ));
1900 }
1901 match self.interactive_tx_constructor_mut() {
1902 Some(interactive_tx_constructor) => Ok(interactive_tx_constructor),
1903 None => Err(InteractiveTxMsgError::new(
1904 ChannelError::WarnAndDisconnect(format!("Received unexpected {msg_name}")),
1905 None,
1906 )),
1907 }
1908 }
1909
1910 fn fail_interactive_tx_negotiation<L: Logger>(
1911 &mut self, reason: AbortReason, logger: &L,
1912 ) -> InteractiveTxMsgError {
1913 let logger = WithChannelContext::from(logger, &self.context(), None);
1914 log_info!(logger, "Failed interactive transaction negotiation: {reason}");
1915
1916 let splice_funding_failed = match &mut self.phase {
1917 ChannelPhase::Undefined => unreachable!(),
1918 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => None,
1919 ChannelPhase::UnfundedV2(pending_v2_channel) => {
1920 pending_v2_channel.interactive_tx_constructor.take();
1921 None
1922 },
1923 ChannelPhase::Funded(funded_channel) => {
1924 if funded_channel.should_reset_pending_splice_state(true) {
1925 let (splice_funding_failed, splice_funding_negotiated) =
1926 funded_channel.reset_pending_splice_state();
1927 debug_assert!(splice_funding_negotiated.is_none());
1928 splice_funding_failed
1929 } else {
1930 debug_assert!(false, "We should never fail an interactive funding negotiation once we're exchanging tx_signatures");
1931 None
1932 }
1933 },
1934 };
1935
1936 InteractiveTxMsgError::new(ChannelError::Abort(reason), splice_funding_failed)
1937 }
1938
1939 pub fn tx_add_input<L: Logger>(
1940 &mut self, msg: &msgs::TxAddInput, logger: &L,
1941 ) -> Result<InteractiveTxMessageSend, InteractiveTxMsgError> {
1942 self.interactive_tx_constructor_for_message("tx_add_input")?
1943 .handle_tx_add_input(msg)
1944 .map_err(|reason| self.fail_interactive_tx_negotiation(reason, logger))
1945 }
1946
1947 pub fn tx_add_output<L: Logger>(
1948 &mut self, msg: &msgs::TxAddOutput, logger: &L,
1949 ) -> Result<InteractiveTxMessageSend, InteractiveTxMsgError> {
1950 self.interactive_tx_constructor_for_message("tx_add_output")?
1951 .handle_tx_add_output(msg)
1952 .map_err(|reason| self.fail_interactive_tx_negotiation(reason, logger))
1953 }
1954
1955 pub fn tx_remove_input<L: Logger>(
1956 &mut self, msg: &msgs::TxRemoveInput, logger: &L,
1957 ) -> Result<InteractiveTxMessageSend, InteractiveTxMsgError> {
1958 self.interactive_tx_constructor_for_message("tx_remove_input")?
1959 .handle_tx_remove_input(msg)
1960 .map_err(|reason| self.fail_interactive_tx_negotiation(reason, logger))
1961 }
1962
1963 pub fn tx_remove_output<L: Logger>(
1964 &mut self, msg: &msgs::TxRemoveOutput, logger: &L,
1965 ) -> Result<InteractiveTxMessageSend, InteractiveTxMsgError> {
1966 self.interactive_tx_constructor_for_message("tx_remove_output")?
1967 .handle_tx_remove_output(msg)
1968 .map_err(|reason| self.fail_interactive_tx_negotiation(reason, logger))
1969 }
1970
1971 pub fn tx_complete<F: FeeEstimator, L: Logger>(
1972 &mut self, msg: &msgs::TxComplete, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
1973 ) -> Result<TxCompleteResult, InteractiveTxMsgError> {
1974 let tx_complete_action = self
1975 .interactive_tx_constructor_for_message("tx_complete")?
1976 .handle_tx_complete(msg)
1977 .map_err(|reason| self.fail_interactive_tx_negotiation(reason, logger))?;
1978
1979 let (interactive_tx_msg_send, negotiation_complete) = match tx_complete_action {
1980 HandleTxCompleteValue::SendTxMessage(interactive_tx_msg_send) => {
1981 (Some(interactive_tx_msg_send), None)
1982 },
1983 HandleTxCompleteValue::NegotiationComplete(
1984 interactive_tx_msg_send,
1985 funding_outpoint,
1986 ) => (interactive_tx_msg_send, Some(funding_outpoint)),
1987 };
1988
1989 let funding_outpoint = if let Some(funding_outpoint) = negotiation_complete {
1990 funding_outpoint
1991 } else {
1992 return Ok(TxCompleteResult {
1993 interactive_tx_msg_send,
1994 event_unsigned_tx: None,
1995 funding_tx_signed: None,
1996 });
1997 };
1998
1999 self.funding_tx_constructed(funding_outpoint)
2000 .map_err(|abort_reason| self.fail_interactive_tx_negotiation(abort_reason, logger))?;
2001
2002 let signing_session = self
2003 .context()
2004 .interactive_tx_signing_session
2005 .as_ref()
2006 .expect("The signing session must have been initialized in funding_tx_constructed");
2007 let has_local_contribution = signing_session.has_local_contribution();
2008
2009 let event_unsigned_tx =
2010 has_local_contribution.then(|| signing_session.unsigned_tx().tx().clone());
2011
2012 let funding_tx_signed = if !has_local_contribution {
2013 let funding_txid = signing_session.unsigned_tx().tx().compute_txid();
2014 self.funding_transaction_signed(funding_txid, vec![], 0, fee_estimator, logger)
2015 .map(Some)
2016 .map_err(|err| {
2017 log_error!(
2018 logger,
2019 "Failed signing funding transaction without local contribution: {err:?}"
2020 );
2021 self.fail_interactive_tx_negotiation(
2022 AbortReason::InternalError("Signing failed"),
2023 logger,
2024 )
2025 })?
2026 } else {
2027 None
2028 };
2029
2030 Ok(TxCompleteResult { interactive_tx_msg_send, event_unsigned_tx, funding_tx_signed })
2031 }
2032
2033 pub fn tx_abort<L: Logger>(
2034 &mut self, msg: &msgs::TxAbort, logger: &L,
2035 ) -> Result<(Option<msgs::TxAbort>, Option<SpliceFundingFailed>), ChannelError> {
2036 let (should_ack, splice_funding_failed) = match &mut self.phase {
2042 ChannelPhase::Undefined => unreachable!(),
2043 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2044 let err = "Got an unexpected tx_abort message: This is an unfunded channel created with V1 channel establishment";
2045 return Err(ChannelError::Warn(err.into()));
2046 },
2047 ChannelPhase::UnfundedV2(pending_v2_channel) => {
2048 let had_constructor =
2049 pending_v2_channel.interactive_tx_constructor.take().is_some();
2050 (had_constructor, None)
2051 },
2052 ChannelPhase::Funded(funded_channel) => {
2053 if funded_channel.has_pending_splice_awaiting_signatures()
2054 && funded_channel
2055 .context()
2056 .interactive_tx_signing_session
2057 .as_ref()
2058 .expect("We have a pending splice awaiting signatures")
2059 .has_received_commitment_signed()
2060 {
2061 return Err(ChannelError::close(
2067 "Received tx_abort while awaiting tx_signatures exchange".to_owned(),
2068 ));
2069 }
2070 if funded_channel.should_reset_pending_splice_state(false) {
2071 let has_funding_negotiation = funded_channel
2072 .pending_splice
2073 .as_ref()
2074 .map(|pending_splice| pending_splice.funding_negotiation.is_some())
2075 .unwrap_or(false);
2076 debug_assert!(has_funding_negotiation);
2077 let (splice_funding_failed, splice_funding_negotiated) =
2078 funded_channel.reset_pending_splice_state();
2079 debug_assert!(splice_funding_negotiated.is_none());
2080 (true, splice_funding_failed)
2081 } else {
2082 (false, None)
2085 }
2086 },
2087 };
2088
2089 let tx_abort = should_ack.then(|| {
2090 let logger = WithChannelContext::from(logger, &self.context(), None);
2091 let reason = String::from_utf8_lossy(&msg.data);
2092 log_info!(
2093 logger,
2094 "Counterparty failed interactive transaction negotiation: {}",
2095 log_msg!(reason)
2096 );
2097 msgs::TxAbort {
2098 channel_id: msg.channel_id,
2099 data: "Acknowledged tx_abort".to_string().into_bytes(),
2100 }
2101 });
2102
2103 Ok((tx_abort, splice_funding_failed))
2104 }
2105
2106 #[rustfmt::skip]
2107 pub fn funding_signed<L: Logger>(
2108 &mut self, msg: &msgs::FundingSigned, best_block: BlockLocator, signer_provider: &SP, logger: &L
2109 ) -> Result<(&mut FundedChannel<SP>, ChannelMonitor<SP::EcdsaSigner>), ChannelError> {
2110 let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined);
2111 let result = if let ChannelPhase::UnfundedOutboundV1(chan) = phase {
2112 let channel_state = chan.context.channel_state;
2113 let logger = WithChannelContext::from(logger, &chan.context, None);
2114 match chan.funding_signed(msg, best_block, signer_provider, &&logger) {
2115 Ok((chan, monitor)) => {
2116 debug_assert!(matches!(chan.context.channel_state, ChannelState::AwaitingChannelReady(_)));
2117 self.phase = ChannelPhase::Funded(chan);
2118 Ok(monitor)
2119 },
2120 Err((chan, e)) => {
2121 debug_assert_eq!(chan.context.channel_state, channel_state);
2122 self.phase = ChannelPhase::UnfundedOutboundV1(chan);
2123 Err(e)
2124 },
2125 }
2126 } else {
2127 self.phase = phase;
2128 Err(ChannelError::SendError("Failed to find corresponding UnfundedOutboundV1 channel".to_owned()))
2129 };
2130
2131 debug_assert!(!matches!(self.phase, ChannelPhase::Undefined));
2132 result.map(|monitor| (self.as_funded_mut().expect("Channel should be funded"), monitor))
2133 }
2134
2135 fn funding_tx_constructed(&mut self, funding_outpoint: OutPoint) -> Result<(), AbortReason> {
2136 let interactive_tx_constructor = match &mut self.phase {
2137 ChannelPhase::UnfundedV2(chan) => {
2138 debug_assert_eq!(
2139 chan.context.channel_state,
2140 ChannelState::NegotiatingFunding(
2141 NegotiatingFundingFlags::OUR_INIT_SENT
2142 | NegotiatingFundingFlags::THEIR_INIT_SENT
2143 ),
2144 );
2145 chan.context.assert_no_commitment_advancement(
2146 chan.unfunded_context.transaction_number(),
2147 "initial commitment_signed",
2148 );
2149
2150 chan.context.channel_state =
2151 ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
2152 chan.funding.channel_transaction_parameters.funding_outpoint =
2153 Some(funding_outpoint);
2154
2155 chan.interactive_tx_constructor
2156 .take()
2157 .expect("PendingV2Channel::interactive_tx_constructor should be set")
2158 },
2159 ChannelPhase::Funded(chan) => {
2160 if let Some(pending_splice) = chan.pending_splice.as_mut() {
2161 let funding_negotiation = pending_splice.funding_negotiation.take();
2162 if let Some(FundingNegotiation::ConstructingTransaction {
2163 mut funding,
2164 funding_feerate_sat_per_1000_weight,
2165 interactive_tx_constructor,
2166 }) = funding_negotiation
2167 {
2168 let is_initiator = interactive_tx_constructor.is_initiator();
2169 funding.channel_transaction_parameters.funding_outpoint =
2170 Some(funding_outpoint);
2171 pending_splice.funding_negotiation =
2172 Some(FundingNegotiation::AwaitingSignatures {
2173 is_initiator,
2174 funding,
2175 funding_feerate_sat_per_1000_weight,
2176 initial_commitment_signed_from_counterparty: None,
2177 });
2178 interactive_tx_constructor
2179 } else {
2180 pending_splice.funding_negotiation = funding_negotiation;
2182 return Err(AbortReason::InternalError(
2183 "Got a tx_complete message in an invalid state",
2184 ));
2185 }
2186 } else {
2187 return Err(AbortReason::InternalError(
2188 "Got a tx_complete message in an invalid state",
2189 ));
2190 }
2191 },
2192 _ => {
2193 debug_assert!(false);
2194 return Err(AbortReason::InternalError(
2195 "Got a tx_complete message in an invalid phase",
2196 ));
2197 },
2198 };
2199
2200 let signing_session = interactive_tx_constructor.into_signing_session();
2201 self.context_mut().interactive_tx_signing_session = Some(signing_session);
2202 Ok(())
2203 }
2204
2205 pub fn funding_transaction_signed<F: FeeEstimator, L: Logger>(
2206 &mut self, funding_txid_signed: Txid, witnesses: Vec<Witness>, best_block_height: u32,
2207 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
2208 ) -> Result<FundingTxSigned, APIError> {
2209 let (context, funding, pending_splice) = match &mut self.phase {
2210 ChannelPhase::Undefined => unreachable!(),
2211 ChannelPhase::UnfundedV2(channel) => (&mut channel.context, &channel.funding, None),
2212 ChannelPhase::Funded(channel) => {
2213 (&mut channel.context, &channel.funding, channel.pending_splice.as_ref())
2214 },
2215 _ => {
2216 return Err(APIError::APIMisuseError {
2217 err: format!(
2218 "Channel with id {} not expecting funding signatures",
2219 self.context().channel_id
2220 ),
2221 });
2222 },
2223 };
2224
2225 let signing_session = if let Some(signing_session) =
2226 context.interactive_tx_signing_session.as_mut()
2227 {
2228 if let Some(pending_splice) = pending_splice.as_ref() {
2229 debug_assert!(pending_splice
2230 .funding_negotiation
2231 .as_ref()
2232 .map(|funding_negotiation| matches!(
2233 funding_negotiation,
2234 FundingNegotiation::AwaitingSignatures { .. }
2235 ))
2236 .unwrap_or(false));
2237 }
2238
2239 if signing_session.has_holder_witnesses() {
2240 return Ok(FundingTxSigned {
2241 commitment_signed: None,
2242 counterparty_initial_commitment_signed_result: None,
2243 tx_signatures: None,
2244 funding_tx: None,
2245 splice_negotiated: None,
2246 splice_locked: None,
2247 });
2248 }
2249
2250 signing_session
2251 } else {
2252 if Some(funding_txid_signed) == funding.get_funding_txid() {
2253 return Ok(FundingTxSigned {
2256 commitment_signed: None,
2257 counterparty_initial_commitment_signed_result: None,
2258 tx_signatures: None,
2259 funding_tx: None,
2260 splice_negotiated: None,
2261 splice_locked: None,
2262 });
2263 }
2264 let err = format!("Channel {} not expecting funding signatures", context.channel_id);
2265 return Err(APIError::APIMisuseError { err });
2266 };
2267
2268 let (mut tx_signatures, mut funding_tx) = signing_session
2269 .provide_holder_witnesses(
2270 context.channel_id,
2271 funding_txid_signed,
2272 witnesses,
2273 &context.secp_ctx,
2274 )
2275 .map_err(|err| APIError::APIMisuseError { err })?;
2276
2277 debug_assert_eq!(
2278 pending_splice.is_some(),
2279 signing_session.unsigned_tx().shared_input_index().is_some()
2280 );
2281 if let Some(splice_input_index) = signing_session.unsigned_tx().shared_input_index() {
2282 let sig = context
2283 .holder_signer
2284 .sign_splice_shared_input(
2285 &funding.channel_transaction_parameters,
2286 signing_session.unsigned_tx().tx(),
2287 splice_input_index as usize,
2288 &context.secp_ctx,
2289 )
2290 .ok();
2291 if let Some(sig) = sig {
2292 (tx_signatures, funding_tx) = signing_session
2293 .provide_holder_shared_input_signature(sig)
2294 .map_err(|err| APIError::APIMisuseError { err })?;
2295 } else {
2296 log_debug!(
2297 logger,
2298 "Splice shared input signature not available, waiting on async signer"
2299 );
2300 debug_assert!(tx_signatures.is_none());
2301 debug_assert!(funding_tx.is_none());
2302 }
2303 }
2304
2305 let logger = WithChannelContext::from(logger, &context, None);
2306 if tx_signatures.is_some() {
2307 log_info!(
2308 logger,
2309 "Sending tx_signatures for interactive funding transaction {funding_txid_signed}"
2310 );
2311 }
2312
2313 let funding = pending_splice
2314 .as_ref()
2315 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
2316 .and_then(|funding_negotiation| funding_negotiation.as_funding())
2317 .unwrap_or(funding);
2318 let commitment_signed = context.get_initial_commitment_signed_v2(funding, &&logger);
2319
2320 let mut funding_tx_signed = FundingTxSigned {
2321 commitment_signed,
2322 counterparty_initial_commitment_signed_result: None,
2323 tx_signatures,
2324 funding_tx: None,
2325 splice_negotiated: None,
2326 splice_locked: None,
2327 };
2328
2329 funding_tx_signed.counterparty_initial_commitment_signed_result =
2332 self.as_funded_mut().and_then(|funded_channel| {
2333 funded_channel
2334 .pending_splice
2335 .as_mut()
2336 .and_then(|pending_splice| pending_splice.funding_negotiation.as_mut())
2337 .and_then(|funding_negotiation| {
2338 if let FundingNegotiation::AwaitingSignatures {
2339 ref mut initial_commitment_signed_from_counterparty,
2340 ..
2341 } = funding_negotiation
2342 {
2343 initial_commitment_signed_from_counterparty.take()
2344 } else {
2345 None
2346 }
2347 })
2348 .map(|commit_sig| {
2349 funded_channel.splice_initial_commitment_signed(
2350 &commit_sig,
2351 fee_estimator,
2352 &&logger,
2353 )
2354 })
2355 });
2356
2357 if let Some(funding_tx) = funding_tx {
2363 debug_assert!(funding_tx_signed.tx_signatures.is_some());
2364 let funded_channel = self.as_funded_mut().expect(
2365 "Funding transactions ready for broadcast can only exist for funded channels",
2366 );
2367 funded_channel.on_tx_signatures_exchange(
2368 &mut funding_tx_signed,
2369 funding_tx,
2370 best_block_height,
2371 &logger,
2372 )
2373 };
2374
2375 Ok(funding_tx_signed)
2376 }
2377
2378 pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
2379 let (funding, context) = self.funding_and_context_mut();
2380 context.force_shutdown(funding, closure_reason)
2381 }
2382
2383 #[rustfmt::skip]
2384 pub fn commitment_signed<F: FeeEstimator, L: Logger>(
2385 &mut self, msg: &msgs::CommitmentSigned, best_block: BlockLocator, signer_provider: &SP, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
2386 ) -> Result<(Option<ChannelMonitor<SP::EcdsaSigner>>, Option<ChannelMonitorUpdate>), ChannelError> {
2387 let phase = core::mem::replace(&mut self.phase, ChannelPhase::Undefined);
2388 match phase {
2389 ChannelPhase::UnfundedV2(chan) => {
2390 let holder_commitment_point = match chan.unfunded_context.holder_commitment_point {
2391 Some(point) => point,
2392 None => {
2393 let channel_id = chan.context.channel_id();
2394 return Err( ChannelError::close(
2396 format!("Expected to have holder commitment points available upon finishing interactive tx construction for channel {}",
2397 channel_id)));
2398 }
2399 };
2400 let mut funded_channel = FundedChannel {
2401 funding: chan.funding,
2402 context: chan.context,
2403 holder_commitment_point,
2404 pending_splice: None,
2405 quiescent_action: None,
2406 };
2407 let res = funded_channel.initial_commitment_signed_v2(msg, best_block, signer_provider, logger)
2408 .map(|monitor| (Some(monitor), None))
2409 .map_err(|err| {
2411 debug_assert!(matches!(err, ChannelError::Close(_)));
2413 err
2414 });
2415 self.phase = ChannelPhase::Funded(funded_channel);
2416 res
2417 },
2418 ChannelPhase::Funded(mut funded_channel) => {
2419 let has_negotiated_pending_splice = funded_channel.pending_splice.as_ref()
2420 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
2421 .filter(|funding_negotiation| {
2422 matches!(funding_negotiation, FundingNegotiation::AwaitingSignatures { .. })
2423 })
2424 .map(|funding_negotiation| funding_negotiation.as_funding().is_some())
2425 .unwrap_or(false);
2426 let session_received_commitment_signed = funded_channel
2427 .context
2428 .interactive_tx_signing_session
2429 .as_ref()
2430 .map(|session| session.has_received_commitment_signed())
2431 .unwrap_or(true);
2434 let res = if has_negotiated_pending_splice && !session_received_commitment_signed {
2435 let has_holder_witnesses = funded_channel
2436 .context
2437 .interactive_tx_signing_session
2438 .as_ref()
2439 .map(|session| session.has_holder_witnesses())
2440 .unwrap_or(false);
2441
2442 if has_holder_witnesses {
2446 funded_channel
2447 .splice_initial_commitment_signed(msg, fee_estimator, logger)
2448 .map(|monitor_update_opt| (None, monitor_update_opt))
2449 } else {
2450 let pending_splice = funded_channel.pending_splice.as_mut()
2451 .expect("We have a pending splice negotiated");
2452 let funding_negotiation = pending_splice.funding_negotiation.as_mut()
2453 .expect("We have a pending splice negotiated");
2454 log_debug!(logger, "Stashing counterparty initial commitment_signed to process after funding_transaction_signed");
2455 if let FundingNegotiation::AwaitingSignatures {
2456 ref mut initial_commitment_signed_from_counterparty, ..
2457 } = funding_negotiation {
2458 *initial_commitment_signed_from_counterparty = Some(msg.clone());
2459 }
2460 Ok((None, None))
2461 }
2462 } else {
2463 funded_channel.commitment_signed(msg, fee_estimator, logger)
2464 .map(|monitor_update_opt| (None, monitor_update_opt))
2465 };
2466
2467 self.phase = ChannelPhase::Funded(funded_channel);
2468 res
2469 },
2470 _ => {
2471 self.phase = phase;
2472 debug_assert!(!matches!(self.phase, ChannelPhase::Undefined));
2473 Err(ChannelError::close("Got a commitment_signed message for an unfunded V1 channel!".into()))
2474 }
2475 }
2476 }
2477
2478 pub fn get_available_balances<F: FeeEstimator>(
2483 &self, fee_estimator: &LowerBoundedFeeEstimator<F>,
2484 ) -> Result<AvailableBalances, ()> {
2485 match &self.phase {
2486 ChannelPhase::Undefined => unreachable!(),
2487 ChannelPhase::Funded(chan) => chan.get_available_balances(fee_estimator),
2488 ChannelPhase::UnfundedOutboundV1(chan) => {
2489 chan.context.get_available_balances_for_scope(&chan.funding, fee_estimator)
2490 },
2491 ChannelPhase::UnfundedInboundV1(chan) => {
2492 chan.context.get_available_balances_for_scope(&chan.funding, fee_estimator)
2493 },
2494 ChannelPhase::UnfundedV2(chan) => {
2495 chan.context.get_available_balances_for_scope(&chan.funding, fee_estimator)
2496 },
2497 }
2498 }
2499
2500 pub fn minimum_depth(&self) -> Option<u32> {
2501 self.context().minimum_depth(self.funding())
2502 }
2503}
2504
2505impl<SP: SignerProvider> From<OutboundV1Channel<SP>> for Channel<SP>
2506where
2507 SP::EcdsaSigner: ChannelSigner,
2508{
2509 fn from(channel: OutboundV1Channel<SP>) -> Self {
2510 Channel { phase: ChannelPhase::UnfundedOutboundV1(channel) }
2511 }
2512}
2513
2514impl<SP: SignerProvider> From<InboundV1Channel<SP>> for Channel<SP>
2515where
2516 SP::EcdsaSigner: ChannelSigner,
2517{
2518 fn from(channel: InboundV1Channel<SP>) -> Self {
2519 Channel { phase: ChannelPhase::UnfundedInboundV1(channel) }
2520 }
2521}
2522
2523impl<SP: SignerProvider> From<PendingV2Channel<SP>> for Channel<SP>
2524where
2525 SP::EcdsaSigner: ChannelSigner,
2526{
2527 fn from(channel: PendingV2Channel<SP>) -> Self {
2528 Channel { phase: ChannelPhase::UnfundedV2(channel) }
2529 }
2530}
2531
2532impl<SP: SignerProvider> From<FundedChannel<SP>> for Channel<SP>
2533where
2534 SP::EcdsaSigner: ChannelSigner,
2535{
2536 fn from(channel: FundedChannel<SP>) -> Self {
2537 Channel { phase: ChannelPhase::Funded(channel) }
2538 }
2539}
2540
2541pub(super) struct UnfundedChannelContext {
2543 unfunded_channel_age_ticks: usize,
2550 holder_commitment_point: Option<HolderCommitmentPoint>,
2552}
2553
2554impl UnfundedChannelContext {
2555 pub fn should_expire_unfunded_channel(&mut self) -> bool {
2560 self.unfunded_channel_age_ticks += 1;
2561 self.unfunded_channel_age_ticks >= UNFUNDED_CHANNEL_AGE_LIMIT_TICKS
2562 }
2563
2564 fn transaction_number(&self) -> u64 {
2565 self.holder_commitment_point
2566 .as_ref()
2567 .map(|point| point.next_transaction_number())
2568 .unwrap_or(INITIAL_COMMITMENT_NUMBER)
2569 }
2570}
2571
2572#[derive(Debug)]
2576pub(super) struct FundingScope {
2577 value_to_self_msat: u64, #[cfg(any(test, feature = "_externalize_tests"))]
2581 pub(super) counterparty_selected_channel_reserve_satoshis: Option<u64>,
2582 #[cfg(not(any(test, feature = "_externalize_tests")))]
2583 counterparty_selected_channel_reserve_satoshis: Option<u64>,
2584
2585 #[cfg(any(test, feature = "_externalize_tests"))]
2586 pub(super) holder_selected_channel_reserve_satoshis: u64,
2587 #[cfg(not(any(test, feature = "_externalize_tests")))]
2588 holder_selected_channel_reserve_satoshis: u64,
2589
2590 #[cfg(debug_assertions)]
2591 holder_prev_commitment_tx_balance: Mutex<(u64, u64)>,
2593 #[cfg(debug_assertions)]
2594 counterparty_prev_commitment_tx_balance: Mutex<(u64, u64)>,
2596
2597 #[cfg(any(test, fuzzing))]
2601 next_local_fee: Mutex<PredictedNextFee>,
2602 #[cfg(any(test, fuzzing))]
2603 next_remote_fee: Mutex<PredictedNextFee>,
2604
2605 pub(super) channel_transaction_parameters: ChannelTransactionParameters,
2606
2607 funding_transaction: Option<Transaction>,
2610 funding_tx_confirmed_in: Option<BlockHash>,
2612 funding_tx_confirmation_height: u32,
2613 short_channel_id: Option<u64>,
2614
2615 minimum_depth_override: Option<u32>,
2618}
2619
2620impl Writeable for FundingScope {
2621 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
2622 write_tlv_fields!(writer, {
2623 (1, self.value_to_self_msat, required),
2624 (3, self.counterparty_selected_channel_reserve_satoshis, option),
2625 (5, self.holder_selected_channel_reserve_satoshis, required),
2626 (7, self.channel_transaction_parameters, (required: ReadableArgs, None)),
2627 (9, self.funding_transaction, option),
2628 (11, self.funding_tx_confirmed_in, option),
2629 (13, self.funding_tx_confirmation_height, required),
2630 (15, self.short_channel_id, option),
2631 (17, self.minimum_depth_override, option),
2632 });
2633 Ok(())
2634 }
2635}
2636
2637impl Readable for FundingScope {
2638 #[rustfmt::skip]
2639 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
2640 let mut value_to_self_msat = RequiredWrapper(None);
2641 let mut counterparty_selected_channel_reserve_satoshis = None;
2642 let mut holder_selected_channel_reserve_satoshis = RequiredWrapper(None);
2643 let mut channel_transaction_parameters = RequiredWrapper(None);
2644 let mut funding_transaction = None;
2645 let mut funding_tx_confirmed_in = None;
2646 let mut funding_tx_confirmation_height = RequiredWrapper(None);
2647 let mut short_channel_id = None;
2648 let mut minimum_depth_override = None;
2649
2650 read_tlv_fields!(reader, {
2651 (1, value_to_self_msat, required),
2652 (3, counterparty_selected_channel_reserve_satoshis, option),
2653 (5, holder_selected_channel_reserve_satoshis, required),
2654 (7, channel_transaction_parameters, (required: ReadableArgs, None)),
2655 (9, funding_transaction, option),
2656 (11, funding_tx_confirmed_in, option),
2657 (13, funding_tx_confirmation_height, required),
2658 (15, short_channel_id, option),
2659 (17, minimum_depth_override, option),
2660 });
2661
2662 Ok(Self {
2663 value_to_self_msat: value_to_self_msat.0.unwrap(),
2664 counterparty_selected_channel_reserve_satoshis,
2665 holder_selected_channel_reserve_satoshis: holder_selected_channel_reserve_satoshis.0.unwrap(),
2666 #[cfg(debug_assertions)]
2667 holder_prev_commitment_tx_balance: Mutex::new((0, 0)),
2668 #[cfg(debug_assertions)]
2669 counterparty_prev_commitment_tx_balance: Mutex::new((0, 0)),
2670 channel_transaction_parameters: channel_transaction_parameters.0.unwrap(),
2671 funding_transaction,
2672 funding_tx_confirmed_in,
2673 funding_tx_confirmation_height: funding_tx_confirmation_height.0.unwrap(),
2674 short_channel_id,
2675 minimum_depth_override,
2676 #[cfg(any(test, fuzzing))]
2677 next_local_fee: Mutex::new(PredictedNextFee::default()),
2678 #[cfg(any(test, fuzzing))]
2679 next_remote_fee: Mutex::new(PredictedNextFee::default()),
2680 })
2681 }
2682}
2683
2684impl FundingScope {
2685 pub fn get_value_satoshis(&self) -> u64 {
2686 self.channel_transaction_parameters.channel_value_satoshis
2687 }
2688
2689 pub(crate) fn get_value_to_self_msat(&self) -> u64 {
2690 self.value_to_self_msat
2691 }
2692
2693 pub fn get_holder_counterparty_selected_channel_reserve_satoshis(&self) -> (u64, Option<u64>) {
2694 (
2695 self.holder_selected_channel_reserve_satoshis,
2696 self.counterparty_selected_channel_reserve_satoshis,
2697 )
2698 }
2699
2700 fn get_htlc_maximum_msat(&self, party_max_htlc_value_in_flight_msat: u64) -> Option<u64> {
2701 self.counterparty_selected_channel_reserve_satoshis.map(|counterparty_reserve| {
2702 let holder_reserve = self.holder_selected_channel_reserve_satoshis;
2703 cmp::min(
2704 (self.get_value_satoshis() - counterparty_reserve - holder_reserve) * 1000,
2705 party_max_htlc_value_in_flight_msat,
2706 )
2707 })
2708 }
2709
2710 pub fn is_outbound(&self) -> bool {
2711 self.channel_transaction_parameters.is_outbound_from_holder
2712 }
2713
2714 pub fn get_funding_txo(&self) -> Option<OutPoint> {
2717 self.channel_transaction_parameters.funding_outpoint
2718 }
2719
2720 pub fn get_funding_output(&self) -> Option<TxOut> {
2726 self.channel_transaction_parameters.make_funding_redeemscript_opt().map(|redeem_script| {
2727 TxOut {
2728 value: Amount::from_sat(self.get_value_satoshis()),
2729 script_pubkey: redeem_script.to_p2wsh(),
2730 }
2731 })
2732 }
2733
2734 fn get_funding_txid(&self) -> Option<Txid> {
2735 self.channel_transaction_parameters.funding_outpoint.map(|txo| txo.txid)
2736 }
2737
2738 fn get_holder_selected_contest_delay(&self) -> u16 {
2739 self.channel_transaction_parameters.holder_selected_contest_delay
2740 }
2741
2742 fn get_holder_pubkeys(&self) -> &ChannelPublicKeys {
2743 &self.channel_transaction_parameters.holder_pubkeys
2744 }
2745
2746 pub fn get_counterparty_selected_contest_delay(&self) -> Option<u16> {
2747 let params_opt = self.channel_transaction_parameters.counterparty_parameters.as_ref();
2748 params_opt.map(|params| params.selected_contest_delay)
2749 }
2750
2751 fn get_counterparty_pubkeys(&self) -> &ChannelPublicKeys {
2752 &self.channel_transaction_parameters.counterparty_parameters.as_ref().unwrap().pubkeys
2753 }
2754
2755 pub fn get_funding_redeemscript(&self) -> ScriptBuf {
2759 self.channel_transaction_parameters.make_funding_redeemscript()
2760 }
2761
2762 fn holder_funding_pubkey(&self) -> &PublicKey {
2763 &self.get_holder_pubkeys().funding_pubkey
2764 }
2765
2766 fn counterparty_funding_pubkey(&self) -> &PublicKey {
2767 &self.get_counterparty_pubkeys().funding_pubkey
2768 }
2769
2770 pub fn get_channel_type(&self) -> &ChannelTypeFeatures {
2772 &self.channel_transaction_parameters.channel_type_features
2773 }
2774
2775 pub fn get_funding_tx_confirmation_height(&self) -> Option<u32> {
2777 let conf_height = self.funding_tx_confirmation_height;
2778 if conf_height > 0 {
2779 Some(conf_height)
2780 } else {
2781 None
2782 }
2783 }
2784
2785 pub fn get_funding_tx_confirmations(&self, height: u32) -> u32 {
2787 if self.funding_tx_confirmation_height == 0 {
2788 return 0;
2790 }
2791
2792 height.checked_sub(self.funding_tx_confirmation_height).map_or(0, |c| c + 1)
2793 }
2794
2795 pub fn get_short_channel_id(&self) -> Option<u64> {
2799 self.short_channel_id
2800 }
2801
2802 fn for_splice<SP: SignerProvider>(
2804 prev_funding: &Self, context: &ChannelContext<SP>, our_funding_contribution: SignedAmount,
2805 their_funding_contribution: SignedAmount, counterparty_funding_pubkey: PublicKey,
2806 our_new_holder_keys: ChannelPublicKeys, min_funding_satoshis: u64,
2807 ) -> Result<Self, String> {
2808 if our_funding_contribution.unsigned_abs() > Amount::MAX_MONEY {
2809 return Err(format!(
2810 "Our {} contribution exceeds the total bitcoin supply",
2811 our_funding_contribution,
2812 ));
2813 }
2814
2815 if their_funding_contribution.unsigned_abs() > Amount::MAX_MONEY {
2816 return Err(format!(
2817 "Their {} contribution exceeds the total bitcoin supply",
2818 their_funding_contribution,
2819 ));
2820 }
2821
2822 let channel_value_satoshis = prev_funding.get_value_satoshis();
2823 let value_to_self_satoshis = prev_funding.get_value_to_self_msat() / 1000;
2824 let value_to_counterparty_satoshis = channel_value_satoshis
2825 .checked_sub(value_to_self_satoshis)
2826 .expect("value_to_self is greater than channel value");
2827 let our_funding_contribution_sat = our_funding_contribution.to_sat();
2828 let their_funding_contribution_sat = their_funding_contribution.to_sat();
2829
2830 let post_value_to_self_msat = prev_funding
2831 .get_value_to_self_msat()
2832 .checked_add_signed(our_funding_contribution_sat * 1000)
2833 .ok_or(format!(
2834 "Our contribution candidate {our_funding_contribution_sat}sat is \
2835 greater than our total balance in the channel {value_to_self_satoshis}sat"
2836 ))?;
2837
2838 value_to_counterparty_satoshis.checked_add_signed(their_funding_contribution_sat).ok_or(
2839 format!(
2840 "Their contribution candidate {their_funding_contribution_sat}sat is \
2841 greater than their total balance in the channel {value_to_counterparty_satoshis}sat"
2842 ),
2843 )?;
2844
2845 let post_channel_value_sat = prev_funding
2846 .get_value_satoshis()
2847 .checked_add_signed(our_funding_contribution.to_sat())
2848 .and_then(|v| v.checked_add_signed(their_funding_contribution.to_sat()))
2849 .ok_or(format!(
2850 "The sum of contributions {our_funding_contribution} and \
2851 {their_funding_contribution} is greater than the channel's value"
2852 ))?;
2853 if post_channel_value_sat < MIN_CHANNEL_VALUE_SATOSHIS {
2854 return Err(format!(
2855 "Spliced channel value must be at least 1000 satoshis. It would be \
2856 {post_channel_value_sat}"
2857 ));
2858 }
2859 if post_channel_value_sat < min_funding_satoshis
2860 && their_funding_contribution.is_negative()
2861 && !prev_funding.is_outbound()
2862 {
2863 return Err(format!(
2864 "Spliced channel value {post_channel_value_sat} would be smaller \
2865 than the configured min_funding_satoshis {min_funding_satoshis}"
2866 ));
2867 }
2868
2869 let channel_parameters = &prev_funding.channel_transaction_parameters;
2870 let mut post_channel_transaction_parameters = ChannelTransactionParameters {
2871 holder_pubkeys: our_new_holder_keys,
2872 holder_selected_contest_delay: channel_parameters.holder_selected_contest_delay,
2873 is_outbound_from_holder: channel_parameters.is_outbound_from_holder,
2875 counterparty_parameters: channel_parameters.counterparty_parameters.clone(),
2876 funding_outpoint: None, splice_parent_funding_txid: prev_funding.get_funding_txid(),
2878 channel_type_features: channel_parameters.channel_type_features.clone(),
2879 channel_value_satoshis: post_channel_value_sat,
2880 };
2881 post_channel_transaction_parameters
2882 .counterparty_parameters
2883 .as_mut()
2884 .expect("counterparty_parameters should be set")
2885 .pubkeys
2886 .funding_pubkey = counterparty_funding_pubkey;
2887
2888 let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
2890 post_channel_value_sat,
2891 context.holder_dust_limit_satoshis,
2892 prev_funding
2893 .counterparty_selected_channel_reserve_satoshis
2894 .expect("counterparty reserve is set")
2895 == 0,
2896 )
2897 .map_err(|()| {
2898 format!(
2899 "The post-splice channel value {post_channel_value_sat} is smaller \
2900 than our dust limit {}",
2901 context.holder_dust_limit_satoshis
2902 )
2903 })?;
2904 let holder_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
2905 post_channel_value_sat,
2906 context.counterparty_dust_limit_satoshis,
2907 prev_funding.holder_selected_channel_reserve_satoshis == 0,
2908 )
2909 .map_err(|()| {
2910 format!(
2911 "The post-splice channel value {post_channel_value_sat} is smaller \
2912 than their dust limit {}",
2913 context.counterparty_dust_limit_satoshis,
2914 )
2915 })?;
2916
2917 Ok(Self {
2918 channel_transaction_parameters: post_channel_transaction_parameters,
2919 value_to_self_msat: post_value_to_self_msat,
2920 funding_transaction: None,
2921 counterparty_selected_channel_reserve_satoshis: Some(
2922 counterparty_selected_channel_reserve_satoshis,
2923 ),
2924 holder_selected_channel_reserve_satoshis,
2925 #[cfg(debug_assertions)]
2926 holder_prev_commitment_tx_balance: {
2927 let prev = *prev_funding.holder_prev_commitment_tx_balance.lock().unwrap();
2928 let new_holder_balance_msat =
2929 prev.0.saturating_add_signed(our_funding_contribution.to_sat() * 1000);
2930 let new_counterparty_balance_msat =
2931 prev.1.saturating_add_signed(their_funding_contribution.to_sat() * 1000);
2932 Mutex::new((new_holder_balance_msat, new_counterparty_balance_msat))
2933 },
2934 #[cfg(debug_assertions)]
2935 counterparty_prev_commitment_tx_balance: {
2936 let prev = *prev_funding.counterparty_prev_commitment_tx_balance.lock().unwrap();
2937 let new_holder_balance_msat =
2938 prev.0.saturating_add_signed(our_funding_contribution.to_sat() * 1000);
2939 let new_counterparty_balance_msat =
2940 prev.1.saturating_add_signed(their_funding_contribution.to_sat() * 1000);
2941 Mutex::new((new_holder_balance_msat, new_counterparty_balance_msat))
2942 },
2943 #[cfg(any(test, fuzzing))]
2944 next_local_fee: Mutex::new(PredictedNextFee::default()),
2945 #[cfg(any(test, fuzzing))]
2946 next_remote_fee: Mutex::new(PredictedNextFee::default()),
2947 funding_tx_confirmation_height: 0,
2948 funding_tx_confirmed_in: None,
2949 minimum_depth_override: None,
2950 short_channel_id: None,
2951 })
2952 }
2953
2954 fn to_splice_funding_input(&self) -> SharedOwnedInput {
2956 let funding_txo = self.get_funding_txo().expect("funding_txo should be set");
2957 let input = TxIn {
2958 previous_output: funding_txo.into_bitcoin_outpoint(),
2959 script_sig: ScriptBuf::new(),
2960 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
2961 witness: Witness::new(),
2962 };
2963
2964 let prev_output = TxOut {
2965 value: Amount::from_sat(self.get_value_satoshis()),
2966 script_pubkey: self.get_funding_redeemscript().to_p2wsh(),
2967 };
2968
2969 let local_owned = self.value_to_self_msat / 1000;
2970 let holder_sig_first = self.holder_funding_pubkey().serialize()[..]
2971 < self.counterparty_funding_pubkey().serialize()[..];
2972
2973 SharedOwnedInput::new(
2974 input,
2975 prev_output,
2976 local_owned,
2977 holder_sig_first,
2978 self.get_funding_redeemscript(),
2979 )
2980 }
2981}
2982
2983#[derive(Debug)]
2987struct PendingFunding {
2988 funding_negotiation: Option<FundingNegotiation>,
2989
2990 negotiation_contribution: Option<FundingContribution>,
3000
3001 negotiated_candidates: Vec<NegotiatedCandidate>,
3004
3005 sent_funding_txid: Option<Txid>,
3007
3008 received_funding_txid: Option<Txid>,
3010
3011 last_funding_feerate_sat_per_1000_weight: Option<u32>,
3014}
3015
3016#[derive(Debug)]
3019struct NegotiatedCandidate {
3020 funding: FundingScope,
3021
3022 contribution: Option<FundingContribution>,
3027}
3028
3029impl_writeable_tlv_based!(NegotiatedCandidate, {
3030 (1, funding, required),
3031 (3, contribution, option),
3032});
3033
3034#[derive(Debug)]
3035enum FundingNegotiation {
3036 AwaitingAck {
3037 context: FundingNegotiationContext,
3038 new_holder_funding_key: PublicKey,
3039 },
3040 ConstructingTransaction {
3041 funding: FundingScope,
3042 funding_feerate_sat_per_1000_weight: u32,
3043 interactive_tx_constructor: InteractiveTxConstructor,
3044 },
3045 AwaitingSignatures {
3046 funding: FundingScope,
3047 funding_feerate_sat_per_1000_weight: u32,
3048 is_initiator: bool,
3049 initial_commitment_signed_from_counterparty: Option<msgs::CommitmentSigned>,
3060 },
3061}
3062
3063impl_writeable_tlv_based_enum_upgradable!(FundingNegotiation,
3064 (0, AwaitingSignatures) => {
3065 (1, funding, required),
3066 (3, is_initiator, required),
3067 (5, funding_feerate_sat_per_1000_weight, (default_value, 0)),
3068 (_unused, initial_commitment_signed_from_counterparty, (static_value, None)),
3069 },
3070 unread_variants: AwaitingAck, ConstructingTransaction
3071);
3072
3073struct PendingFundingWriteable<'a> {
3074 pending_funding: &'a PendingFunding,
3075 reset_funding_negotiation: bool,
3076}
3077
3078impl Writeable for PendingFundingWriteable<'_> {
3079 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
3080 let funding_negotiation = if self.reset_funding_negotiation {
3081 None
3082 } else {
3083 self.pending_funding.funding_negotiation.as_ref()
3084 };
3085 debug_assert!(
3086 funding_negotiation.is_none()
3087 || matches!(
3088 funding_negotiation,
3089 Some(FundingNegotiation::AwaitingSignatures { .. })
3090 )
3091 );
3092 let negotiation_contribution = funding_negotiation
3096 .is_some()
3097 .then(|| self.pending_funding.negotiation_contribution.as_ref())
3098 .flatten();
3099 let candidates = &self.pending_funding.negotiated_candidates;
3100 debug_assert!(
3101 self.pending_funding.contributions_form_suffix(),
3102 "contributions must form a suffix of the negotiated candidates",
3103 );
3104 let first_funding = Iterable(candidates.iter().take(1).map(|candidate| &candidate.funding));
3116 let any_contribution = candidates.iter().any(|candidate| candidate.contribution.is_some());
3117 let negotiated_candidates =
3118 (candidates.len() > 1 || any_contribution).then(|| Iterable(candidates.iter()));
3119 let is_rbf = candidates.len() + usize::from(funding_negotiation.is_some()) > 1;
3120 let rbf_gate = is_rbf.then_some(());
3121 write_tlv_fields!(writer, {
3122 (1, funding_negotiation, upgradable_option),
3123 (3, first_funding, required),
3124 (5, self.pending_funding.sent_funding_txid, option),
3125 (7, self.pending_funding.received_funding_txid, option),
3126 (9, self.pending_funding.last_funding_feerate_sat_per_1000_weight, option),
3127 (11, negotiated_candidates, option),
3128 (13, negotiation_contribution, option),
3129 (14, rbf_gate, option),
3130 });
3131 Ok(())
3132 }
3133}
3134
3135impl Readable for PendingFunding {
3136 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
3137 let mut funding_negotiation = None;
3138 let mut legacy_negotiated_candidates: Option<Vec<FundingScope>> = None;
3139 let mut sent_funding_txid = None;
3140 let mut received_funding_txid = None;
3141 let mut last_funding_feerate_sat_per_1000_weight = None;
3142 let mut negotiated_candidates: Option<Vec<NegotiatedCandidate>> = None;
3143 let mut negotiation_contribution: Option<FundingContribution> = None;
3144 let mut rbf_gate: Option<()> = None;
3145
3146 read_tlv_fields!(reader, {
3147 (1, funding_negotiation, upgradable_option),
3148 (3, legacy_negotiated_candidates, optional_vec),
3149 (5, sent_funding_txid, option),
3150 (7, received_funding_txid, option),
3151 (9, last_funding_feerate_sat_per_1000_weight, option),
3152 (11, negotiated_candidates, optional_vec),
3153 (13, negotiation_contribution, option),
3154 (14, rbf_gate, option),
3155 });
3156
3157 let negotiated_candidates = negotiated_candidates.unwrap_or_else(|| {
3162 legacy_negotiated_candidates
3163 .unwrap_or_default()
3164 .into_iter()
3165 .map(|funding| NegotiatedCandidate { funding, contribution: None })
3166 .collect()
3167 });
3168 if funding_negotiation.is_none() && negotiation_contribution.is_some() {
3171 return Err(DecodeError::InvalidValue);
3172 }
3173 let is_rbf = negotiated_candidates.len() + usize::from(funding_negotiation.is_some()) > 1;
3177 if rbf_gate.is_some() != is_rbf {
3178 return Err(DecodeError::InvalidValue);
3179 }
3180
3181 Ok(PendingFunding {
3182 funding_negotiation,
3183 negotiation_contribution,
3184 negotiated_candidates,
3185 sent_funding_txid,
3186 received_funding_txid,
3187 last_funding_feerate_sat_per_1000_weight,
3188 })
3189 }
3190}
3191
3192impl FundingNegotiation {
3193 fn as_funding(&self) -> Option<&FundingScope> {
3194 match self {
3195 FundingNegotiation::AwaitingAck { .. } => None,
3196 FundingNegotiation::ConstructingTransaction { funding, .. } => Some(funding),
3197 FundingNegotiation::AwaitingSignatures { funding, .. } => Some(funding),
3198 }
3199 }
3200
3201 fn funding_feerate_sat_per_1000_weight(&self) -> u32 {
3202 match self {
3203 FundingNegotiation::AwaitingAck { context, .. } => {
3204 context.funding_feerate_sat_per_1000_weight
3205 },
3206 FundingNegotiation::ConstructingTransaction {
3207 funding_feerate_sat_per_1000_weight,
3208 ..
3209 } => *funding_feerate_sat_per_1000_weight,
3210 FundingNegotiation::AwaitingSignatures {
3211 funding_feerate_sat_per_1000_weight, ..
3212 } => *funding_feerate_sat_per_1000_weight,
3213 }
3214 }
3215
3216 fn is_initiator(&self) -> bool {
3217 match self {
3218 FundingNegotiation::AwaitingAck { context, .. } => context.is_initiator,
3219 FundingNegotiation::ConstructingTransaction { interactive_tx_constructor, .. } => {
3220 interactive_tx_constructor.is_initiator()
3221 },
3222 FundingNegotiation::AwaitingSignatures { is_initiator, .. } => *is_initiator,
3223 }
3224 }
3225 fn for_initiator<SP: SignerProvider, ES: EntropySource>(
3226 funding: FundingScope, context: &ChannelContext<SP>,
3227 funding_negotiation_context: FundingNegotiationContext, entropy_source: &ES,
3228 holder_node_id: &PublicKey,
3229 ) -> (FundingNegotiation, Option<InteractiveTxMessageSend>) {
3230 let funding_feerate_sat_per_1000_weight =
3231 funding_negotiation_context.funding_feerate_sat_per_1000_weight;
3232 let (interactive_tx_constructor, tx_msg_opt) = funding_negotiation_context
3233 .into_interactive_tx_constructor(
3234 context,
3235 &funding,
3236 entropy_source,
3237 holder_node_id.clone(),
3238 );
3239 debug_assert!(tx_msg_opt.is_some());
3240
3241 (
3242 FundingNegotiation::ConstructingTransaction {
3243 funding,
3244 funding_feerate_sat_per_1000_weight,
3245 interactive_tx_constructor,
3246 },
3247 tx_msg_opt,
3248 )
3249 }
3250
3251 fn for_acceptor<SP: SignerProvider, ES: EntropySource>(
3252 funding: FundingScope, context: &ChannelContext<SP>, entropy_source: &ES,
3253 holder_node_id: &PublicKey, our_funding_contribution: SignedAmount,
3254 prev_funding_input: SharedOwnedInput, locktime: u32, feerate_sat_per_1000_weight: u32,
3255 our_funding_inputs: Vec<ConfirmedUtxo>, our_funding_outputs: Vec<TxOut>,
3256 ) -> FundingNegotiation {
3257 let funding_negotiation_context = FundingNegotiationContext {
3258 is_initiator: false,
3259 our_funding_contribution,
3260 funding_tx_locktime: LockTime::from_consensus(locktime),
3261 funding_feerate_sat_per_1000_weight: feerate_sat_per_1000_weight,
3262 shared_funding_input: Some(prev_funding_input),
3263 our_funding_inputs,
3264 our_funding_outputs,
3265 };
3266
3267 let (interactive_tx_constructor, first_message) = funding_negotiation_context
3268 .into_interactive_tx_constructor(
3269 context,
3270 &funding,
3271 entropy_source,
3272 holder_node_id.clone(),
3273 );
3274 debug_assert!(first_message.is_none());
3275
3276 FundingNegotiation::ConstructingTransaction {
3277 funding,
3278 funding_feerate_sat_per_1000_weight: feerate_sat_per_1000_weight,
3279 interactive_tx_constructor,
3280 }
3281 }
3282}
3283
3284impl PendingFunding {
3285 fn has_confirmed_candidate(&self) -> bool {
3286 self.negotiated_candidates
3287 .iter()
3288 .any(|candidate| candidate.funding.funding_tx_confirmation_height != 0)
3289 }
3290
3291 fn contributions_form_suffix(&self) -> bool {
3295 self.negotiated_candidates
3296 .iter()
3297 .skip_while(|candidate| candidate.contribution.is_none())
3298 .all(|candidate| candidate.contribution.is_some())
3299 }
3300
3301 fn awaiting_ack_context(
3302 &self, msg_name: &str,
3303 ) -> Result<(&FundingNegotiationContext, &PublicKey), ChannelError> {
3304 match &self.funding_negotiation {
3305 Some(FundingNegotiation::AwaitingAck { context, new_holder_funding_key }) => {
3306 Ok((context, new_holder_funding_key))
3307 },
3308 Some(FundingNegotiation::ConstructingTransaction { .. })
3309 | Some(FundingNegotiation::AwaitingSignatures { .. }) => Err(ChannelError::WarnAndDisconnect(
3310 format!("Got unexpected {}; funding negotiation already in progress", msg_name,),
3311 )),
3312 None => Err(ChannelError::Ignore(format!(
3313 "Got unexpected {}; no funding negotiation in progress",
3314 msg_name,
3315 ))),
3316 }
3317 }
3318
3319 fn take_awaiting_ack_context(
3320 &mut self, msg_name: &str,
3321 ) -> Result<FundingNegotiationContext, ChannelError> {
3322 match self.funding_negotiation.take() {
3323 Some(FundingNegotiation::AwaitingAck { context, .. }) => Ok(context),
3324 Some(other) => {
3325 self.funding_negotiation = Some(other);
3326 Err(ChannelError::WarnAndDisconnect(format!(
3327 "Got unexpected {}; funding negotiation already in progress",
3328 msg_name,
3329 )))
3330 },
3331 None => Err(ChannelError::Ignore(format!(
3332 "Got unexpected {}; no funding negotiation in progress",
3333 msg_name,
3334 ))),
3335 }
3336 }
3337
3338 fn min_rbf_feerate_above(prev_feerate: u32) -> FeeRate {
3345 let flat_increment = (prev_feerate as u64).saturating_add(25);
3346 let spec_increment = (prev_feerate as u64) * 25 / 24;
3347 FeeRate::from_sat_per_kwu(cmp::max(flat_increment, spec_increment))
3348 }
3349
3350 fn min_rbf_feerate(&self) -> Option<FeeRate> {
3359 self.last_funding_feerate_sat_per_1000_weight
3360 .or_else(|| {
3361 self.funding_negotiation.as_ref().map(|n| n.funding_feerate_sat_per_1000_weight())
3362 })
3363 .map(Self::min_rbf_feerate_above)
3364 }
3365
3366 fn is_rbf_feerate_sufficient<F: FeeEstimator>(
3371 &self, feerate_sat_per_kw: u32, fee_estimator: &LowerBoundedFeeEstimator<F>,
3372 ) -> bool {
3373 const MAX_LOW_FEERATE_RBF_ATTEMPTS: usize = 10;
3374 if self.negotiated_candidates.len() <= MAX_LOW_FEERATE_RBF_ATTEMPTS {
3375 return true;
3376 }
3377 let min_feerate =
3378 fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
3379 feerate_sat_per_kw >= min_feerate
3380 }
3381
3382 fn committed_funding_parts(&self) -> (Vec<bitcoin::OutPoint>, Vec<&bitcoin::Script>) {
3386 let mut inputs = Vec::new();
3387 let mut output_scripts = Vec::new();
3388 for candidate in &self.negotiated_candidates {
3389 match candidate.contribution.as_ref() {
3390 Some(contribution) => {
3391 inputs.extend(contribution.contributed_inputs());
3392 output_scripts.extend(contribution.contributed_outputs());
3393 },
3394 None => {
3395 let transaction = candidate
3401 .funding
3402 .funding_transaction
3403 .as_ref()
3404 .expect("negotiated candidate must have a funding transaction");
3405 inputs.extend(transaction.input.iter().map(|txin| txin.previous_output));
3406 output_scripts.extend(
3407 transaction.output.iter().map(|txout| txout.script_pubkey.as_script()),
3408 );
3409 },
3410 }
3411 }
3412 if let Some(contribution) = self.negotiation_contribution.as_ref() {
3413 inputs.extend(contribution.contributed_inputs());
3414 output_scripts.extend(contribution.contributed_outputs());
3415 }
3416 (inputs, output_scripts)
3417 }
3418
3419 fn can_queue_contribution_for_fresh_splice(&self, contribution: &FundingContribution) -> bool {
3422 let (committed_inputs, committed_output_scripts) = self.committed_funding_parts();
3423 !contribution.contributed_inputs().any(|input| committed_inputs.contains(&input))
3424 && !contribution
3425 .contributed_outputs()
3426 .any(|output| committed_output_scripts.contains(&output))
3427 }
3428
3429 fn latest_contribution(&self) -> Option<&FundingContribution> {
3431 self.negotiation_contribution.as_ref().or_else(|| {
3432 self.negotiated_candidates.last().and_then(|candidate| candidate.contribution.as_ref())
3433 })
3434 }
3435
3436 fn to_details<SP: SignerProvider>(
3437 &self, context: &ChannelContext<SP>, best_block_height: u32,
3438 ) -> SpliceDetails {
3439 let mut candidates: Vec<SpliceCandidateDetails> = self
3440 .negotiated_candidates
3441 .iter()
3442 .map(|candidate| SpliceCandidateDetails {
3443 contribution: candidate.contribution.clone(),
3444 status: SpliceCandidateStatus::Negotiated {
3445 txid: candidate
3446 .funding
3447 .get_funding_txid()
3448 .expect("negotiated candidates should have a funding txid"),
3449 new_channel_value_satoshis: candidate.funding.get_value_satoshis(),
3450 },
3451 })
3452 .collect();
3453
3454 if let Some(funding_negotiation) = self.funding_negotiation.as_ref() {
3456 let is_initiator = funding_negotiation.is_initiator();
3457 let funding_feerate_sat_per_1000_weight =
3458 funding_negotiation.funding_feerate_sat_per_1000_weight();
3459 let status = match funding_negotiation {
3460 FundingNegotiation::AwaitingAck { .. } => SpliceCandidateStatus::AwaitingAck {
3461 is_initiator,
3462 funding_feerate_sat_per_1000_weight,
3463 },
3464 FundingNegotiation::ConstructingTransaction { funding, .. } => {
3465 SpliceCandidateStatus::ConstructingTransaction {
3466 is_initiator,
3467 funding_feerate_sat_per_1000_weight,
3468 new_channel_value_satoshis: funding.get_value_satoshis(),
3469 }
3470 },
3471 FundingNegotiation::AwaitingSignatures { funding, .. } => {
3472 SpliceCandidateStatus::AwaitingSignatures {
3473 is_initiator,
3474 funding_feerate_sat_per_1000_weight,
3475 new_channel_value_satoshis: funding.get_value_satoshis(),
3476 txid: funding
3477 .get_funding_txid()
3478 .expect("a splice awaiting signatures should have a funding txid"),
3479 }
3480 },
3481 };
3482 candidates.push(SpliceCandidateDetails {
3483 contribution: self.negotiation_contribution.clone(),
3484 status,
3485 });
3486 }
3487 let confirmed_candidate = self.negotiated_candidates.iter().find_map(|candidate| {
3491 let confirmations = candidate.funding.get_funding_tx_confirmations(best_block_height);
3492 let txid = candidate
3493 .funding
3494 .get_funding_txid()
3495 .expect("negotiated candidates should have a funding txid");
3496 let splice_locked_sent = self.sent_funding_txid == Some(txid);
3499 if confirmations == 0 && !splice_locked_sent {
3500 return None;
3501 }
3502 Some(ConfirmedSpliceCandidate {
3503 txid,
3504 confirmations,
3505 confirmations_required: context
3506 .minimum_depth(&candidate.funding)
3507 .expect("set for a ready channel"),
3508 splice_locked_sent,
3509 })
3510 });
3511 SpliceDetails {
3512 candidates,
3513 confirmed_candidate,
3514 received_splice_locked_txid: self.received_funding_txid,
3515 }
3516 }
3517
3518 fn check_get_splice_locked<SP: SignerProvider>(
3519 &mut self, context: &ChannelContext<SP>, confirmed_funding_index: usize, height: u32,
3520 ) -> Option<msgs::SpliceLocked> {
3521 debug_assert!(confirmed_funding_index < self.negotiated_candidates.len());
3522
3523 if context.channel_state.is_quiescent() {
3527 return None;
3528 }
3529
3530 let funding = &self.negotiated_candidates[confirmed_funding_index].funding;
3531 if !context.check_funding_meets_minimum_depth(funding, height) {
3532 return None;
3533 }
3534
3535 let confirmed_funding_txid = match funding.get_funding_txid() {
3536 Some(funding_txid) => funding_txid,
3537 None => {
3538 debug_assert!(false);
3539 return None;
3540 },
3541 };
3542
3543 match self.sent_funding_txid {
3544 Some(sent_funding_txid) if confirmed_funding_txid == sent_funding_txid => None,
3545 _ => {
3546 let splice_locked = msgs::SpliceLocked {
3547 channel_id: context.channel_id(),
3548 splice_txid: confirmed_funding_txid,
3549 };
3550 self.sent_funding_txid = Some(splice_locked.splice_txid);
3551 Some(splice_locked)
3552 },
3553 }
3554 }
3555}
3556
3557#[derive(Debug)]
3558pub(crate) enum QuiescentAction {
3559 Splice {
3560 contribution: FundingContribution,
3561 locktime: LockTime,
3562 },
3563 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
3564 DoNothing,
3565}
3566
3567pub(super) enum QuiescentError {
3568 DoNothing,
3569 DiscardFunding { inputs: Vec<bitcoin::OutPoint>, outputs: Vec<bitcoin::ScriptBuf> },
3570 FailSplice(SpliceFundingFailed, NegotiationFailureReason),
3571}
3572
3573pub(crate) enum StfuResponse {
3574 Stfu(msgs::Stfu),
3575 SpliceInit(msgs::SpliceInit),
3576 TxInitRbf(msgs::TxInitRbf),
3577}
3578
3579struct ConfirmedTransaction<'a> {
3581 tx: &'a Transaction,
3582 txid: Option<Txid>,
3583}
3584
3585impl<'a> ConfirmedTransaction<'a> {
3586 pub fn tx(&self) -> &'a Transaction {
3588 self.tx
3589 }
3590
3591 pub fn txid(&mut self) -> Txid {
3593 *self.txid.get_or_insert_with(|| self.tx.compute_txid())
3594 }
3595}
3596
3597impl<'a> From<&'a Transaction> for ConfirmedTransaction<'a> {
3598 fn from(tx: &'a Transaction) -> Self {
3599 ConfirmedTransaction { tx, txid: None }
3600 }
3601}
3602
3603pub(super) struct ChannelContext<SP: SignerProvider> {
3605 config: LegacyChannelConfig,
3606
3607 prev_config: Option<(ChannelConfig, usize)>,
3611
3612 inbound_handshake_limits_override: Option<ChannelHandshakeLimits>,
3613
3614 user_id: u128,
3615
3616 channel_id: ChannelId,
3618 temporary_channel_id: Option<ChannelId>,
3621 channel_state: ChannelState,
3622
3623 #[cfg(any(test, feature = "_test_utils"))]
3631 pub(crate) announcement_sigs_state: AnnouncementSigsState,
3632 #[cfg(not(any(test, feature = "_test_utils")))]
3633 announcement_sigs_state: AnnouncementSigsState,
3634
3635 secp_ctx: Secp256k1<secp256k1::All>,
3636
3637 latest_monitor_update_id: u64,
3638
3639 holder_signer: SP::EcdsaSigner,
3640 shutdown_scriptpubkey: Option<ShutdownScript>,
3641 destination_script: ScriptBuf,
3642
3643 counterparty_next_commitment_transaction_number: u64,
3647 pending_inbound_htlcs: Vec<InboundHTLCOutput>,
3648 pending_outbound_htlcs: Vec<OutboundHTLCOutput>,
3649 holding_cell_htlc_updates: Vec<HTLCUpdateAwaitingACK>,
3650
3651 resend_order: RAACommitmentOrder,
3659
3660 monitor_pending_tx_signatures: bool,
3661 monitor_pending_channel_ready: bool,
3662 monitor_pending_revoke_and_ack: bool,
3663 monitor_pending_commitment_signed: bool,
3664
3665 monitor_pending_forwards: Vec<(PendingHTLCInfo, u64)>,
3671 monitor_pending_failures: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
3672 monitor_pending_finalized_fulfills: Vec<(HTLCSource, Option<AttributionData>)>,
3673 monitor_pending_update_adds: Vec<msgs::UpdateAddHTLC>,
3674
3675 signer_pending_revoke_and_ack: bool,
3683 signer_pending_commitment_update: bool,
3690 signer_pending_funding: bool,
3695 signer_pending_closing: bool,
3698 signer_pending_channel_ready: bool,
3701 signer_pending_stale_state_verification: Option<(u64, SecretKey)>,
3705
3706 pending_update_fee: Option<(u32, FeeUpdateState)>,
3713 #[cfg(any(test, feature = "_test_utils"))]
3719 pub(super) holding_cell_update_fee: Option<u32>,
3720 #[cfg(not(any(test, feature = "_test_utils")))]
3721 holding_cell_update_fee: Option<u32>,
3722 next_holder_htlc_id: u64,
3723 pub(super) next_counterparty_htlc_id: u64,
3724 pub(super) feerate_per_kw: u32,
3725
3726 update_time_counter: u32,
3731
3732 last_sent_closing_fee: Option<(u64, bool, ClosingSignedFeeRange, Option<Signature>)>,
3734 last_received_closing_sig: Option<Signature>,
3735 target_closing_feerate_sats_per_kw: Option<u32>,
3736
3737 pending_counterparty_closing_signed: Option<msgs::ClosingSigned>,
3741
3742 #[cfg(any(test, feature = "_test_utils"))]
3745 pub(crate) closing_fee_limits: Option<(u64, u64)>,
3746 #[cfg(not(any(test, feature = "_test_utils")))]
3747 closing_fee_limits: Option<(u64, u64)>,
3748
3749 expecting_peer_commitment_signed: bool,
3761
3762 pub(super) channel_creation_height: u32,
3766
3767 #[cfg(any(test, feature = "_test_utils"))]
3768 pub(crate) counterparty_dust_limit_satoshis: u64,
3769 #[cfg(not(any(test, feature = "_test_utils")))]
3770 counterparty_dust_limit_satoshis: u64,
3771
3772 #[cfg(any(test, feature = "_test_utils"))]
3773 pub(crate) holder_dust_limit_satoshis: u64,
3774 #[cfg(not(any(test, feature = "_test_utils")))]
3775 holder_dust_limit_satoshis: u64,
3776
3777 #[cfg(any(test, feature = "_test_utils"))]
3778 pub(crate) counterparty_max_htlc_value_in_flight_msat: u64,
3779 #[cfg(not(any(test, feature = "_test_utils")))]
3780 counterparty_max_htlc_value_in_flight_msat: u64,
3781
3782 #[cfg(any(test, feature = "_test_utils"))]
3783 pub(super) holder_max_htlc_value_in_flight_msat: u64,
3784 #[cfg(not(any(test, feature = "_test_utils")))]
3785 holder_max_htlc_value_in_flight_msat: u64,
3786
3787 counterparty_htlc_minimum_msat: u64,
3788 holder_htlc_minimum_msat: u64,
3789 #[cfg(any(test, feature = "_test_utils"))]
3790 pub counterparty_max_accepted_htlcs: u16,
3791 #[cfg(not(any(test, feature = "_test_utils")))]
3792 counterparty_max_accepted_htlcs: u16,
3793 holder_max_accepted_htlcs: u16,
3794 minimum_depth: Option<u32>,
3795
3796 counterparty_forwarding_info: Option<CounterpartyForwardingInfo>,
3797
3798 is_manual_broadcast: bool,
3801 is_batch_funding: Option<()>,
3802
3803 counterparty_next_commitment_point: Option<PublicKey>,
3804 counterparty_current_commitment_point: Option<PublicKey>,
3805 counterparty_node_id: PublicKey,
3806
3807 counterparty_shutdown_scriptpubkey: Option<ScriptBuf>,
3808
3809 commitment_secrets: CounterpartyCommitmentSecrets,
3810
3811 channel_update_status: ChannelUpdateStatus,
3812 closing_signed_in_flight: bool,
3819
3820 announcement_sigs: Option<(Signature, Signature)>,
3823
3824 pub workaround_lnd_bug_4006: Option<msgs::ChannelReady>,
3832
3833 funding_locked_txid_sent_in_reestablish: Option<Txid>,
3838
3839 sent_message_awaiting_response: Option<usize>,
3849
3850 latest_inbound_scid_alias: Option<u64>,
3861
3862 outbound_scid_alias: u64,
3867
3868 historical_scids: Vec<u64>,
3871
3872 channel_pending_event_emitted: bool,
3874
3875 funding_tx_broadcast_safe_event_emitted: bool,
3877
3878 initial_channel_ready_event_emitted: bool,
3880
3881 local_initiated_shutdown: Option<()>,
3883
3884 #[cfg(not(any(test, feature = "_test_utils")))]
3887 channel_keys_id: [u8; 32],
3888 #[cfg(any(test, feature = "_test_utils"))]
3889 pub channel_keys_id: [u8; 32],
3890
3891 blocked_monitor_updates: Vec<PendingChannelMonitorUpdate>,
3894
3895 pub interactive_tx_signing_session: Option<InteractiveTxSigningSession>,
3903}
3904
3905#[cfg(test)]
3906impl<SP: SignerProvider> fmt::Debug for ChannelContext<SP> {
3907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3908 f.debug_struct("ChannelContext").finish()
3909 }
3910}
3911
3912trait InitialRemoteCommitmentReceiver<SP: SignerProvider> {
3915 fn context(&self) -> &ChannelContext<SP>;
3916
3917 fn context_mut(&mut self) -> &mut ChannelContext<SP>;
3918
3919 fn funding(&self) -> &FundingScope;
3920
3921 fn funding_mut(&mut self) -> &mut FundingScope;
3922
3923 fn received_msg(&self) -> &'static str;
3924
3925 #[rustfmt::skip]
3926 fn check_counterparty_commitment_signature<L: Logger>(
3927 &self, sig: &Signature, holder_commitment_point: &HolderCommitmentPoint, logger: &L
3928 ) -> Result<CommitmentTransaction, ChannelError> {
3929 let funding_script = self.funding().get_funding_redeemscript();
3930
3931 let commitment_data = self.context().build_commitment_transaction(self.funding(),
3932 holder_commitment_point.next_transaction_number(), &holder_commitment_point.next_point(),
3933 true, false, logger);
3934 let initial_commitment_tx = commitment_data.tx;
3935 let trusted_tx = initial_commitment_tx.trust();
3936 let initial_commitment_bitcoin_tx = trusted_tx.built_transaction();
3937 let sighash = initial_commitment_bitcoin_tx.get_sighash_all(&funding_script, self.funding().get_value_satoshis());
3938 log_trace!(logger, "Checking {} tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} for channel {}.",
3940 self.received_msg(), log_bytes!(sig.serialize_compact()[..]), log_bytes!(self.funding().counterparty_funding_pubkey().serialize()),
3941 encode::serialize_hex(&initial_commitment_bitcoin_tx.transaction), log_bytes!(sighash[..]),
3942 encode::serialize_hex(&funding_script), &self.context().channel_id());
3943 secp_check!(self.context().secp_ctx.verify_ecdsa(&sighash, sig, self.funding().counterparty_funding_pubkey()), format!("Invalid {} signature from peer", self.received_msg()));
3944
3945 Ok(initial_commitment_tx)
3946 }
3947
3948 #[rustfmt::skip]
3949 fn initial_commitment_signed<L: Logger>(
3950 &mut self, channel_id: ChannelId, counterparty_signature: Signature, holder_commitment_point: &mut HolderCommitmentPoint,
3951 best_block: BlockLocator, signer_provider: &SP, logger: &L,
3952 ) -> Result<(ChannelMonitor<SP::EcdsaSigner>, CommitmentTransaction), ChannelError> {
3953 let initial_commitment_tx = match self.check_counterparty_commitment_signature(&counterparty_signature, holder_commitment_point, logger) {
3954 Ok(res) => res,
3955 Err(ChannelError::Close(e)) => {
3956 if !self.funding().is_outbound() {
3958 self.funding_mut().channel_transaction_parameters.funding_outpoint = None;
3959 }
3960 return Err(ChannelError::Close(e));
3961 },
3962 Err(e) => {
3963 panic!("unexpected error type from check_counterparty_commitment_signature {:?}", e);
3966 }
3967 };
3968 let context = self.context();
3969 let commitment_data = context.build_commitment_transaction(self.funding(),
3970 context.counterparty_next_commitment_transaction_number,
3971 &context.counterparty_next_commitment_point.unwrap(), false, false, logger);
3972 let counterparty_initial_commitment_tx = commitment_data.tx;
3973 let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
3974 let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
3975
3976 log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
3977 &context.channel_id(), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
3978
3979 let holder_commitment_tx = HolderCommitmentTransaction::new(
3980 initial_commitment_tx,
3981 counterparty_signature,
3982 Vec::new(),
3983 &self.funding().get_holder_pubkeys().funding_pubkey,
3984 &self.funding().counterparty_funding_pubkey()
3985 );
3986
3987 if context.holder_signer.validate_holder_commitment(&holder_commitment_tx, Vec::new()).is_err() {
3988 return Err(ChannelError::close("Failed to validate our commitment".to_owned()));
3989 }
3990
3991 let is_v2_established = self.is_v2_established();
3994 let context = self.context_mut();
3995 context.channel_id = channel_id;
3996
3997 assert!(!context.channel_state.is_monitor_update_in_progress()); if !is_v2_established {
3999 if context.is_batch_funding() {
4000 context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::WAITING_FOR_BATCH);
4001 } else {
4002 context.channel_state = ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
4003 }
4004 }
4005 if holder_commitment_point.advance(&context.holder_signer, &context.secp_ctx, logger).is_err() {
4006 debug_assert!(false, "We should be ready to advance our commitment point by the time we receive {}", self.received_msg());
4011 return Err(ChannelError::close("Failed to advance holder commitment point".to_owned()));
4012 }
4013
4014 let context = self.context();
4015 let funding = self.funding();
4016 let obscure_factor = get_commitment_transaction_number_obscure_factor(&funding.get_holder_pubkeys().payment_point, &funding.get_counterparty_pubkeys().payment_point, funding.is_outbound());
4017 let shutdown_script = context.shutdown_scriptpubkey.clone().map(|script| script.into_inner());
4018 let monitor_signer = signer_provider.derive_channel_signer(context.channel_keys_id);
4019 let channel_monitor = ChannelMonitor::new(
4022 context.secp_ctx.clone(), monitor_signer, shutdown_script,
4023 funding.get_holder_selected_contest_delay(), &context.destination_script,
4024 &funding.channel_transaction_parameters, funding.is_outbound(), obscure_factor,
4025 holder_commitment_tx, best_block, context.counterparty_node_id, context.channel_id(),
4026 context.is_manual_broadcast,
4027 );
4028 channel_monitor.provide_initial_counterparty_commitment_tx(
4029 counterparty_initial_commitment_tx.clone(),
4030 );
4031
4032 self.context_mut().counterparty_next_commitment_transaction_number -= 1;
4033
4034 Ok((channel_monitor, counterparty_initial_commitment_tx))
4035 }
4036
4037 fn is_v2_established(&self) -> bool;
4038}
4039
4040impl<SP: SignerProvider> InitialRemoteCommitmentReceiver<SP> for OutboundV1Channel<SP> {
4041 fn context(&self) -> &ChannelContext<SP> {
4042 &self.context
4043 }
4044
4045 fn context_mut(&mut self) -> &mut ChannelContext<SP> {
4046 &mut self.context
4047 }
4048
4049 fn funding(&self) -> &FundingScope {
4050 &self.funding
4051 }
4052
4053 fn funding_mut(&mut self) -> &mut FundingScope {
4054 &mut self.funding
4055 }
4056
4057 fn received_msg(&self) -> &'static str {
4058 "funding_signed"
4059 }
4060
4061 fn is_v2_established(&self) -> bool {
4062 false
4063 }
4064}
4065
4066impl<SP: SignerProvider> InitialRemoteCommitmentReceiver<SP> for InboundV1Channel<SP> {
4067 fn context(&self) -> &ChannelContext<SP> {
4068 &self.context
4069 }
4070
4071 fn context_mut(&mut self) -> &mut ChannelContext<SP> {
4072 &mut self.context
4073 }
4074
4075 fn funding(&self) -> &FundingScope {
4076 &self.funding
4077 }
4078
4079 fn funding_mut(&mut self) -> &mut FundingScope {
4080 &mut self.funding
4081 }
4082
4083 fn received_msg(&self) -> &'static str {
4084 "funding_created"
4085 }
4086
4087 fn is_v2_established(&self) -> bool {
4088 false
4089 }
4090}
4091
4092impl<SP: SignerProvider> InitialRemoteCommitmentReceiver<SP> for FundedChannel<SP> {
4093 fn context(&self) -> &ChannelContext<SP> {
4094 &self.context
4095 }
4096
4097 fn context_mut(&mut self) -> &mut ChannelContext<SP> {
4098 &mut self.context
4099 }
4100
4101 fn funding(&self) -> &FundingScope {
4102 &self.funding
4103 }
4104
4105 fn funding_mut(&mut self) -> &mut FundingScope {
4106 &mut self.funding
4107 }
4108
4109 fn received_msg(&self) -> &'static str {
4110 "commitment_signed"
4111 }
4112
4113 fn is_v2_established(&self) -> bool {
4114 let channel_parameters = &self.funding().channel_transaction_parameters;
4115 debug_assert!(channel_parameters.counterparty_parameters.is_some());
4118 channel_parameters.counterparty_parameters.as_ref().is_some_and(|counterparty_parameters| {
4119 self.context().channel_id().is_v2_channel_id(
4120 &channel_parameters.holder_pubkeys.revocation_basepoint,
4121 &counterparty_parameters.pubkeys.revocation_basepoint,
4122 )
4123 })
4124 }
4125}
4126
4127impl<SP: SignerProvider> ChannelContext<SP> {
4128 fn new_for_inbound_channel<'a, ES: EntropySource, F: FeeEstimator, L: Logger>(
4129 fee_estimator: &'a LowerBoundedFeeEstimator<F>, entropy_source: &'a ES,
4130 signer_provider: &'a SP, counterparty_node_id: PublicKey, their_features: &'a InitFeatures,
4131 user_id: u128, config: &'a UserConfig, current_chain_height: u32, logger: &'a L,
4132 trusted_channel_features: Option<TrustedChannelFeatures>, our_funding_satoshis: u64,
4133 counterparty_pubkeys: ChannelPublicKeys, channel_type: ChannelTypeFeatures,
4134 holder_selected_channel_reserve_satoshis: u64, msg_channel_reserve_satoshis: u64,
4135 msg_push_msat: u64, open_channel_fields: msgs::CommonOpenChannelFields,
4136 ) -> Result<(FundingScope, ChannelContext<SP>), ChannelError> {
4137 let logger = WithContext::from(
4138 logger,
4139 Some(counterparty_node_id),
4140 Some(open_channel_fields.temporary_channel_id),
4141 None,
4142 );
4143 let announce_for_forwarding =
4144 if (open_channel_fields.channel_flags & 1) == 1 { true } else { false };
4145
4146 let channel_value_satoshis =
4147 our_funding_satoshis.saturating_add(open_channel_fields.funding_satoshis);
4148 if channel_value_satoshis < MIN_CHANNEL_VALUE_SATOSHIS {
4149 return Err(ChannelError::close(format!(
4150 "Channel value must be at least 1000 satoshis. It was {channel_value_satoshis}",
4151 )));
4152 }
4153
4154 let channel_keys_id = signer_provider.generate_channel_keys_id(true, user_id);
4155 let holder_signer = signer_provider.derive_channel_signer(channel_keys_id);
4156
4157 if config.channel_handshake_config.our_to_self_delay < BREAKDOWN_TIMEOUT {
4158 return Err(ChannelError::close(format!(
4159 "Configured with an unreasonable our_to_self_delay ({}) putting user funds at risks. It must be greater than {BREAKDOWN_TIMEOUT}",
4160 config.channel_handshake_config.our_to_self_delay
4161 )));
4162 }
4163
4164 if channel_value_satoshis >= TOTAL_BITCOIN_SUPPLY_SATOSHIS {
4165 return Err(ChannelError::close(format!(
4166 "Funding must be smaller than the total bitcoin supply. It was {channel_value_satoshis}"
4167 )));
4168 }
4169 if !channel_type.supports_anchors_zero_fee_htlc_tx()
4170 && !channel_type.supports_anchor_zero_fee_commitments()
4171 && holder_selected_channel_reserve_satoshis == 0
4172 {
4173 return Err(ChannelError::close(
4174 "0-reserve is not allowed on legacy channels".to_owned(),
4175 ));
4176 }
4177 if msg_channel_reserve_satoshis > channel_value_satoshis {
4178 return Err(ChannelError::close(format!(
4179 "Bogus channel_reserve_satoshis ({msg_channel_reserve_satoshis}). Must be no greater than channel_value_satoshis: {channel_value_satoshis}"
4180 )));
4181 }
4182 let full_channel_value_msat =
4183 (channel_value_satoshis - msg_channel_reserve_satoshis) * 1000;
4184 if msg_push_msat > full_channel_value_msat {
4185 return Err(ChannelError::close(format!(
4186 "push_msat {msg_push_msat} was larger than channel amount minus reserve ({full_channel_value_msat})"
4187 )));
4188 }
4189 if open_channel_fields.dust_limit_satoshis > channel_value_satoshis {
4190 return Err(ChannelError::close(format!(
4191 "dust_limit_satoshis {} was larger than channel_value_satoshis {channel_value_satoshis}. Peer never wants payout outputs?",
4192 open_channel_fields.dust_limit_satoshis
4193 )));
4194 }
4195 if open_channel_fields.htlc_minimum_msat >= full_channel_value_msat {
4196 return Err(ChannelError::close(format!(
4197 "Minimum htlc value ({}) was larger than full channel value ({full_channel_value_msat})",
4198 open_channel_fields.htlc_minimum_msat
4199 )));
4200 }
4201 FundedChannel::<SP>::check_remote_fee(
4202 &channel_type,
4203 fee_estimator,
4204 open_channel_fields.commitment_feerate_sat_per_1000_weight,
4205 None,
4206 &&logger,
4207 )?;
4208
4209 let max_counterparty_selected_contest_delay = u16::min(
4210 config.channel_handshake_limits.their_to_self_delay,
4211 MAX_LOCAL_BREAKDOWN_TIMEOUT,
4212 );
4213 if open_channel_fields.to_self_delay > max_counterparty_selected_contest_delay {
4214 return Err(ChannelError::close(format!(
4215 "They wanted our payments to be delayed by a needlessly long period. Upper limit: {max_counterparty_selected_contest_delay}. Actual: {}",
4216 open_channel_fields.to_self_delay
4217 )));
4218 }
4219 if open_channel_fields.max_accepted_htlcs < 1 {
4220 return Err(ChannelError::close(
4221 "0 max_accepted_htlcs makes for a useless channel".to_owned(),
4222 ));
4223 }
4224 if open_channel_fields.max_accepted_htlcs > max_htlcs(&channel_type) {
4225 return Err(ChannelError::close(format!(
4226 "max_accepted_htlcs was {}. It must not be larger than {}",
4227 open_channel_fields.max_accepted_htlcs,
4228 max_htlcs(&channel_type)
4229 )));
4230 }
4231
4232 if channel_value_satoshis < config.channel_handshake_limits.min_funding_satoshis {
4234 return Err(ChannelError::close(format!(
4235 "Funding satoshis ({channel_value_satoshis}) is less than the user specified limit ({})",
4236 config.channel_handshake_limits.min_funding_satoshis
4237 )));
4238 }
4239 if open_channel_fields.htlc_minimum_msat
4240 > config.channel_handshake_limits.max_htlc_minimum_msat
4241 {
4242 return Err(ChannelError::close(format!(
4243 "htlc_minimum_msat ({}) is higher than the user specified limit ({})",
4244 open_channel_fields.htlc_minimum_msat,
4245 config.channel_handshake_limits.max_htlc_minimum_msat
4246 )));
4247 }
4248 if open_channel_fields.max_htlc_value_in_flight_msat
4249 < config.channel_handshake_limits.min_max_htlc_value_in_flight_msat
4250 {
4251 return Err(ChannelError::close(format!(
4252 "max_htlc_value_in_flight_msat ({}) is less than the user specified limit ({})",
4253 open_channel_fields.max_htlc_value_in_flight_msat,
4254 config.channel_handshake_limits.min_max_htlc_value_in_flight_msat
4255 )));
4256 }
4257 if msg_channel_reserve_satoshis
4258 > config.channel_handshake_limits.max_channel_reserve_satoshis
4259 {
4260 return Err(ChannelError::close(format!(
4261 "channel_reserve_satoshis ({msg_channel_reserve_satoshis}) is higher than the user specified limit ({})",
4262 config.channel_handshake_limits.max_channel_reserve_satoshis
4263 )));
4264 }
4265 if open_channel_fields.max_accepted_htlcs
4266 < config.channel_handshake_limits.min_max_accepted_htlcs
4267 {
4268 return Err(ChannelError::close(format!(
4269 "max_accepted_htlcs ({}) is less than the user specified limit ({})",
4270 open_channel_fields.max_accepted_htlcs,
4271 config.channel_handshake_limits.min_max_accepted_htlcs
4272 )));
4273 }
4274 if open_channel_fields.dust_limit_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS {
4275 return Err(ChannelError::close(format!(
4276 "dust_limit_satoshis ({}) is less than the implementation limit ({MIN_CHAN_DUST_LIMIT_SATOSHIS})",
4277 open_channel_fields.dust_limit_satoshis
4278 )));
4279 }
4280
4281 let max_chan_dust_limit_satoshis = if channel_type.supports_anchors_zero_fee_htlc_tx()
4282 || channel_type.supports_anchor_zero_fee_commitments()
4283 {
4284 MAX_CHAN_DUST_LIMIT_SATOSHIS
4285 } else {
4286 MAX_LEGACY_CHAN_DUST_LIMIT_SATOSHIS
4287 };
4288 if open_channel_fields.dust_limit_satoshis > max_chan_dust_limit_satoshis {
4289 return Err(ChannelError::close(format!(
4290 "dust_limit_satoshis ({}) is greater than the implementation limit ({max_chan_dust_limit_satoshis})",
4291 open_channel_fields.dust_limit_satoshis
4292 )));
4293 }
4294
4295 if config.channel_handshake_limits.force_announced_channel_preference {
4298 if config.channel_handshake_config.announce_for_forwarding != announce_for_forwarding {
4299 return Err(ChannelError::close(String::from(
4300 "Peer tried to open channel but their announcement preference is different from ours"
4301 )));
4302 }
4303 }
4304
4305 if holder_selected_channel_reserve_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS
4306 && holder_selected_channel_reserve_satoshis != 0
4307 {
4308 return Err(ChannelError::close(format!(
4311 "Suitable channel reserve not found. remote_channel_reserve was ({holder_selected_channel_reserve_satoshis}). dust_limit_satoshis is ({MIN_CHAN_DUST_LIMIT_SATOSHIS})."
4312 )));
4313 }
4314 if holder_selected_channel_reserve_satoshis * 1000 >= full_channel_value_msat {
4315 return Err(ChannelError::close(format!(
4316 "Suitable channel reserve not found. remote_channel_reserve was ({})msats. Channel value is ({full_channel_value_msat} - {msg_push_msat})msats.",
4317 holder_selected_channel_reserve_satoshis * 1000
4318 )));
4319 }
4320 if msg_channel_reserve_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS {
4321 log_debug!(
4322 logger,
4323 "channel_reserve_satoshis ({msg_channel_reserve_satoshis}) is smaller than our dust limit ({MIN_CHAN_DUST_LIMIT_SATOSHIS}). We can broadcast \
4324 stale states without any risk, implying this channel is very insecure for our counterparty.");
4325 }
4326 if holder_selected_channel_reserve_satoshis < open_channel_fields.dust_limit_satoshis
4327 && holder_selected_channel_reserve_satoshis != 0
4328 {
4329 return Err(ChannelError::close(format!(
4330 "Dust limit ({}) too high for the channel reserve we require the remote to keep ({holder_selected_channel_reserve_satoshis})",
4331 open_channel_fields.dust_limit_satoshis
4332 )));
4333 }
4334
4335 debug_assert!(our_funding_satoshis == 0 || msg_push_msat == 0);
4337 let value_to_self_msat = our_funding_satoshis * 1000 + msg_push_msat;
4338
4339 let counterparty_shutdown_scriptpubkey =
4340 if their_features.supports_upfront_shutdown_script() {
4341 match &open_channel_fields.shutdown_scriptpubkey {
4342 &Some(ref script) => {
4343 if script.len() == 0 {
4345 None
4346 } else {
4347 if !script::is_bolt2_compliant(&script, their_features) {
4348 return Err(ChannelError::close(format!(
4349 "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: {script}"
4350 )));
4351 }
4352 Some(script.clone())
4353 }
4354 },
4355 &None => {
4357 return Err(ChannelError::close(String::from(
4358 "Peer is signaling upfront_shutdown but we don't get any script. Use 0-length script to opt-out"
4359 )));
4360 },
4361 }
4362 } else {
4363 None
4364 };
4365
4366 let shutdown_scriptpubkey =
4367 if config.channel_handshake_config.commit_upfront_shutdown_pubkey {
4368 match signer_provider.get_shutdown_scriptpubkey() {
4369 Ok(scriptpubkey) => Some(scriptpubkey),
4370 Err(_) => {
4371 return Err(ChannelError::close(
4372 "Failed to get upfront shutdown scriptpubkey".to_owned(),
4373 ))
4374 },
4375 }
4376 } else {
4377 None
4378 };
4379
4380 if let Some(shutdown_scriptpubkey) = &shutdown_scriptpubkey {
4381 if !shutdown_scriptpubkey.is_compatible(&their_features) {
4382 return Err(ChannelError::close(format!(
4383 "Provided a scriptpubkey format not accepted by peer: {shutdown_scriptpubkey}"
4384 )));
4385 }
4386 }
4387
4388 let destination_script = match signer_provider.get_destination_script(channel_keys_id) {
4389 Ok(script) => script,
4390 Err(_) => {
4391 return Err(ChannelError::close("Failed to get destination script".to_owned()))
4392 },
4393 };
4394
4395 let mut secp_ctx = Secp256k1::new();
4396 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
4397
4398 let minimum_depth = if trusted_channel_features.is_some_and(|f| f.is_0conf()) {
4399 Some(0)
4400 } else {
4401 Some(cmp::max(config.channel_handshake_config.minimum_depth, 1))
4402 };
4403
4404 let pubkeys = holder_signer.pubkeys(&secp_ctx);
4407
4408 let funding = FundingScope {
4409 value_to_self_msat,
4410 counterparty_selected_channel_reserve_satoshis: Some(msg_channel_reserve_satoshis),
4411 holder_selected_channel_reserve_satoshis,
4412
4413 #[cfg(debug_assertions)]
4414 holder_prev_commitment_tx_balance: Mutex::new((
4415 value_to_self_msat,
4416 (channel_value_satoshis * 1000 - msg_push_msat).saturating_sub(value_to_self_msat),
4417 )),
4418 #[cfg(debug_assertions)]
4419 counterparty_prev_commitment_tx_balance: Mutex::new((
4420 value_to_self_msat,
4421 (channel_value_satoshis * 1000 - msg_push_msat).saturating_sub(value_to_self_msat),
4422 )),
4423
4424 #[cfg(any(test, fuzzing))]
4425 next_local_fee: Mutex::new(PredictedNextFee::default()),
4426 #[cfg(any(test, fuzzing))]
4427 next_remote_fee: Mutex::new(PredictedNextFee::default()),
4428
4429 channel_transaction_parameters: ChannelTransactionParameters {
4430 holder_pubkeys: pubkeys,
4431 holder_selected_contest_delay: config.channel_handshake_config.our_to_self_delay,
4432 is_outbound_from_holder: false,
4433 counterparty_parameters: Some(CounterpartyChannelTransactionParameters {
4434 selected_contest_delay: open_channel_fields.to_self_delay,
4435 pubkeys: counterparty_pubkeys,
4436 }),
4437 funding_outpoint: None,
4438 splice_parent_funding_txid: None,
4439 channel_type_features: channel_type.clone(),
4440 channel_value_satoshis,
4441 },
4442 funding_transaction: None,
4443 funding_tx_confirmed_in: None,
4444 funding_tx_confirmation_height: 0,
4445 short_channel_id: None,
4446 minimum_depth_override: None,
4447 };
4448 let channel_context = ChannelContext {
4449 user_id,
4450
4451 config: LegacyChannelConfig {
4452 options: config.channel_config.clone(),
4453 announce_for_forwarding,
4454 commit_upfront_shutdown_pubkey: config
4455 .channel_handshake_config
4456 .commit_upfront_shutdown_pubkey,
4457 },
4458
4459 prev_config: None,
4460
4461 inbound_handshake_limits_override: None,
4462
4463 temporary_channel_id: Some(open_channel_fields.temporary_channel_id),
4464 channel_id: open_channel_fields.temporary_channel_id,
4465 channel_state: ChannelState::NegotiatingFunding(
4466 NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT,
4467 ),
4468 announcement_sigs_state: AnnouncementSigsState::NotSent,
4469 secp_ctx,
4470
4471 latest_monitor_update_id: 0,
4472
4473 holder_signer,
4474 shutdown_scriptpubkey,
4475 destination_script,
4476
4477 counterparty_next_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
4478
4479 pending_inbound_htlcs: Vec::new(),
4480 pending_outbound_htlcs: Vec::new(),
4481 holding_cell_htlc_updates: Vec::new(),
4482 pending_update_fee: None,
4483 holding_cell_update_fee: None,
4484 next_holder_htlc_id: 0,
4485 next_counterparty_htlc_id: 0,
4486 update_time_counter: 1,
4487
4488 resend_order: RAACommitmentOrder::CommitmentFirst,
4489
4490 monitor_pending_tx_signatures: false,
4491 monitor_pending_channel_ready: false,
4492 monitor_pending_revoke_and_ack: false,
4493 monitor_pending_commitment_signed: false,
4494 monitor_pending_forwards: Vec::new(),
4495 monitor_pending_failures: Vec::new(),
4496 monitor_pending_finalized_fulfills: Vec::new(),
4497 monitor_pending_update_adds: Vec::new(),
4498
4499 signer_pending_revoke_and_ack: false,
4500 signer_pending_commitment_update: false,
4501 signer_pending_funding: false,
4502 signer_pending_closing: false,
4503 signer_pending_channel_ready: false,
4504 signer_pending_stale_state_verification: None,
4505
4506 last_sent_closing_fee: None,
4507 last_received_closing_sig: None,
4508 pending_counterparty_closing_signed: None,
4509 expecting_peer_commitment_signed: false,
4510 closing_fee_limits: None,
4511 target_closing_feerate_sats_per_kw: None,
4512
4513 channel_creation_height: current_chain_height,
4514
4515 feerate_per_kw: open_channel_fields.commitment_feerate_sat_per_1000_weight,
4516 counterparty_dust_limit_satoshis: open_channel_fields.dust_limit_satoshis,
4517 holder_dust_limit_satoshis: MIN_CHAN_DUST_LIMIT_SATOSHIS,
4518 counterparty_max_htlc_value_in_flight_msat: cmp::min(
4519 open_channel_fields.max_htlc_value_in_flight_msat,
4520 channel_value_satoshis * 1000,
4521 ),
4522 holder_max_htlc_value_in_flight_msat: get_holder_max_htlc_value_in_flight_msat(
4523 channel_value_satoshis,
4524 announce_for_forwarding,
4525 &config.channel_handshake_config,
4526 ),
4527 counterparty_htlc_minimum_msat: open_channel_fields.htlc_minimum_msat,
4528 holder_htlc_minimum_msat: if config.channel_handshake_config.our_htlc_minimum_msat == 0
4529 {
4530 1
4531 } else {
4532 config.channel_handshake_config.our_htlc_minimum_msat
4533 },
4534 counterparty_max_accepted_htlcs: open_channel_fields.max_accepted_htlcs,
4535 holder_max_accepted_htlcs: cmp::min(
4536 config.channel_handshake_config.our_max_accepted_htlcs,
4537 max_htlcs(&channel_type),
4538 ),
4539 minimum_depth,
4540
4541 counterparty_forwarding_info: None,
4542
4543 is_batch_funding: None,
4544
4545 counterparty_next_commitment_point: Some(
4546 open_channel_fields.first_per_commitment_point,
4547 ),
4548 counterparty_current_commitment_point: None,
4549 counterparty_node_id,
4550
4551 counterparty_shutdown_scriptpubkey,
4552
4553 commitment_secrets: CounterpartyCommitmentSecrets::new(),
4554
4555 channel_update_status: ChannelUpdateStatus::Enabled,
4556 closing_signed_in_flight: false,
4557
4558 announcement_sigs: None,
4559
4560 workaround_lnd_bug_4006: None,
4561 funding_locked_txid_sent_in_reestablish: None,
4562 sent_message_awaiting_response: None,
4563
4564 latest_inbound_scid_alias: None,
4565 outbound_scid_alias: 0,
4566 historical_scids: Vec::new(),
4567
4568 channel_pending_event_emitted: false,
4569 funding_tx_broadcast_safe_event_emitted: false,
4570 initial_channel_ready_event_emitted: false,
4571
4572 channel_keys_id,
4573
4574 local_initiated_shutdown: None,
4575
4576 blocked_monitor_updates: Vec::new(),
4577
4578 is_manual_broadcast: false,
4579
4580 interactive_tx_signing_session: None,
4581 };
4582
4583 let funders_amount_msat =
4586 funding.get_value_satoshis() * 1000 - funding.get_value_to_self_msat();
4587 let htlc_candidate = None;
4588 let addl_nondust_htlc_count = MIN_AFFORDABLE_HTLC_COUNT;
4589 let dust_exposure_limiting_feerate = channel_context
4590 .get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
4591 let (remote_stats, _remote_htlcs) = channel_context
4592 .get_next_remote_commitment_stats(
4593 &funding,
4594 htlc_candidate,
4595 NextCommitmentView::ValidatingOwnUpdate,
4596 addl_nondust_htlc_count,
4597 channel_context.feerate_per_kw,
4598 false,
4599 dust_exposure_limiting_feerate,
4600 )
4601 .map_err(|()| {
4602 ChannelError::close(format!(
4603 "Funding amount ({} sats) can't even pay fee for initial commitment transaction.",
4604 funders_amount_msat / 1000
4605 ))
4606 })?;
4607
4608 if remote_stats.commitment_stats.counterparty_balance_msat / 1000
4611 < funding.holder_selected_channel_reserve_satoshis
4612 {
4613 return Err(ChannelError::close(
4614 "Insufficient funding amount for initial reserve".to_owned(),
4615 ));
4616 }
4617
4618 Ok((funding, channel_context))
4619 }
4620
4621 fn new_for_outbound_channel<'a, ES: EntropySource, F: FeeEstimator, L: Logger>(
4622 fee_estimator: &'a LowerBoundedFeeEstimator<F>, entropy_source: &'a ES,
4623 signer_provider: &'a SP, counterparty_node_id: PublicKey, their_features: &'a InitFeatures,
4624 funding_satoshis: u64, push_msat: u64, user_id: u128, config: &'a UserConfig,
4625 current_chain_height: u32, outbound_scid_alias: u64,
4626 temporary_channel_id_fn: Option<impl Fn(&ChannelPublicKeys) -> ChannelId>,
4627 holder_selected_channel_reserve_satoshis: u64, channel_keys_id: [u8; 32],
4628 holder_signer: SP::EcdsaSigner, _logger: L,
4629 ) -> Result<(FundingScope, ChannelContext<SP>), APIError> {
4630 let channel_value_satoshis = funding_satoshis;
4632
4633 let holder_selected_contest_delay = config.channel_handshake_config.our_to_self_delay;
4634
4635 if !their_features.supports_wumbo()
4636 && channel_value_satoshis > MAX_FUNDING_SATOSHIS_NO_WUMBO
4637 {
4638 return Err(APIError::APIMisuseError {
4639 err: format!(
4640 "funding_value must not exceed {MAX_FUNDING_SATOSHIS_NO_WUMBO}, it was {channel_value_satoshis}"
4641 ),
4642 });
4643 }
4644 if channel_value_satoshis >= TOTAL_BITCOIN_SUPPLY_SATOSHIS {
4645 return Err(APIError::APIMisuseError {
4646 err: format!(
4647 "funding_value must be smaller than the total bitcoin supply, it was {channel_value_satoshis}"
4648 ),
4649 });
4650 }
4651 let channel_value_msat = channel_value_satoshis * 1000;
4652 if push_msat > channel_value_msat {
4653 return Err(APIError::APIMisuseError {
4654 err: format!(
4655 "Push value ({push_msat}) was larger than channel_value ({channel_value_msat})"
4656 ),
4657 });
4658 }
4659 if holder_selected_contest_delay < BREAKDOWN_TIMEOUT {
4660 return Err(APIError::APIMisuseError {
4661 err: format!(
4662 "Configured with an unreasonable our_to_self_delay ({holder_selected_contest_delay}) putting user funds at risks"
4663 ),
4664 });
4665 }
4666
4667 let channel_type = get_initial_channel_type(&config, their_features);
4668 if !channel_type.supports_anchors_zero_fee_htlc_tx()
4669 && !channel_type.supports_anchor_zero_fee_commitments()
4670 && holder_selected_channel_reserve_satoshis == 0
4671 {
4672 return Err(APIError::APIMisuseError {
4673 err: "0-reserve is not allowed on legacy channels".to_owned(),
4674 });
4675 }
4676 debug_assert!(!channel_type.supports_any_optional_bits());
4677 debug_assert!(!channel_type
4678 .requires_unknown_bits_from(&channelmanager::provided_channel_type_features(&config)));
4679
4680 let commitment_feerate =
4681 selected_commitment_sat_per_1000_weight(&fee_estimator, &channel_type);
4682
4683 let value_to_self_msat = channel_value_satoshis * 1000 - push_msat;
4684
4685 let mut secp_ctx = Secp256k1::new();
4686 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
4687
4688 let shutdown_scriptpubkey =
4689 if config.channel_handshake_config.commit_upfront_shutdown_pubkey {
4690 match signer_provider.get_shutdown_scriptpubkey() {
4691 Ok(scriptpubkey) => Some(scriptpubkey),
4692 Err(_) => {
4693 return Err(APIError::ChannelUnavailable {
4694 err: "Failed to get shutdown scriptpubkey".to_owned(),
4695 })
4696 },
4697 }
4698 } else {
4699 None
4700 };
4701
4702 if let Some(shutdown_scriptpubkey) = &shutdown_scriptpubkey {
4703 if !shutdown_scriptpubkey.is_compatible(&their_features) {
4704 return Err(APIError::IncompatibleShutdownScript {
4705 script: shutdown_scriptpubkey.clone(),
4706 });
4707 }
4708 }
4709
4710 let destination_script = match signer_provider.get_destination_script(channel_keys_id) {
4711 Ok(script) => script,
4712 Err(_) => {
4713 return Err(APIError::ChannelUnavailable {
4714 err: "Failed to get destination script".to_owned(),
4715 })
4716 },
4717 };
4718
4719 let pubkeys = holder_signer.pubkeys(&secp_ctx);
4720 let temporary_channel_id = temporary_channel_id_fn
4721 .map(|f| f(&pubkeys))
4722 .unwrap_or_else(|| ChannelId::temporary_from_entropy_source(entropy_source));
4723
4724 let funding = FundingScope {
4725 value_to_self_msat,
4726 counterparty_selected_channel_reserve_satoshis: None, holder_selected_channel_reserve_satoshis,
4728
4729 #[cfg(debug_assertions)]
4732 holder_prev_commitment_tx_balance: Mutex::new((
4733 channel_value_satoshis * 1000 - push_msat,
4734 push_msat,
4735 )),
4736 #[cfg(debug_assertions)]
4737 counterparty_prev_commitment_tx_balance: Mutex::new((
4738 channel_value_satoshis * 1000 - push_msat,
4739 push_msat,
4740 )),
4741
4742 #[cfg(any(test, fuzzing))]
4743 next_local_fee: Mutex::new(PredictedNextFee::default()),
4744 #[cfg(any(test, fuzzing))]
4745 next_remote_fee: Mutex::new(PredictedNextFee::default()),
4746
4747 channel_transaction_parameters: ChannelTransactionParameters {
4748 holder_pubkeys: pubkeys,
4749 holder_selected_contest_delay: config.channel_handshake_config.our_to_self_delay,
4750 is_outbound_from_holder: true,
4751 counterparty_parameters: None,
4752 funding_outpoint: None,
4753 splice_parent_funding_txid: None,
4754 channel_type_features: channel_type.clone(),
4755 channel_value_satoshis,
4757 },
4758 funding_transaction: None,
4759 funding_tx_confirmed_in: None,
4760 funding_tx_confirmation_height: 0,
4761 short_channel_id: None,
4762 minimum_depth_override: None,
4763 };
4764 let channel_context = Self {
4765 user_id,
4766
4767 config: LegacyChannelConfig {
4768 options: config.channel_config.clone(),
4769 announce_for_forwarding: config.channel_handshake_config.announce_for_forwarding,
4770 commit_upfront_shutdown_pubkey: config
4771 .channel_handshake_config
4772 .commit_upfront_shutdown_pubkey,
4773 },
4774
4775 prev_config: None,
4776
4777 inbound_handshake_limits_override: Some(config.channel_handshake_limits.clone()),
4778
4779 channel_id: temporary_channel_id,
4780 temporary_channel_id: Some(temporary_channel_id),
4781 channel_state: ChannelState::NegotiatingFunding(NegotiatingFundingFlags::OUR_INIT_SENT),
4782 announcement_sigs_state: AnnouncementSigsState::NotSent,
4783 secp_ctx,
4784
4785 latest_monitor_update_id: 0,
4786
4787 holder_signer,
4788 shutdown_scriptpubkey,
4789 destination_script,
4790
4791 counterparty_next_commitment_transaction_number: INITIAL_COMMITMENT_NUMBER,
4792
4793 pending_inbound_htlcs: Vec::new(),
4794 pending_outbound_htlcs: Vec::new(),
4795 holding_cell_htlc_updates: Vec::new(),
4796 pending_update_fee: None,
4797 holding_cell_update_fee: None,
4798 next_holder_htlc_id: 0,
4799 next_counterparty_htlc_id: 0,
4800 update_time_counter: 1,
4801
4802 resend_order: RAACommitmentOrder::CommitmentFirst,
4803
4804 monitor_pending_tx_signatures: false,
4805 monitor_pending_channel_ready: false,
4806 monitor_pending_revoke_and_ack: false,
4807 monitor_pending_commitment_signed: false,
4808 monitor_pending_forwards: Vec::new(),
4809 monitor_pending_failures: Vec::new(),
4810 monitor_pending_finalized_fulfills: Vec::new(),
4811 monitor_pending_update_adds: Vec::new(),
4812
4813 signer_pending_revoke_and_ack: false,
4814 signer_pending_commitment_update: false,
4815 signer_pending_funding: false,
4816 signer_pending_closing: false,
4817 signer_pending_channel_ready: false,
4818 signer_pending_stale_state_verification: None,
4819
4820 last_sent_closing_fee: None,
4821 last_received_closing_sig: None,
4822 pending_counterparty_closing_signed: None,
4823 expecting_peer_commitment_signed: false,
4824 closing_fee_limits: None,
4825 target_closing_feerate_sats_per_kw: None,
4826
4827 channel_creation_height: current_chain_height,
4828
4829 feerate_per_kw: commitment_feerate,
4830 counterparty_dust_limit_satoshis: 0,
4831 holder_dust_limit_satoshis: MIN_CHAN_DUST_LIMIT_SATOSHIS,
4832 counterparty_max_htlc_value_in_flight_msat: 0,
4833 holder_max_htlc_value_in_flight_msat: get_holder_max_htlc_value_in_flight_msat(
4836 channel_value_satoshis,
4837 config.channel_handshake_config.announce_for_forwarding,
4838 &config.channel_handshake_config,
4839 ),
4840 counterparty_htlc_minimum_msat: 0,
4841 holder_htlc_minimum_msat: if config.channel_handshake_config.our_htlc_minimum_msat == 0
4842 {
4843 1
4844 } else {
4845 config.channel_handshake_config.our_htlc_minimum_msat
4846 },
4847 counterparty_max_accepted_htlcs: 0,
4848 holder_max_accepted_htlcs: cmp::min(
4849 config.channel_handshake_config.our_max_accepted_htlcs,
4850 max_htlcs(&channel_type),
4851 ),
4852 minimum_depth: None, counterparty_forwarding_info: None,
4855
4856 is_batch_funding: None,
4857
4858 counterparty_next_commitment_point: None,
4859 counterparty_current_commitment_point: None,
4860 counterparty_node_id,
4861
4862 counterparty_shutdown_scriptpubkey: None,
4863
4864 commitment_secrets: CounterpartyCommitmentSecrets::new(),
4865
4866 channel_update_status: ChannelUpdateStatus::Enabled,
4867 closing_signed_in_flight: false,
4868
4869 announcement_sigs: None,
4870
4871 workaround_lnd_bug_4006: None,
4872 funding_locked_txid_sent_in_reestablish: None,
4873 sent_message_awaiting_response: None,
4874
4875 latest_inbound_scid_alias: None,
4876 outbound_scid_alias,
4877 historical_scids: Vec::new(),
4878
4879 channel_pending_event_emitted: false,
4880 funding_tx_broadcast_safe_event_emitted: false,
4881 initial_channel_ready_event_emitted: false,
4882
4883 channel_keys_id,
4884
4885 blocked_monitor_updates: Vec::new(),
4886 local_initiated_shutdown: None,
4887 is_manual_broadcast: false,
4888
4889 interactive_tx_signing_session: None,
4890 };
4891
4892 let htlc_candidate = None;
4893 let addl_nondust_htlc_count = MIN_AFFORDABLE_HTLC_COUNT;
4894 let dust_exposure_limiting_feerate = channel_context
4895 .get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
4896 let _local_stats = channel_context
4897 .get_next_local_commitment_stats(
4898 &funding,
4899 htlc_candidate,
4900 NextCommitmentView::ValidatingOwnUpdate,
4901 addl_nondust_htlc_count,
4902 channel_context.feerate_per_kw,
4903 false,
4904 dust_exposure_limiting_feerate,
4905 )
4906 .map_err(|()| APIError::APIMisuseError {
4907 err: format!(
4908 "Funding amount ({}) can't even pay fee for initial commitment transaction.",
4909 funding.get_value_to_self_msat() / 1000
4910 ),
4911 })?;
4912
4913 Ok((funding, channel_context))
4914 }
4915
4916 pub fn get_update_time_counter(&self) -> u32 {
4918 self.update_time_counter
4919 }
4920
4921 pub fn get_latest_monitor_update_id(&self) -> u64 {
4922 self.latest_monitor_update_id
4923 }
4924
4925 pub fn get_latest_unblocked_monitor_update_id(&self) -> u64 {
4926 if self.blocked_monitor_updates.is_empty() {
4927 return self.get_latest_monitor_update_id();
4928 }
4929 self.blocked_monitor_updates[0].update.update_id - 1
4930 }
4931
4932 pub fn should_announce(&self) -> bool {
4933 self.config.announce_for_forwarding
4934 }
4935
4936 pub fn get_outbound_forwarding_fee_base_msat(&self) -> u32 {
4939 self.config.options.forwarding_fee_base_msat
4940 }
4941
4942 pub fn have_received_message(&self) -> bool {
4944 self.channel_state
4945 > ChannelState::NegotiatingFunding(NegotiatingFundingFlags::OUR_INIT_SENT)
4946 }
4947
4948 pub fn is_usable(&self) -> bool {
4951 matches!(self.channel_state, ChannelState::ChannelReady(_))
4952 && !self.channel_state.is_local_shutdown_sent()
4953 && !self.channel_state.is_remote_shutdown_sent()
4954 && !self.monitor_pending_channel_ready
4955 }
4956
4957 pub fn shutdown_state(&self) -> ChannelShutdownState {
4959 match self.channel_state {
4960 ChannelState::AwaitingChannelReady(_) | ChannelState::ChannelReady(_) => {
4961 if self.channel_state.is_local_shutdown_sent()
4962 && !self.channel_state.is_remote_shutdown_sent()
4963 {
4964 ChannelShutdownState::ShutdownInitiated
4965 } else if (self.channel_state.is_local_shutdown_sent()
4966 || self.channel_state.is_remote_shutdown_sent())
4967 && !self.closing_negotiation_ready()
4968 {
4969 ChannelShutdownState::ResolvingHTLCs
4970 } else if (self.channel_state.is_local_shutdown_sent()
4971 || self.channel_state.is_remote_shutdown_sent())
4972 && self.closing_negotiation_ready()
4973 {
4974 ChannelShutdownState::NegotiatingClosingFee
4975 } else {
4976 ChannelShutdownState::NotShuttingDown
4977 }
4978 },
4979 ChannelState::ShutdownComplete => ChannelShutdownState::ShutdownComplete,
4980 _ => ChannelShutdownState::NotShuttingDown,
4981 }
4982 }
4983
4984 fn closing_negotiation_ready(&self) -> bool {
4985 let is_ready_to_close = match self.channel_state {
4986 ChannelState::AwaitingChannelReady(flags) => {
4987 flags & FundedStateFlags::ALL
4988 == FundedStateFlags::LOCAL_SHUTDOWN_SENT
4989 | FundedStateFlags::REMOTE_SHUTDOWN_SENT
4990 },
4991 ChannelState::ChannelReady(flags) => {
4992 flags
4993 == FundedStateFlags::LOCAL_SHUTDOWN_SENT
4994 | FundedStateFlags::REMOTE_SHUTDOWN_SENT
4995 },
4996 _ => false,
4997 };
4998 self.pending_inbound_htlcs.is_empty()
4999 && self.pending_outbound_htlcs.is_empty()
5000 && self.pending_update_fee.is_none()
5001 && is_ready_to_close
5002 }
5003
5004 pub fn is_live(&self) -> bool {
5008 self.is_usable() && !self.channel_state.is_peer_disconnected()
5009 }
5010
5011 pub fn is_connected(&self) -> bool {
5014 !self.channel_state.is_peer_disconnected()
5015 }
5016
5017 pub fn is_enabled(&self) -> bool {
5019 self.is_usable()
5020 && match self.channel_update_status {
5021 ChannelUpdateStatus::Enabled | ChannelUpdateStatus::DisabledStaged(_) => true,
5022 ChannelUpdateStatus::Disabled | ChannelUpdateStatus::EnabledStaged(_) => false,
5023 }
5024 }
5025
5026 pub fn is_monitor_or_signer_pending_channel_update(&self) -> bool {
5030 self.channel_state.is_monitor_update_in_progress()
5031 || self.signer_pending_revoke_and_ack
5032 || self.signer_pending_commitment_update
5033 }
5034
5035 #[rustfmt::skip]
5047 fn is_waiting_on_peer_pending_channel_update(&self) -> bool {
5048 if self.channel_state.is_awaiting_remote_revoke() || self.expecting_peer_commitment_signed {
5054 return true;
5055 }
5056
5057 if self.pending_update_fee.is_some() {
5059 return true;
5060 }
5061
5062 if self.pending_inbound_htlcs.iter()
5063 .any(|htlc| match htlc.state {
5064 InboundHTLCState::Committed { .. } => false,
5065 InboundHTLCState::LocalRemoved(_) => true,
5067 InboundHTLCState::RemoteAnnounced(_)
5069 | InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_)
5070 | InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => true,
5071 })
5072 {
5073 return true;
5074 }
5075
5076 self.pending_outbound_htlcs.iter()
5077 .any(|htlc| match htlc.state {
5078 OutboundHTLCState::Committed => false,
5079 OutboundHTLCState::LocalAnnounced(_) => true,
5081 OutboundHTLCState::RemoteRemoved(_)
5083 | OutboundHTLCState::AwaitingRemoteRevokeToRemove(_)
5084 | OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) => true,
5085 })
5086 }
5087
5088 pub fn channel_id(&self) -> ChannelId {
5091 self.channel_id
5092 }
5093
5094 pub fn temporary_channel_id(&self) -> Option<ChannelId> {
5098 self.temporary_channel_id
5099 }
5100
5101 pub(super) fn minimum_depth(&self, funding: &FundingScope) -> Option<u32> {
5102 funding.minimum_depth_override.or(self.minimum_depth)
5103 }
5104
5105 pub fn get_user_id(&self) -> u128 {
5108 self.user_id
5109 }
5110
5111 pub fn latest_inbound_scid_alias(&self) -> Option<u64> {
5113 self.latest_inbound_scid_alias
5114 }
5115
5116 pub fn outbound_scid_alias(&self) -> u64 {
5118 self.outbound_scid_alias
5119 }
5120
5121 #[cfg(any(test, feature = "_test_utils"))]
5123 pub fn get_mut_signer(&mut self) -> &mut SP::EcdsaSigner {
5124 return &mut self.holder_signer;
5125 }
5126
5127 pub fn set_outbound_scid_alias(&mut self, outbound_scid_alias: u64) {
5131 debug_assert_eq!(self.outbound_scid_alias, 0);
5132 self.outbound_scid_alias = outbound_scid_alias;
5133 }
5134
5135 pub fn do_accept_channel_checks(
5138 &mut self, funding: &mut FundingScope, default_limits: &ChannelHandshakeLimits,
5139 their_features: &InitFeatures, common_fields: &msgs::CommonAcceptChannelFields,
5140 channel_reserve_satoshis: u64,
5141 ) -> Result<(), ChannelError> {
5142 let peer_limits = if let Some(ref limits) = self.inbound_handshake_limits_override {
5143 limits
5144 } else {
5145 default_limits
5146 };
5147
5148 if !funding.is_outbound() {
5150 return Err(ChannelError::close(
5151 "Got an accept_channel message from an inbound peer".to_owned(),
5152 ));
5153 }
5154 if !matches!(self.channel_state, ChannelState::NegotiatingFunding(flags)
5155 if flags == NegotiatingFundingFlags::OUR_INIT_SENT)
5156 {
5157 return Err(ChannelError::close(
5158 "Got an accept_channel message at a strange time".to_owned(),
5159 ));
5160 }
5161
5162 let channel_type = common_fields.channel_type.as_ref().ok_or_else(|| {
5163 ChannelError::close("option_channel_type assumed to be supported".to_owned())
5164 })?;
5165 if channel_type != funding.get_channel_type() {
5166 return Err(ChannelError::close(String::from(
5167 "Channel Type in accept_channel didn't match the one sent in open_channel.",
5168 )));
5169 }
5170
5171 if common_fields.dust_limit_satoshis > 21000000 * 100000000 {
5172 return Err(ChannelError::close(format!(
5173 "Peer never wants payout outputs? dust_limit_satoshis was {}",
5174 common_fields.dust_limit_satoshis
5175 )));
5176 }
5177 if channel_reserve_satoshis > funding.get_value_satoshis() {
5178 return Err(ChannelError::close(format!(
5179 "Bogus channel_reserve_satoshis ({channel_reserve_satoshis}). Must not be greater than ({})",
5180 funding.get_value_satoshis()
5181 )));
5182 }
5183 if common_fields.dust_limit_satoshis > funding.holder_selected_channel_reserve_satoshis
5184 && funding.holder_selected_channel_reserve_satoshis != 0
5185 {
5186 return Err(ChannelError::close(format!(
5187 "Dust limit ({}) is bigger than our channel reserve ({})",
5188 common_fields.dust_limit_satoshis, funding.holder_selected_channel_reserve_satoshis
5189 )));
5190 }
5191 if channel_reserve_satoshis
5192 > funding.get_value_satoshis() - funding.holder_selected_channel_reserve_satoshis
5193 {
5194 return Err(ChannelError::close(format!(
5195 "Bogus channel_reserve_satoshis ({channel_reserve_satoshis}). Must not be greater than channel value minus our reserve ({})",
5196 funding.get_value_satoshis() - funding.holder_selected_channel_reserve_satoshis
5197 )));
5198 }
5199 let full_channel_value_msat =
5200 (funding.get_value_satoshis() - channel_reserve_satoshis) * 1000;
5201 if common_fields.htlc_minimum_msat >= full_channel_value_msat {
5202 return Err(ChannelError::close(format!(
5203 "Minimum htlc value ({}) is full channel value ({full_channel_value_msat})",
5204 common_fields.htlc_minimum_msat
5205 )));
5206 }
5207 let max_delay_acceptable =
5208 u16::min(peer_limits.their_to_self_delay, MAX_LOCAL_BREAKDOWN_TIMEOUT);
5209 if common_fields.to_self_delay > max_delay_acceptable {
5210 return Err(ChannelError::close(format!(
5211 "They wanted our payments to be delayed by a needlessly long period. Upper limit: {max_delay_acceptable}. Actual: {}",
5212 common_fields.to_self_delay
5213 )));
5214 }
5215 if common_fields.max_accepted_htlcs < 1 {
5216 return Err(ChannelError::close(
5217 "0 max_accepted_htlcs makes for a useless channel".to_owned(),
5218 ));
5219 }
5220
5221 let channel_type = funding.get_channel_type();
5222 if !channel_type.supports_anchors_zero_fee_htlc_tx()
5223 && !channel_type.supports_anchor_zero_fee_commitments()
5224 && funding.holder_selected_channel_reserve_satoshis == 0
5225 {
5226 return Err(ChannelError::close(
5227 "0-reserve is not allowed on legacy channels".to_owned(),
5228 ));
5229 }
5230 if common_fields.max_accepted_htlcs > max_htlcs(channel_type) {
5231 return Err(ChannelError::close(format!(
5232 "max_accepted_htlcs was {}. It must not be larger than {}",
5233 common_fields.max_accepted_htlcs,
5234 max_htlcs(channel_type)
5235 )));
5236 }
5237
5238 if common_fields.htlc_minimum_msat > peer_limits.max_htlc_minimum_msat {
5240 return Err(ChannelError::close(format!(
5241 "htlc_minimum_msat ({}) is higher than the user specified limit ({})",
5242 common_fields.htlc_minimum_msat, peer_limits.max_htlc_minimum_msat
5243 )));
5244 }
5245 if common_fields.max_htlc_value_in_flight_msat
5246 < peer_limits.min_max_htlc_value_in_flight_msat
5247 {
5248 return Err(ChannelError::close(format!(
5249 "max_htlc_value_in_flight_msat ({}) is less than the user specified limit ({})",
5250 common_fields.max_htlc_value_in_flight_msat,
5251 peer_limits.min_max_htlc_value_in_flight_msat
5252 )));
5253 }
5254 if channel_reserve_satoshis > peer_limits.max_channel_reserve_satoshis {
5255 return Err(ChannelError::close(format!(
5256 "channel_reserve_satoshis ({channel_reserve_satoshis}) is higher than the user specified limit ({})",
5257 peer_limits.max_channel_reserve_satoshis
5258 )));
5259 }
5260 if common_fields.max_accepted_htlcs < peer_limits.min_max_accepted_htlcs {
5261 return Err(ChannelError::close(format!(
5262 "max_accepted_htlcs ({}) is less than the user specified limit ({})",
5263 common_fields.max_accepted_htlcs, peer_limits.min_max_accepted_htlcs
5264 )));
5265 }
5266 if common_fields.dust_limit_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS {
5267 return Err(ChannelError::close(format!(
5268 "dust_limit_satoshis ({}) is less than the implementation limit ({MIN_CHAN_DUST_LIMIT_SATOSHIS})",
5269 common_fields.dust_limit_satoshis
5270 )));
5271 }
5272
5273 let max_chan_dust_limit_satoshis = if channel_type.supports_anchors_zero_fee_htlc_tx()
5274 || channel_type.supports_anchor_zero_fee_commitments()
5275 {
5276 MAX_CHAN_DUST_LIMIT_SATOSHIS
5277 } else {
5278 MAX_LEGACY_CHAN_DUST_LIMIT_SATOSHIS
5279 };
5280 if common_fields.dust_limit_satoshis > max_chan_dust_limit_satoshis {
5281 return Err(ChannelError::close(format!(
5282 "dust_limit_satoshis ({}) is greater than the implementation limit ({max_chan_dust_limit_satoshis})",
5283 common_fields.dust_limit_satoshis
5284 )));
5285 }
5286 if common_fields.minimum_depth > peer_limits.max_minimum_depth {
5287 return Err(ChannelError::close(format!(
5288 "We consider the minimum depth to be unreasonably large. Expected minimum: ({}). Actual: ({})",
5289 peer_limits.max_minimum_depth, common_fields.minimum_depth
5290 )));
5291 }
5292
5293 let counterparty_shutdown_scriptpubkey =
5294 if their_features.supports_upfront_shutdown_script() {
5295 match &common_fields.shutdown_scriptpubkey {
5296 &Some(ref script) => {
5297 if script.len() == 0 {
5299 None
5300 } else {
5301 if !script::is_bolt2_compliant(&script, their_features) {
5302 return Err(ChannelError::close(format!(
5303 "Peer is signaling upfront_shutdown but has provided an unacceptable scriptpubkey format: {script}"
5304 )));
5305 }
5306 Some(script.clone())
5307 }
5308 },
5309 &None => {
5311 return Err(ChannelError::close(String::from(
5312 "Peer is signaling upfront_shutdown but we don't get any script. Use 0-length script to opt-out"
5313 )));
5314 },
5315 }
5316 } else {
5317 None
5318 };
5319
5320 self.counterparty_dust_limit_satoshis = common_fields.dust_limit_satoshis;
5321 self.counterparty_max_htlc_value_in_flight_msat = cmp::min(
5322 common_fields.max_htlc_value_in_flight_msat,
5323 funding.get_value_satoshis() * 1000,
5324 );
5325 funding.counterparty_selected_channel_reserve_satoshis = Some(channel_reserve_satoshis);
5326 self.counterparty_htlc_minimum_msat = common_fields.htlc_minimum_msat;
5327 self.counterparty_max_accepted_htlcs = common_fields.max_accepted_htlcs;
5328
5329 if peer_limits.trust_own_funding_0conf {
5330 self.minimum_depth = Some(common_fields.minimum_depth);
5331 } else {
5332 self.minimum_depth = Some(cmp::max(1, common_fields.minimum_depth));
5333 }
5334
5335 let counterparty_pubkeys = ChannelPublicKeys {
5336 funding_pubkey: common_fields.funding_pubkey,
5337 revocation_basepoint: RevocationBasepoint::from(common_fields.revocation_basepoint),
5338 payment_point: common_fields.payment_basepoint,
5339 delayed_payment_basepoint: DelayedPaymentBasepoint::from(
5340 common_fields.delayed_payment_basepoint,
5341 ),
5342 htlc_basepoint: HtlcBasepoint::from(common_fields.htlc_basepoint),
5343 };
5344
5345 funding.channel_transaction_parameters.counterparty_parameters =
5346 Some(CounterpartyChannelTransactionParameters {
5347 selected_contest_delay: common_fields.to_self_delay,
5348 pubkeys: counterparty_pubkeys,
5349 });
5350
5351 self.counterparty_next_commitment_point = Some(common_fields.first_per_commitment_point);
5352 self.counterparty_shutdown_scriptpubkey = counterparty_shutdown_scriptpubkey;
5353
5354 self.channel_state = ChannelState::NegotiatingFunding(
5355 NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT,
5356 );
5357 self.inbound_handshake_limits_override = None; Ok(())
5360 }
5361
5362 pub fn get_counterparty_node_id(&self) -> PublicKey {
5364 self.counterparty_node_id
5365 }
5366
5367 pub fn get_holder_htlc_minimum_msat(&self) -> u64 {
5369 self.holder_htlc_minimum_msat
5370 }
5371
5372 pub fn get_holder_htlc_maximum_msat(&self, funding: &FundingScope) -> Option<u64> {
5374 funding.get_htlc_maximum_msat(self.holder_max_htlc_value_in_flight_msat)
5375 }
5376
5377 pub fn get_counterparty_htlc_minimum_msat(&self) -> u64 {
5379 self.counterparty_htlc_minimum_msat
5380 }
5381
5382 pub fn get_counterparty_htlc_maximum_msat(&self, funding: &FundingScope) -> Option<u64> {
5384 funding.get_htlc_maximum_msat(self.counterparty_max_htlc_value_in_flight_msat)
5385 }
5386
5387 pub fn get_fee_proportional_millionths(&self) -> u32 {
5388 self.config.options.forwarding_fee_proportional_millionths
5389 }
5390
5391 pub fn is_manual_broadcast(&self) -> bool {
5392 self.is_manual_broadcast
5393 }
5394
5395 pub fn get_cltv_expiry_delta(&self) -> u16 {
5396 cmp::max(self.config.options.cltv_expiry_delta, MIN_CLTV_EXPIRY_DELTA)
5397 }
5398
5399 fn get_dust_exposure_limiting_feerate<F: FeeEstimator>(
5403 &self, fee_estimator: &LowerBoundedFeeEstimator<F>, channel_type: &ChannelTypeFeatures,
5404 ) -> Option<u32> {
5405 if channel_type.supports_anchor_zero_fee_commitments() {
5406 None
5407 } else {
5408 Some(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MaximumFeeEstimate))
5409 }
5410 }
5411
5412 pub fn get_max_dust_htlc_exposure_msat(&self, limiting_feerate_sat_per_kw: Option<u32>) -> u64 {
5417 match self.config.options.max_dust_htlc_exposure {
5418 MaxDustHTLCExposure::FeeRateMultiplier(multiplier) => {
5419 (limiting_feerate_sat_per_kw.unwrap_or(250) as u64).saturating_mul(multiplier)
5420 },
5421 MaxDustHTLCExposure::FixedLimitMsat(limit) => limit,
5422 }
5423 }
5424
5425 pub fn prev_config(&self) -> Option<ChannelConfig> {
5427 self.prev_config.map(|prev_config| prev_config.0)
5428 }
5429
5430 pub(crate) fn should_emit_channel_pending_event(&mut self) -> bool {
5432 self.is_funding_broadcastable() && !self.channel_pending_event_emitted
5433 }
5434
5435 pub(crate) fn channel_pending_event_emitted(&self) -> bool {
5437 self.channel_pending_event_emitted
5438 }
5439
5440 pub(crate) fn funding_tx_broadcast_safe_event_emitted(&self) -> bool {
5442 self.funding_tx_broadcast_safe_event_emitted
5443 }
5444
5445 pub(crate) fn set_channel_pending_event_emitted(&mut self) {
5447 self.channel_pending_event_emitted = true;
5448 }
5449
5450 pub(crate) fn should_emit_initial_channel_ready_event(&mut self) -> bool {
5452 self.is_usable() && !self.initial_channel_ready_event_emitted
5453 }
5454
5455 pub(crate) fn set_initial_channel_ready_event_emitted(&mut self) {
5457 self.initial_channel_ready_event_emitted = true;
5458 }
5459
5460 pub(crate) fn set_funding_tx_broadcast_safe_event_emitted(&mut self) {
5462 self.funding_tx_broadcast_safe_event_emitted = true;
5463 }
5464
5465 pub fn maybe_expire_prev_config(&mut self) {
5469 if self.prev_config.is_none() {
5470 return;
5471 }
5472 let prev_config = self.prev_config.as_mut().unwrap();
5473 prev_config.1 += 1;
5474 if prev_config.1 == EXPIRE_PREV_CONFIG_TICKS {
5475 self.prev_config = None;
5476 }
5477 }
5478
5479 pub fn config(&self) -> ChannelConfig {
5481 self.config.options
5482 }
5483
5484 #[rustfmt::skip]
5487 pub fn update_config(&mut self, config: &ChannelConfig) -> bool {
5488 let did_channel_update =
5489 self.config.options.forwarding_fee_proportional_millionths != config.forwarding_fee_proportional_millionths ||
5490 self.config.options.forwarding_fee_base_msat != config.forwarding_fee_base_msat ||
5491 self.config.options.cltv_expiry_delta != config.cltv_expiry_delta;
5492 if did_channel_update {
5493 self.prev_config = Some((self.config.options, 0));
5494 self.update_time_counter += 1;
5497 }
5498 self.config.options = *config;
5499 did_channel_update
5500 }
5501
5502 pub fn set_manual_broadcast(&mut self) {
5510 self.is_manual_broadcast = true;
5511 }
5512
5513 fn can_resume_on_reconnect(&self) -> bool {
5514 match self.channel_state {
5515 ChannelState::NegotiatingFunding(_) => false,
5516 ChannelState::FundingNegotiated(_) => self.interactive_tx_signing_session.is_some(),
5517 _ => true,
5518 }
5519 }
5520
5521 pub fn can_resume_on_restart(&self) -> bool {
5527 self.can_resume_on_reconnect()
5528 && match self.channel_state {
5529 ChannelState::AwaitingChannelReady(flags) => !flags.is_waiting_for_batch(),
5530 _ => true,
5531 }
5532 }
5533
5534 fn is_funding_broadcastable(&self) -> bool {
5537 match self.channel_state {
5538 ChannelState::NegotiatingFunding(_) => false,
5539 ChannelState::FundingNegotiated(_) => self
5540 .interactive_tx_signing_session
5541 .as_ref()
5542 .map(|signing_session| signing_session.has_holder_witnesses())
5543 .unwrap_or(false),
5544 ChannelState::AwaitingChannelReady(flags) => !flags.is_waiting_for_batch(),
5545 _ => true,
5546 }
5547 }
5548
5549 #[rustfmt::skip]
5550 fn unset_funding_info(&mut self, funding: &mut FundingScope) {
5551 funding.channel_transaction_parameters.funding_outpoint = None;
5552 self.channel_id = self.temporary_channel_id.expect(
5553 "temporary_channel_id should be set since unset_funding_info is only called on funded \
5554 channels that were unfunded immediately beforehand"
5555 );
5556 }
5557
5558 fn get_next_commitment_projection(
5562 &self, funding: &FundingScope, local: bool, htlc_candidate: Option<HTLCAmountDirection>,
5563 commitment_view: NextCommitmentView,
5564 ) -> NextCommitmentProjection {
5565 let mut next_commitment_htlcs = Vec::with_capacity(
5566 1 + self.pending_inbound_htlcs.len()
5567 + self.pending_outbound_htlcs.len()
5568 + self.holding_cell_htlc_updates.len(),
5569 );
5570 next_commitment_htlcs.extend(htlc_candidate);
5571
5572 let mut inbound_claimed_htlc_msat = 0u64;
5573 let mut outbound_claimed_htlc_msat = 0u64;
5574
5575 for htlc in self.pending_inbound_htlcs.iter() {
5576 let included = match (&htlc.state, local) {
5577 (InboundHTLCState::RemoteAnnounced(..), _) => true,
5578 (InboundHTLCState::AwaitingRemoteRevokeToAnnounce(..), _) => true,
5579 (InboundHTLCState::AwaitingAnnouncedRemoteRevoke(..), _) => true,
5580 (InboundHTLCState::Committed { .. }, _) => true,
5581 (InboundHTLCState::LocalRemoved(..), true) => true,
5582 (InboundHTLCState::LocalRemoved(..), false) => false,
5583 };
5584 if included {
5585 next_commitment_htlcs
5586 .push(HTLCAmountDirection { outbound: false, amount_msat: htlc.amount_msat });
5587 } else if htlc.state.preimage().is_some() {
5588 inbound_claimed_htlc_msat += htlc.amount_msat;
5589 }
5590 }
5591
5592 for htlc in self.pending_outbound_htlcs.iter() {
5593 let included = match (&htlc.state, local) {
5594 (OutboundHTLCState::LocalAnnounced(..), _) => {
5595 commitment_view == NextCommitmentView::ValidatingOwnUpdate
5596 },
5597 (OutboundHTLCState::Committed, _) => true,
5598 (OutboundHTLCState::RemoteRemoved(..), true) => false,
5599 (OutboundHTLCState::RemoteRemoved(..), false) => {
5600 commitment_view == NextCommitmentView::ValidatingOwnUpdate
5601 },
5602 (OutboundHTLCState::AwaitingRemoteRevokeToRemove(..), _) => false,
5603 (OutboundHTLCState::AwaitingRemovedRemoteRevoke(..), _) => false,
5604 };
5605 if included {
5606 next_commitment_htlcs
5607 .push(HTLCAmountDirection { outbound: true, amount_msat: htlc.amount_msat });
5608 } else if htlc.state.preimage().is_some() {
5609 outbound_claimed_htlc_msat += htlc.amount_msat;
5610 }
5611 }
5612
5613 if let NextCommitmentView::ValidatingOwnUpdate = commitment_view {
5617 next_commitment_htlcs.extend(self.holding_cell_htlc_updates.iter().filter_map(
5618 |htlc| {
5619 if let &HTLCUpdateAwaitingACK::AddHTLC { amount_msat, .. } = htlc {
5620 Some(HTLCAmountDirection { outbound: true, amount_msat })
5621 } else {
5622 None
5623 }
5624 },
5625 ));
5626 }
5627
5628 let next_value_to_self_msat = funding
5629 .value_to_self_msat
5630 .saturating_sub(outbound_claimed_htlc_msat)
5631 .saturating_add(inbound_claimed_htlc_msat);
5632
5633 NextCommitmentProjection { next_value_to_self_msat, next_commitment_htlcs }
5634 }
5635
5636 fn get_channel_constraints(&self, funding: &FundingScope) -> ChannelConstraints {
5637 ChannelConstraints {
5638 holder_dust_limit_satoshis: self.holder_dust_limit_satoshis,
5639 counterparty_selected_channel_reserve_satoshis: funding
5640 .counterparty_selected_channel_reserve_satoshis
5641 .unwrap_or(0),
5642 counterparty_dust_limit_satoshis: self.counterparty_dust_limit_satoshis,
5643 holder_selected_channel_reserve_satoshis: funding
5644 .holder_selected_channel_reserve_satoshis,
5645 counterparty_htlc_minimum_msat: self.counterparty_htlc_minimum_msat,
5646 counterparty_max_accepted_htlcs: self.counterparty_max_accepted_htlcs as u64,
5647 counterparty_max_htlc_value_in_flight_msat: self
5648 .counterparty_max_htlc_value_in_flight_msat,
5649 }
5650 }
5651
5652 fn get_next_local_commitment_stats(
5653 &self, funding: &FundingScope, htlc_candidate: Option<HTLCAmountDirection>,
5654 commitment_view: NextCommitmentView, addl_nondust_htlc_count: usize, feerate_per_kw: u32,
5655 assume_fee_spike: bool, dust_exposure_limiting_feerate: Option<u32>,
5656 ) -> Result<(ChannelStats, Vec<HTLCAmountDirection>), ()> {
5657 let NextCommitmentProjection { next_value_to_self_msat, next_commitment_htlcs } =
5658 self.get_next_commitment_projection(funding, true, htlc_candidate, commitment_view);
5659
5660 let max_dust_htlc_exposure_msat =
5661 self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate);
5662
5663 let channel_constraints = self.get_channel_constraints(funding);
5664
5665 let local_stats = SpecTxBuilder {}.get_channel_stats(
5666 true,
5667 funding.is_outbound(),
5668 funding.get_value_satoshis(),
5669 next_value_to_self_msat,
5670 &next_commitment_htlcs,
5671 addl_nondust_htlc_count,
5672 feerate_per_kw,
5673 assume_fee_spike,
5674 dust_exposure_limiting_feerate,
5675 max_dust_htlc_exposure_msat,
5676 channel_constraints,
5677 funding.get_channel_type(),
5678 )?;
5679
5680 #[cfg(any(test, fuzzing))]
5681 {
5682 if addl_nondust_htlc_count == 0 {
5683 *funding.next_local_fee.lock().unwrap() = PredictedNextFee {
5684 predicted_feerate: feerate_per_kw,
5685 predicted_nondust_htlc_count: local_stats.commitment_stats.nondust_htlc_count,
5686 predicted_fee_sat: local_stats.commitment_stats.commit_tx_fee_sat,
5687 };
5688 } else {
5689 let predicted_stats = SpecTxBuilder {}
5690 .get_channel_stats(
5691 true,
5692 funding.is_outbound(),
5693 funding.get_value_satoshis(),
5694 next_value_to_self_msat,
5695 &next_commitment_htlcs,
5696 0,
5697 feerate_per_kw,
5698 false,
5699 dust_exposure_limiting_feerate,
5700 max_dust_htlc_exposure_msat,
5701 channel_constraints,
5702 funding.get_channel_type(),
5703 )
5704 .expect("Balance exhausted on local commitment")
5705 .commitment_stats;
5706 *funding.next_local_fee.lock().unwrap() = PredictedNextFee {
5707 predicted_feerate: feerate_per_kw,
5708 predicted_nondust_htlc_count: predicted_stats.nondust_htlc_count,
5709 predicted_fee_sat: predicted_stats.commit_tx_fee_sat,
5710 };
5711 }
5712 }
5713
5714 Ok((local_stats, next_commitment_htlcs))
5715 }
5716
5717 fn get_next_remote_commitment_stats(
5718 &self, funding: &FundingScope, htlc_candidate: Option<HTLCAmountDirection>,
5719 commitment_view: NextCommitmentView, addl_nondust_htlc_count: usize, feerate_per_kw: u32,
5720 assume_fee_spike: bool, dust_exposure_limiting_feerate: Option<u32>,
5721 ) -> Result<(ChannelStats, Vec<HTLCAmountDirection>), ()> {
5722 let NextCommitmentProjection { next_value_to_self_msat, next_commitment_htlcs } =
5723 self.get_next_commitment_projection(funding, false, htlc_candidate, commitment_view);
5724
5725 let max_dust_htlc_exposure_msat =
5726 self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate);
5727
5728 let channel_constraints = self.get_channel_constraints(funding);
5729
5730 let remote_stats = SpecTxBuilder {}.get_channel_stats(
5731 false,
5732 funding.is_outbound(),
5733 funding.get_value_satoshis(),
5734 next_value_to_self_msat,
5735 &next_commitment_htlcs,
5736 addl_nondust_htlc_count,
5737 feerate_per_kw,
5738 assume_fee_spike,
5739 dust_exposure_limiting_feerate,
5740 max_dust_htlc_exposure_msat,
5741 channel_constraints,
5742 funding.get_channel_type(),
5743 )?;
5744
5745 #[cfg(any(test, fuzzing))]
5746 {
5747 if addl_nondust_htlc_count == 0 {
5748 *funding.next_remote_fee.lock().unwrap() = PredictedNextFee {
5749 predicted_feerate: feerate_per_kw,
5750 predicted_nondust_htlc_count: remote_stats.commitment_stats.nondust_htlc_count,
5751 predicted_fee_sat: remote_stats.commitment_stats.commit_tx_fee_sat,
5752 };
5753 } else {
5754 let predicted_stats = SpecTxBuilder {}
5755 .get_channel_stats(
5756 false,
5757 funding.is_outbound(),
5758 funding.get_value_satoshis(),
5759 next_value_to_self_msat,
5760 &next_commitment_htlcs,
5761 0,
5762 feerate_per_kw,
5763 false,
5764 dust_exposure_limiting_feerate,
5765 max_dust_htlc_exposure_msat,
5766 channel_constraints,
5767 funding.get_channel_type(),
5768 )
5769 .expect("Balance exhausted on remote commitment")
5770 .commitment_stats;
5771 *funding.next_remote_fee.lock().unwrap() = PredictedNextFee {
5772 predicted_feerate: feerate_per_kw,
5773 predicted_nondust_htlc_count: predicted_stats.nondust_htlc_count,
5774 predicted_fee_sat: predicted_stats.commit_tx_fee_sat,
5775 };
5776 }
5777 }
5778
5779 Ok((remote_stats, next_commitment_htlcs))
5780 }
5781
5782 fn validate_update_add_htlc<F: FeeEstimator>(
5783 &self, funding: &FundingScope, msg: &msgs::UpdateAddHTLC,
5784 fee_estimator: &LowerBoundedFeeEstimator<F>,
5785 ) -> Result<(), ChannelError> {
5786 if msg.amount_msat > funding.get_value_satoshis() * 1000 {
5787 return Err(ChannelError::close(
5788 "Remote side tried to send more than the total value of the channel".to_owned(),
5789 ));
5790 }
5791
5792 let dust_exposure_limiting_feerate =
5793 self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
5794 let fee_spike_buffer_htlc = 0;
5798 let (remote_stats, remote_htlcs) = self
5799 .get_next_remote_commitment_stats(
5800 funding,
5801 Some(HTLCAmountDirection { outbound: false, amount_msat: msg.amount_msat }),
5802 NextCommitmentView::ValidatingPeerUpdate,
5803 fee_spike_buffer_htlc,
5804 self.feerate_per_kw,
5805 false,
5806 dust_exposure_limiting_feerate,
5807 )
5808 .map_err(|()| {
5809 ChannelError::close(String::from("Remote HTLC add would overdraw remaining funds"))
5810 })?;
5811
5812 let inbound_htlcs_count = remote_htlcs.iter().filter(|htlc| !htlc.outbound).count();
5813 let inbound_htlcs_value_msat: u64 = remote_htlcs
5814 .iter()
5815 .filter_map(|htlc| (!htlc.outbound).then_some(htlc.amount_msat))
5816 .sum();
5817
5818 if inbound_htlcs_count > self.holder_max_accepted_htlcs as usize {
5819 return Err(ChannelError::close(format!(
5820 "Remote tried to push more than our max accepted HTLCs ({})",
5821 self.holder_max_accepted_htlcs,
5822 )));
5823 }
5824 if inbound_htlcs_value_msat > self.holder_max_htlc_value_in_flight_msat {
5825 return Err(ChannelError::close(format!(
5826 "Remote HTLC add would put them over our max HTLC value ({})",
5827 self.holder_max_htlc_value_in_flight_msat,
5828 )));
5829 }
5830
5831 if remote_stats.commitment_stats.counterparty_balance_msat
5847 < funding.holder_selected_channel_reserve_satoshis * 1000
5848 {
5849 return Err(ChannelError::close(
5850 "Remote HTLC add would put them under remote reserve value".to_owned(),
5851 ));
5852 }
5853
5854 let (_local_stats, _local_htlcs) = self
5858 .get_next_local_commitment_stats(
5859 funding,
5860 Some(HTLCAmountDirection { outbound: false, amount_msat: msg.amount_msat }),
5861 NextCommitmentView::ValidatingPeerUpdate,
5862 fee_spike_buffer_htlc,
5863 self.feerate_per_kw,
5864 false,
5865 dust_exposure_limiting_feerate,
5866 )
5867 .map_err(|()| {
5868 ChannelError::close(String::from("Balance exhausted on local commitment"))
5869 })?;
5870
5871 Ok(())
5872 }
5873
5874 fn validate_update_fee<F: FeeEstimator>(
5875 &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator<F>,
5876 new_feerate_per_kw: u32,
5877 ) -> Result<(), ChannelError> {
5878 let dust_exposure_limiting_feerate =
5880 self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
5881 let (local_stats, _local_htlcs) = self
5884 .get_next_local_commitment_stats(
5885 funding,
5886 None,
5887 NextCommitmentView::ValidatingPeerUpdate,
5888 0,
5889 new_feerate_per_kw,
5890 false,
5891 dust_exposure_limiting_feerate,
5892 )
5893 .map_err(|()| {
5894 ChannelError::close(String::from("Funding remote cannot afford proposed new fee"))
5895 })?;
5896
5897 local_stats
5898 .commitment_stats
5899 .counterparty_balance_msat
5900 .checked_sub(funding.holder_selected_channel_reserve_satoshis * 1000)
5901 .ok_or(ChannelError::close(
5902 "Funding remote cannot afford proposed new fee".to_owned(),
5903 ))?;
5904
5905 let (remote_stats, _remote_htlcs) = self
5906 .get_next_remote_commitment_stats(
5907 funding,
5908 None,
5909 NextCommitmentView::ValidatingPeerUpdate,
5910 0,
5911 new_feerate_per_kw,
5912 false,
5913 dust_exposure_limiting_feerate,
5914 )
5915 .map_err(|()| {
5916 ChannelError::close(String::from("Balance exhausted on remote commitment"))
5917 })?;
5918
5919 let max_dust_htlc_exposure_msat =
5920 self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate);
5921 if local_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat {
5922 return Err(ChannelError::close(
5923 format!(
5924 "Peer sent update_fee with a feerate ({}) which may over-expose us to dust-in-flight on our own transactions (totaling {} msat)",
5925 new_feerate_per_kw,
5926 local_stats.commitment_stats.dust_exposure_msat,
5927 )
5928 ));
5929 }
5930 if remote_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat {
5931 return Err(ChannelError::close(
5932 format!(
5933 "Peer sent update_fee with a feerate ({}) which may over-expose us to dust-in-flight on our counterparty's transactions (totaling {} msat)",
5934 new_feerate_per_kw,
5935 remote_stats.commitment_stats.dust_exposure_msat,
5936 )
5937 ));
5938 }
5939
5940 Ok(())
5941 }
5942
5943 fn validate_commitment_signed<F: FeeEstimator, L: Logger>(
5944 &self, funding: &FundingScope, transaction_number: u64, commitment_point: PublicKey,
5945 msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
5946 ) -> Result<
5947 (HolderCommitmentTransaction, Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>),
5948 ChannelError,
5949 > {
5950 let funding_script = funding.get_funding_redeemscript();
5951
5952 let commitment_data = self.build_commitment_transaction(
5953 funding,
5954 transaction_number,
5955 &commitment_point,
5956 true,
5957 false,
5958 logger,
5959 );
5960 let commitment_txid = {
5961 let trusted_tx = commitment_data.tx.trust();
5962 let bitcoin_tx = trusted_tx.built_transaction();
5963 if bitcoin_tx.transaction.output.is_empty() {
5964 return Err(ChannelError::close(
5965 "Commitment tx from peer has 0 outputs".to_owned(),
5966 ));
5967 }
5968
5969 let sighash = bitcoin_tx.get_sighash_all(&funding_script, funding.get_value_satoshis());
5970
5971 log_trace!(logger, "Checking commitment tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}",
5972 log_bytes!(msg.signature.serialize_compact()[..]),
5973 log_bytes!(funding.counterparty_funding_pubkey().serialize()),
5974 encode::serialize_hex(&bitcoin_tx.transaction),
5975 log_bytes!(sighash[..]), encode::serialize_hex(&funding_script),
5976 &self.channel_id(),
5977 );
5978 if let Err(_) = self.secp_ctx.verify_ecdsa(
5979 &sighash,
5980 &msg.signature,
5981 &funding.counterparty_funding_pubkey(),
5982 ) {
5983 return Err(ChannelError::close(
5984 "Invalid commitment tx signature from peer".to_owned(),
5985 ));
5986 }
5987 bitcoin_tx.txid
5988 };
5989
5990 if let Some((new_feerate_per_kw, FeeUpdateState::RemoteAnnounced)) = self.pending_update_fee
5993 {
5994 debug_assert!(!funding.is_outbound());
5995 self.validate_update_fee(funding, fee_estimator, new_feerate_per_kw)?;
5996 }
5997
5998 if msg.htlc_signatures.len() != commitment_data.tx.nondust_htlcs().len() {
5999 return Err(ChannelError::close(format!(
6000 "Got wrong number of HTLC signatures ({}) from remote. It must be {}",
6001 msg.htlc_signatures.len(),
6002 commitment_data.tx.nondust_htlcs().len()
6003 )));
6004 }
6005
6006 let holder_keys = commitment_data.tx.trust().keys();
6007 for (htlc, counterparty_sig) in
6008 commitment_data.tx.nondust_htlcs().iter().zip(msg.htlc_signatures.iter())
6009 {
6010 assert!(htlc.transaction_output_index.is_some());
6011 let htlc_tx = chan_utils::build_htlc_transaction(
6012 &commitment_txid,
6013 commitment_data.tx.negotiated_feerate_per_kw(),
6014 funding.get_counterparty_selected_contest_delay().unwrap(),
6015 &htlc,
6016 funding.get_channel_type(),
6017 &holder_keys.broadcaster_delayed_payment_key,
6018 &holder_keys.revocation_key,
6019 );
6020
6021 let htlc_redeemscript =
6022 chan_utils::get_htlc_redeemscript(&htlc, funding.get_channel_type(), &holder_keys);
6023 let channel_type = funding.get_channel_type();
6024 let htlc_sighashtype = if channel_type.supports_anchors_zero_fee_htlc_tx()
6025 || channel_type.supports_anchor_zero_fee_commitments()
6026 {
6027 EcdsaSighashType::SinglePlusAnyoneCanPay
6028 } else {
6029 EcdsaSighashType::All
6030 };
6031 let htlc_sighash = hash_to_message!(
6032 &sighash::SighashCache::new(&htlc_tx)
6033 .p2wsh_signature_hash(
6034 0,
6035 &htlc_redeemscript,
6036 htlc.to_bitcoin_amount(),
6037 htlc_sighashtype
6038 )
6039 .unwrap()[..]
6040 );
6041 log_trace!(logger, "Checking HTLC tx signature {} by key {} against tx {} (sighash {}) with redeemscript {} in channel {}.",
6042 log_bytes!(counterparty_sig.serialize_compact()[..]),
6043 log_bytes!(holder_keys.countersignatory_htlc_key.to_public_key().serialize()),
6044 encode::serialize_hex(&htlc_tx),
6045 log_bytes!(htlc_sighash[..]),
6046 encode::serialize_hex(&htlc_redeemscript),
6047 &self.channel_id(),
6048 );
6049 if let Err(_) = self.secp_ctx.verify_ecdsa(
6050 &htlc_sighash,
6051 &counterparty_sig,
6052 &holder_keys.countersignatory_htlc_key.to_public_key(),
6053 ) {
6054 return Err(ChannelError::close("Invalid HTLC tx signature from peer".to_owned()));
6055 }
6056 }
6057
6058 let holder_commitment_tx = HolderCommitmentTransaction::new(
6059 commitment_data.tx,
6060 msg.signature,
6061 msg.htlc_signatures.clone(),
6062 &funding.get_holder_pubkeys().funding_pubkey,
6063 funding.counterparty_funding_pubkey(),
6064 );
6065
6066 self.holder_signer
6067 .validate_holder_commitment(
6068 &holder_commitment_tx,
6069 commitment_data.outbound_htlc_preimages,
6070 )
6071 .map_err(|_| ChannelError::close("Failed to validate our commitment".to_owned()))?;
6072
6073 Ok((holder_commitment_tx, commitment_data.htlcs_included))
6074 }
6075
6076 fn can_send_update_fee<F: FeeEstimator, L: Logger>(
6077 &self, funding: &FundingScope, feerate_per_kw: u32,
6078 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
6079 ) -> bool {
6080 let dust_exposure_limiting_feerate =
6082 self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
6083 let (remote_stats, _remote_htlcs) = if let Ok(stats) = self
6086 .get_next_remote_commitment_stats(
6087 funding,
6088 None,
6089 NextCommitmentView::ValidatingOwnUpdate,
6090 CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize,
6091 feerate_per_kw,
6092 false,
6093 dust_exposure_limiting_feerate,
6094 ) {
6095 stats
6096 } else {
6097 log_debug!(
6098 logger,
6099 "Cannot afford to send new feerate due to balance exhausted on remote commitment",
6100 );
6101 return false;
6102 };
6103 if remote_stats.commitment_stats.holder_balance_msat
6106 < funding.counterparty_selected_channel_reserve_satoshis.unwrap() * 1000
6107 {
6108 log_debug!(logger, "Cannot afford to send new feerate at {}", feerate_per_kw);
6110 return false;
6111 }
6112
6113 let max_dust_htlc_exposure_msat =
6116 self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate);
6117 if remote_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat {
6118 log_debug!(
6119 logger,
6120 "Cannot afford to send new feerate at {} without infringing max dust htlc exposure",
6121 feerate_per_kw,
6122 );
6123 return false;
6124 }
6125
6126 let (local_stats, _local_htlcs) = if let Ok(stats) = self.get_next_local_commitment_stats(
6127 funding,
6128 None,
6129 NextCommitmentView::ValidatingOwnUpdate,
6130 CONCURRENT_INBOUND_HTLC_FEE_BUFFER as usize,
6131 feerate_per_kw,
6132 false,
6133 dust_exposure_limiting_feerate,
6134 ) {
6135 stats
6136 } else {
6137 log_debug!(
6138 logger,
6139 "Cannot afford to send new feerate due to balance exhausted on local commitment",
6140 );
6141 return false;
6142 };
6143 if local_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat {
6144 log_debug!(
6145 logger,
6146 "Cannot afford to send new feerate at {} without infringing max dust htlc exposure",
6147 feerate_per_kw,
6148 );
6149 return false;
6150 }
6151
6152 return true;
6153 }
6154
6155 fn can_accept_incoming_htlc<L: Logger>(
6156 &self, funding: &FundingScope, dust_exposure_limiting_feerate: Option<u32>, logger: &L,
6157 ) -> Result<(), LocalHTLCFailureReason> {
6158 let fee_spike_buffer_htlc =
6162 if funding.get_channel_type().supports_anchor_zero_fee_commitments() { 0 } else { 1 };
6163 let feerate =
6169 cmp::max(self.feerate_per_kw, self.pending_update_fee.map(|(fee, _)| fee).unwrap_or(0));
6170 let (local_stats, _local_htlcs) = self
6173 .get_next_local_commitment_stats(
6174 funding,
6175 None,
6176 NextCommitmentView::ValidatingOwnUpdate,
6177 fee_spike_buffer_htlc,
6178 feerate,
6179 false,
6180 dust_exposure_limiting_feerate,
6181 )
6182 .map_err(|()| {
6183 log_trace!(
6184 logger,
6185 "Attempting to fail HTLC due to balance exhausted on local commitment"
6186 );
6187 LocalHTLCFailureReason::ChannelBalanceOverdrawn
6188 })?;
6189 let (remote_stats, _remote_htlcs) = self
6190 .get_next_remote_commitment_stats(
6191 funding,
6192 None,
6193 NextCommitmentView::ValidatingOwnUpdate,
6194 fee_spike_buffer_htlc,
6195 feerate,
6196 false,
6197 dust_exposure_limiting_feerate,
6198 )
6199 .map_err(|()| {
6200 log_trace!(
6201 logger,
6202 "Attempting to fail HTLC due to balance exhausted on remote commitment"
6203 );
6204 LocalHTLCFailureReason::ChannelBalanceOverdrawn
6205 })?;
6206
6207 let max_dust_htlc_exposure_msat =
6208 self.get_max_dust_htlc_exposure_msat(dust_exposure_limiting_feerate);
6209 if remote_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat {
6210 log_info!(
6213 logger,
6214 "Cannot accept value that would put our total dust exposure at {} over the limit {} on counterparty commitment tx",
6215 remote_stats.commitment_stats.dust_exposure_msat,
6216 max_dust_htlc_exposure_msat,
6217 );
6218 return Err(LocalHTLCFailureReason::DustLimitCounterparty);
6219 }
6220 if local_stats.commitment_stats.dust_exposure_msat > max_dust_htlc_exposure_msat {
6221 log_info!(
6222 logger,
6223 "Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx",
6224 local_stats.commitment_stats.dust_exposure_msat,
6225 max_dust_htlc_exposure_msat,
6226 );
6227 return Err(LocalHTLCFailureReason::DustLimitHolder);
6228 }
6229
6230 if !funding.is_outbound() {
6231 let (remote_stats, _remote_htlcs) = self
6234 .get_next_remote_commitment_stats(
6235 funding,
6236 None,
6237 NextCommitmentView::ValidatingOwnUpdate,
6238 fee_spike_buffer_htlc,
6239 feerate,
6240 true,
6241 dust_exposure_limiting_feerate,
6242 )
6243 .map_err(|()| {
6244 log_trace!(
6245 logger,
6246 "Attempting to fail HTLC due to balance exhausted on remote commitment"
6247 );
6248 LocalHTLCFailureReason::FeeSpikeBuffer
6249 })?;
6250 if remote_stats.commitment_stats.counterparty_balance_msat
6251 < funding.holder_selected_channel_reserve_satoshis * 1000
6252 {
6253 log_info!(
6254 logger,
6255 "Attempting to fail HTLC due to fee spike buffer violation. Rebalancing is required.",
6256
6257 );
6258 return Err(LocalHTLCFailureReason::FeeSpikeBuffer);
6259 }
6260 }
6261
6262 Ok(())
6263 }
6264
6265 #[inline]
6266 #[rustfmt::skip]
6267 fn get_commitment_feerate(&self, funding: &FundingScope, generated_by_local: bool) -> u32 {
6268 let mut feerate_per_kw = self.feerate_per_kw;
6269 if let Some((feerate, update_state)) = self.pending_update_fee {
6270 if match update_state {
6271 FeeUpdateState::RemoteAnnounced => { debug_assert!(!funding.is_outbound()); !generated_by_local },
6274 FeeUpdateState::AwaitingRemoteRevokeToAnnounce => { debug_assert!(!funding.is_outbound()); !generated_by_local },
6275 FeeUpdateState::Outbound => { assert!(funding.is_outbound()); generated_by_local },
6276 } {
6277 feerate_per_kw = feerate;
6278 }
6279 }
6280
6281 feerate_per_kw
6282 }
6283
6284 #[inline]
6298 #[rustfmt::skip]
6299 fn build_commitment_transaction<L: Logger>(&self, funding: &FundingScope, commitment_number: u64, per_commitment_point: &PublicKey, local: bool, generated_by_local: bool, logger: &L) -> CommitmentData<'_> {
6300 let broadcaster_dust_limit_sat = if local { self.holder_dust_limit_satoshis } else { self.counterparty_dust_limit_satoshis };
6301 let feerate_per_kw = self.get_commitment_feerate(funding, generated_by_local);
6302
6303 let num_htlcs = self.pending_inbound_htlcs.len() + self.pending_outbound_htlcs.len();
6304 let mut htlcs_included: Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)> = Vec::with_capacity(num_htlcs);
6305 let mut value_to_self_claimed_msat = 0;
6306 let mut value_to_remote_claimed_msat = 0;
6307
6308 log_trace!(logger, "Building commitment transaction number {} (really {} xor {}) for channel {} for {}, generated by {} with fee {}...",
6309 commitment_number, (INITIAL_COMMITMENT_NUMBER - commitment_number),
6310 get_commitment_transaction_number_obscure_factor(&funding.get_holder_pubkeys().payment_point, &funding.get_counterparty_pubkeys().payment_point, funding.is_outbound()),
6311 self.channel_id,
6312 if local { "us" } else { "remote" }, if generated_by_local { "us" } else { "remote" }, feerate_per_kw);
6313
6314 macro_rules! get_htlc_in_commitment {
6315 ($htlc: expr, $offered: expr) => {
6316 HTLCOutputInCommitment {
6317 offered: $offered,
6318 amount_msat: $htlc.amount_msat,
6319 cltv_expiry: $htlc.cltv_expiry,
6320 payment_hash: $htlc.payment_hash,
6321 transaction_output_index: None,
6322 }
6323 }
6324 }
6325
6326 macro_rules! add_htlc_output {
6327 ($htlc: expr, $outbound: expr, $source: expr) => {
6328 let htlc = get_htlc_in_commitment!($htlc, $outbound == local);
6329 htlcs_included.push((htlc, $source));
6330 }
6331 }
6332
6333 let mut inbound_htlc_preimages: Vec<PaymentPreimage> = Vec::new();
6334 let mut outbound_htlc_preimages: Vec<PaymentPreimage> = Vec::new();
6335
6336 for htlc in self.pending_inbound_htlcs.iter() {
6337 if htlc.state.included_in_commitment(generated_by_local) {
6338 log_trace!(logger, " ...including inbound {} HTLC {} (hash {}) with value {}", htlc.state, htlc.htlc_id, htlc.payment_hash, htlc.amount_msat);
6339 add_htlc_output!(htlc, false, None);
6340 } else {
6341 log_trace!(logger, " ...not including inbound HTLC {} (hash {}) with value {} due to state ({})", htlc.htlc_id, htlc.payment_hash, htlc.amount_msat, htlc.state);
6342 if let Some(preimage) = htlc.state.preimage() {
6343 inbound_htlc_preimages.push(preimage);
6344 value_to_self_claimed_msat += htlc.amount_msat;
6345 }
6346 }
6347 };
6348
6349 for htlc in self.pending_outbound_htlcs.iter() {
6350 if let Some(preimage) = htlc.state.preimage() {
6351 outbound_htlc_preimages.push(preimage);
6352 }
6353 if htlc.state.included_in_commitment(generated_by_local) {
6354 log_trace!(logger, " ...including outbound {} HTLC {} (hash {}) with value {}", htlc.state, htlc.htlc_id, htlc.payment_hash, htlc.amount_msat);
6355 add_htlc_output!(htlc, true, Some(&htlc.source));
6356 } else {
6357 log_trace!(logger, " ...not including outbound HTLC {} (hash {}) with value {} due to state ({})", htlc.htlc_id, htlc.payment_hash, htlc.amount_msat, htlc.state);
6358 if htlc.state.preimage().is_some() {
6359 value_to_remote_claimed_msat += htlc.amount_msat;
6360 }
6361 }
6362 };
6363
6364 let value_to_self_msat = (funding.value_to_self_msat + value_to_self_claimed_msat).checked_sub(value_to_remote_claimed_msat).unwrap();
6369
6370 let (tx, _stats) = SpecTxBuilder {}.build_commitment_transaction(
6371 local,
6372 commitment_number,
6373 per_commitment_point,
6374 &funding.channel_transaction_parameters,
6375 &self.secp_ctx,
6376 value_to_self_msat,
6377 htlcs_included.iter().map(|(htlc, _source)| htlc).cloned().collect(),
6378 feerate_per_kw,
6379 broadcaster_dust_limit_sat,
6380 logger,
6381 );
6382 #[cfg(any(test, fuzzing))]
6383 {
6384 let PredictedNextFee { predicted_feerate, predicted_nondust_htlc_count, predicted_fee_sat } = if local { *funding.next_local_fee.lock().unwrap() } else { *funding.next_remote_fee.lock().unwrap() };
6385 if predicted_feerate == tx.negotiated_feerate_per_kw() && predicted_nondust_htlc_count == tx.nondust_htlcs().len() {
6386 assert_eq!(predicted_fee_sat, _stats.commit_tx_fee_sat);
6387 }
6388 }
6389 #[cfg(debug_assertions)]
6390 {
6391 let mut broadcaster_prev_commitment_balance = if generated_by_local {
6394 funding.holder_prev_commitment_tx_balance.lock().unwrap()
6395 } else {
6396 funding.counterparty_prev_commitment_tx_balance.lock().unwrap()
6397 };
6398
6399 #[cfg(test)]
6404 if _stats.local_balance_before_fee_msat / 1000 < funding.counterparty_selected_channel_reserve_satoshis.unwrap() {
6405 debug_assert!(broadcaster_prev_commitment_balance.0 <= _stats.local_balance_before_fee_msat);
6408 }
6409 broadcaster_prev_commitment_balance.0 = _stats.local_balance_before_fee_msat;
6410
6411 if _stats.remote_balance_before_fee_msat / 1000 < funding.holder_selected_channel_reserve_satoshis {
6412 debug_assert!(broadcaster_prev_commitment_balance.1 <= _stats.remote_balance_before_fee_msat);
6415 }
6416 broadcaster_prev_commitment_balance.1 = _stats.remote_balance_before_fee_msat;
6417 }
6418
6419 for nondust_htlc in tx.nondust_htlcs() {
6425 let htlc = htlcs_included
6426 .iter_mut()
6427 .filter(|(htlc, _source)| htlc.transaction_output_index.is_none())
6428 .find_map(|(htlc, _source)| {
6429 if htlc.is_data_equal(nondust_htlc) {
6430 Some(htlc)
6431 } else {
6432 None
6433 }
6434 })
6435 .unwrap();
6436 htlc.transaction_output_index = Some(nondust_htlc.transaction_output_index.unwrap());
6437 }
6438
6439 htlcs_included.sort_unstable_by(|(htlc_a, _), (htlc_b, _)| {
6442 match (htlc_a.transaction_output_index, htlc_b.transaction_output_index) {
6443 (None, Some(_)) => cmp::Ordering::Greater,
6445 (Some(_), None) => cmp::Ordering::Less,
6446 (l, r) => cmp::Ord::cmp(&l, &r),
6447 }
6448 });
6449
6450 CommitmentData {
6451 tx,
6452 htlcs_included,
6453 inbound_htlc_preimages,
6454 outbound_htlc_preimages,
6455 }
6456 }
6457
6458 pub fn get_feerate_sat_per_1000_weight(&self) -> u32 {
6459 self.feerate_per_kw
6460 }
6461
6462 pub fn get_dust_buffer_feerate(&self, outbound_feerate_update: Option<u32>) -> u32 {
6463 let mut feerate_per_kw = self.feerate_per_kw;
6469 if let Some((feerate, _)) = self.pending_update_fee {
6472 feerate_per_kw = cmp::max(feerate_per_kw, feerate);
6473 }
6474 if let Some(feerate) = outbound_feerate_update {
6475 feerate_per_kw = cmp::max(feerate_per_kw, feerate);
6476 }
6477 let feerate_plus_quarter = feerate_per_kw.checked_mul(1250).map(|v| v / 1000);
6478 cmp::max(feerate_per_kw.saturating_add(2530), feerate_plus_quarter.unwrap_or(u32::MAX))
6479 }
6480
6481 pub fn counterparty_forwarding_info(&self) -> Option<CounterpartyForwardingInfo> {
6483 self.counterparty_forwarding_info.clone()
6484 }
6485
6486 #[rustfmt::skip]
6488 pub fn get_pending_inbound_htlc_details(&self, funding: &FundingScope) -> Vec<InboundHTLCDetails> {
6489 let mut holding_cell_states = new_hash_map();
6490 for holding_cell_update in self.holding_cell_htlc_updates.iter() {
6491 match holding_cell_update {
6492 HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => {
6493 holding_cell_states.insert(
6494 htlc_id,
6495 InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFulfill,
6496 );
6497 },
6498 HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => {
6499 holding_cell_states.insert(
6500 htlc_id,
6501 InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFail,
6502 );
6503 },
6504 HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, .. } => {
6505 holding_cell_states.insert(
6506 htlc_id,
6507 InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFail,
6508 );
6509 },
6510 HTLCUpdateAwaitingACK::AddHTLC { .. } => {},
6512 }
6513 }
6514 let mut inbound_details = Vec::new();
6515
6516 let dust_buffer_feerate = self.get_dust_buffer_feerate(None);
6517 let (htlc_success_tx_fee_sat, _) = second_stage_tx_fees_sat(
6518 funding.get_channel_type(), dust_buffer_feerate,
6519 );
6520 let holder_dust_limit_success_sat = htlc_success_tx_fee_sat + self.holder_dust_limit_satoshis;
6521 for htlc in self.pending_inbound_htlcs.iter() {
6522 if let Some(state_details) = (&htlc.state).into() {
6523 inbound_details.push(InboundHTLCDetails{
6524 htlc_id: htlc.htlc_id,
6525 amount_msat: htlc.amount_msat,
6526 cltv_expiry: htlc.cltv_expiry,
6527 payment_hash: htlc.payment_hash,
6528 state: Some(holding_cell_states.remove(&htlc.htlc_id).unwrap_or(state_details)),
6529 is_dust: htlc.amount_msat / 1000 < holder_dust_limit_success_sat,
6530 });
6531 }
6532 }
6533 inbound_details
6534 }
6535
6536 #[rustfmt::skip]
6538 pub fn get_pending_outbound_htlc_details(&self, funding: &FundingScope) -> Vec<OutboundHTLCDetails> {
6539 let mut outbound_details = Vec::new();
6540
6541 let dust_buffer_feerate = self.get_dust_buffer_feerate(None);
6542 let (_, htlc_timeout_tx_fee_sat) = second_stage_tx_fees_sat(
6543 funding.get_channel_type(), dust_buffer_feerate,
6544 );
6545 let holder_dust_limit_timeout_sat = htlc_timeout_tx_fee_sat + self.holder_dust_limit_satoshis;
6546 for htlc in self.pending_outbound_htlcs.iter() {
6547 outbound_details.push(OutboundHTLCDetails{
6548 htlc_id: Some(htlc.htlc_id),
6549 amount_msat: htlc.amount_msat,
6550 cltv_expiry: htlc.cltv_expiry,
6551 payment_hash: htlc.payment_hash,
6552 skimmed_fee_msat: htlc.skimmed_fee_msat,
6553 state: Some((&htlc.state).into()),
6554 is_dust: htlc.amount_msat / 1000 < holder_dust_limit_timeout_sat,
6555 });
6556 }
6557 for holding_cell_update in self.holding_cell_htlc_updates.iter() {
6558 if let HTLCUpdateAwaitingACK::AddHTLC {
6559 amount_msat,
6560 cltv_expiry,
6561 payment_hash,
6562 skimmed_fee_msat,
6563 ..
6564 } = *holding_cell_update {
6565 outbound_details.push(OutboundHTLCDetails{
6566 htlc_id: None,
6567 amount_msat: amount_msat,
6568 cltv_expiry: cltv_expiry,
6569 payment_hash: payment_hash,
6570 skimmed_fee_msat: skimmed_fee_msat,
6571 state: Some(OutboundHTLCStateDetails::AwaitingRemoteRevokeToAdd),
6572 is_dust: amount_msat / 1000 < holder_dust_limit_timeout_sat,
6573 });
6574 }
6575 }
6576 outbound_details
6577 }
6578
6579 fn get_available_balances_for_scope<F: FeeEstimator>(
6580 &self, funding: &FundingScope, fee_estimator: &LowerBoundedFeeEstimator<F>,
6581 ) -> Result<AvailableBalances, ()> {
6582 let htlc_candidate = None;
6583 let addl_nondust_htlc_count = 0;
6584 let dust_exposure_limiting_feerate =
6585 self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
6586
6587 let balances = self
6588 .get_next_remote_commitment_stats(
6589 funding,
6590 htlc_candidate,
6591 NextCommitmentView::ValidatingOwnUpdate,
6592 addl_nondust_htlc_count,
6593 self.feerate_per_kw,
6594 false,
6595 dust_exposure_limiting_feerate,
6596 )
6597 .map(|(remote_stats, _)| remote_stats.available_balances)?;
6598
6599 #[cfg(debug_assertions)]
6600 if balances.next_outbound_htlc_limit_msat >= balances.next_outbound_htlc_minimum_msat
6601 && balances.next_outbound_htlc_limit_msat != 0
6602 {
6603 let (remote_stats, _remote_htlcs) = self
6604 .get_next_remote_commitment_stats(
6605 funding,
6606 Some(HTLCAmountDirection {
6607 outbound: true,
6608 amount_msat: balances.next_outbound_htlc_limit_msat,
6612 }),
6613 NextCommitmentView::ValidatingOwnUpdate,
6614 addl_nondust_htlc_count,
6615 self.feerate_per_kw,
6616 false,
6617 dust_exposure_limiting_feerate,
6618 )
6619 .unwrap();
6620 assert!(
6621 remote_stats.commitment_stats.holder_balance_msat
6622 >= funding.counterparty_selected_channel_reserve_satoshis.unwrap_or(0) * 1000
6623 );
6624 }
6625
6626 Ok(balances)
6627 }
6628
6629 #[rustfmt::skip]
6630 fn if_unbroadcasted_funding<F, O>(&self, f: F) -> Option<O> where F: Fn() -> Option<O> {
6631 match self.channel_state {
6632 ChannelState::FundingNegotiated(_) => f(),
6633 ChannelState::AwaitingChannelReady(flags) =>
6634 if flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH) ||
6635 flags.is_set(FundedStateFlags::MONITOR_UPDATE_IN_PROGRESS.into())
6636 {
6637 f()
6638 } else {
6639 None
6640 },
6641 _ => None,
6642 }
6643 }
6644
6645 pub fn unbroadcasted_funding(&self, funding: &FundingScope) -> Option<Transaction> {
6651 self.if_unbroadcasted_funding(|| funding.funding_transaction.clone())
6652 }
6653
6654 pub fn unbroadcasted_funding_txid(&self, funding: &FundingScope) -> Option<Txid> {
6657 self.if_unbroadcasted_funding(|| {
6658 funding.channel_transaction_parameters.funding_outpoint.map(|txo| txo.txid)
6659 })
6660 }
6661
6662 pub fn is_batch_funding(&self) -> bool {
6664 self.is_batch_funding.is_some()
6665 }
6666
6667 pub fn unbroadcasted_batch_funding_txid(&self, funding: &FundingScope) -> Option<Txid> {
6670 self.unbroadcasted_funding_txid(funding).filter(|_| self.is_batch_funding())
6671 }
6672
6673 fn force_shutdown(
6676 &mut self, funding: &FundingScope, mut closure_reason: ClosureReason,
6677 ) -> ShutdownResult {
6678 assert!(!matches!(self.channel_state, ChannelState::ShutdownComplete));
6683
6684 let broadcast = self.is_funding_broadcastable();
6685
6686 let mut dropped_outbound_htlcs = Vec::with_capacity(self.holding_cell_htlc_updates.len());
6689 let counterparty_node_id = self.get_counterparty_node_id();
6690 for htlc_update in self.holding_cell_htlc_updates.drain(..) {
6691 match htlc_update {
6692 HTLCUpdateAwaitingACK::AddHTLC { source, payment_hash, .. } => {
6693 dropped_outbound_htlcs.push((
6694 source,
6695 payment_hash,
6696 counterparty_node_id,
6697 self.channel_id,
6698 ));
6699 },
6700 _ => {},
6701 }
6702 }
6703
6704 'htlc_iter: for htlc in self.pending_outbound_htlcs.iter() {
6710 if let OutboundHTLCState::LocalAnnounced(_) = htlc.state {
6711 for update in self.blocked_monitor_updates.iter() {
6712 for update in update.update.updates.iter() {
6713 let have_htlc = match update {
6714 ChannelMonitorUpdateStep::LatestCounterpartyCommitment {
6715 htlc_data,
6716 ..
6717 } => {
6718 let dust =
6719 htlc_data.dust_htlcs.iter().map(|(_, source)| source.as_ref());
6720 let nondust =
6721 htlc_data.nondust_htlc_sources.iter().map(|s| Some(s));
6722 dust.chain(nondust).any(|source| source == Some(&htlc.source))
6723 },
6724 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
6725 htlc_outputs,
6726 ..
6727 } => htlc_outputs.iter().any(|(_, source)| {
6728 source.as_ref().map(|s| &**s) == Some(&htlc.source)
6729 }),
6730 _ => continue,
6731 };
6732 debug_assert!(have_htlc);
6733 if have_htlc {
6734 dropped_outbound_htlcs.push((
6735 htlc.source.clone(),
6736 htlc.payment_hash,
6737 counterparty_node_id,
6738 self.channel_id,
6739 ));
6740 }
6741 continue 'htlc_iter;
6742 }
6743 }
6744 }
6745 }
6746
6747 let monitor_update = if let Some(funding_txo) = funding.get_funding_txo() {
6748 if self.counterparty_next_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER {
6754 self.latest_monitor_update_id = self.get_latest_unblocked_monitor_update_id() + 1;
6755
6756 let counterparty_failed_htlcs = self
6761 .monitor_pending_failures
6762 .drain(..)
6763 .map(|(source, payment_hash, _)| (source, payment_hash))
6764 .collect();
6765 let update = ChannelMonitorUpdate {
6766 update_id: self.latest_monitor_update_id,
6767 updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed {
6768 should_broadcast: broadcast,
6769 counterparty_failed_htlcs,
6770 }],
6771 channel_id: Some(self.channel_id()),
6772 };
6773 Some((self.get_counterparty_node_id(), funding_txo, self.channel_id(), update))
6774 } else {
6775 None
6776 }
6777 } else {
6778 None
6779 };
6780 let unbroadcasted_batch_funding_txid = self.unbroadcasted_batch_funding_txid(funding);
6781 let unbroadcasted_funding_tx = self.unbroadcasted_funding(funding);
6782
6783 if let ClosureReason::HolderForceClosed { ref mut broadcasted_latest_txn, .. } =
6784 &mut closure_reason
6785 {
6786 *broadcasted_latest_txn = Some(broadcast);
6787 }
6788
6789 self.channel_state = ChannelState::ShutdownComplete;
6790 self.update_time_counter += 1;
6791 ShutdownResult {
6792 closure_reason,
6793 monitor_update,
6794 dropped_outbound_htlcs,
6795 unbroadcasted_batch_funding_txid,
6796 channel_id: self.channel_id,
6797 user_channel_id: self.user_id,
6798 channel_capacity_satoshis: funding.get_value_satoshis(),
6799 counterparty_node_id: self.counterparty_node_id,
6800 unbroadcasted_funding_tx,
6801 is_manual_broadcast: self.is_manual_broadcast,
6802 channel_funding_txo: funding.get_funding_txo(),
6803 last_local_balance_msat: funding.value_to_self_msat,
6804 splice_funding_failed: Vec::new(),
6805 splice_funding_negotiated: None,
6806 }
6807 }
6808
6809 #[rustfmt::skip]
6811 fn get_funding_signed_msg<L: Logger>(
6812 &mut self, channel_parameters: &ChannelTransactionParameters, logger: &L,
6813 counterparty_initial_commitment_tx: CommitmentTransaction,
6814 ) -> Option<msgs::FundingSigned> {
6815 let counterparty_trusted_tx = counterparty_initial_commitment_tx.trust();
6816 let counterparty_initial_bitcoin_tx = counterparty_trusted_tx.built_transaction();
6817 log_trace!(logger, "Initial counterparty tx for channel {} is: txid {} tx {}",
6818 &self.channel_id(), counterparty_initial_bitcoin_tx.txid, encode::serialize_hex(&counterparty_initial_bitcoin_tx.transaction));
6819
6820 let signature = self
6822 .holder_signer
6823 .sign_counterparty_commitment(
6824 channel_parameters,
6825 &counterparty_initial_commitment_tx,
6826 Vec::new(),
6827 Vec::new(),
6828 &self.secp_ctx,
6829 )
6830 .ok();
6831
6832 if signature.is_some() && self.signer_pending_funding {
6833 log_trace!(logger, "Counterparty commitment signature available for funding_signed message; clearing signer_pending_funding");
6834 self.signer_pending_funding = false;
6835 } else if signature.is_none() {
6836 log_trace!(logger, "Counterparty commitment signature not available for funding_signed message; setting signer_pending_funding");
6837 self.signer_pending_funding = true;
6838 }
6839
6840 signature.map(|(signature, _)| msgs::FundingSigned {
6841 channel_id: self.channel_id(),
6842 signature,
6843 })
6844 }
6845
6846 pub(crate) fn maybe_downgrade_channel_features<F: FeeEstimator>(
6850 &mut self, funding: &mut FundingScope, fee_estimator: &LowerBoundedFeeEstimator<F>,
6851 user_config: &UserConfig, their_features: &InitFeatures,
6852 ) -> Result<(), ()> {
6853 if !funding.is_outbound()
6854 || !matches!(
6855 self.channel_state, ChannelState::NegotiatingFunding(flags)
6856 if flags == NegotiatingFundingFlags::OUR_INIT_SENT
6857 ) {
6858 return Err(());
6859 }
6860 if funding.get_channel_type() == &ChannelTypeFeatures::only_static_remote_key() {
6861 return Err(());
6863 }
6864
6865 let channel_type = &funding.channel_transaction_parameters.channel_type_features;
6868 assert!(!channel_type.supports_anchors_nonzero_fee_htlc_tx());
6869
6870 let mut eligible_features = their_features.clone();
6876 if channel_type.supports_anchor_zero_fee_commitments() {
6877 eligible_features.clear_anchor_zero_fee_commitments();
6878 } else if channel_type.supports_anchors_zero_fee_htlc_tx() {
6879 eligible_features.clear_anchor_zero_fee_commitments();
6880 eligible_features.clear_anchors_zero_fee_htlc_tx();
6881 } else if channel_type.supports_scid_privacy() {
6882 eligible_features.clear_scid_privacy();
6883 eligible_features.clear_anchors_zero_fee_htlc_tx();
6884 eligible_features.clear_anchor_zero_fee_commitments();
6885 }
6886
6887 let next_channel_type = get_initial_channel_type(user_config, &eligible_features);
6888 if !next_channel_type.supports_anchors_zero_fee_htlc_tx()
6889 && !next_channel_type.supports_anchor_zero_fee_commitments()
6890 && funding.holder_selected_channel_reserve_satoshis == 0
6891 {
6892 return Err(());
6894 }
6895
6896 self.feerate_per_kw =
6897 selected_commitment_sat_per_1000_weight(&fee_estimator, &next_channel_type);
6898 funding.channel_transaction_parameters.channel_type_features = next_channel_type;
6899
6900 Ok(())
6901 }
6902
6903 fn assert_no_commitment_advancement(
6905 &self, holder_commitment_transaction_number: u64, msg_name: &str,
6906 ) {
6907 if self.commitment_secrets.get_min_seen_secret() != (1 << 48)
6908 || self.counterparty_next_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER
6909 || holder_commitment_transaction_number != INITIAL_COMMITMENT_NUMBER
6910 {
6911 debug_assert!(
6912 false,
6913 "Should not have advanced channel commitment tx numbers prior to {}",
6914 msg_name
6915 );
6916 }
6917 }
6918
6919 fn get_initial_counterparty_commitment_signatures<L: Logger>(
6920 &self, funding: &FundingScope, logger: &L,
6921 ) -> Option<(Signature, Vec<Signature>)> {
6922 let mut commitment_number = self.counterparty_next_commitment_transaction_number;
6923 let mut commitment_point = self.counterparty_next_commitment_point.unwrap();
6924
6925 if commitment_number != INITIAL_COMMITMENT_NUMBER {
6927 commitment_number += 1;
6928 commitment_point = self.counterparty_current_commitment_point.unwrap();
6929 }
6930
6931 let commitment_data = self.build_commitment_transaction(
6932 funding,
6933 commitment_number,
6934 &commitment_point,
6935 false,
6936 true,
6937 logger,
6938 );
6939 let counterparty_initial_commitment_tx = commitment_data.tx;
6940 let channel_parameters = &funding.channel_transaction_parameters;
6941 self.holder_signer
6942 .sign_counterparty_commitment(
6943 channel_parameters,
6944 &counterparty_initial_commitment_tx,
6945 Vec::new(),
6946 Vec::new(),
6947 &self.secp_ctx,
6948 )
6949 .ok()
6950 }
6951
6952 fn get_initial_commitment_signed_v2<L: Logger>(
6953 &mut self, funding: &FundingScope, logger: &L,
6954 ) -> Option<msgs::CommitmentSigned> {
6955 let signatures = self.get_initial_counterparty_commitment_signatures(funding, logger);
6956 if let Some((signature, htlc_signatures)) = signatures {
6957 log_info!(logger, "Generated commitment_signed for peer",);
6958 if matches!(self.channel_state, ChannelState::FundingNegotiated(_)) {
6959 debug_assert!(htlc_signatures.is_empty());
6961 }
6962 self.signer_pending_funding = false;
6963 Some(msgs::CommitmentSigned {
6964 channel_id: self.channel_id,
6965 htlc_signatures,
6966 signature,
6967 funding_txid: funding.get_funding_txo().map(|funding_txo| funding_txo.txid),
6968 })
6969 } else {
6970 log_debug!(
6971 logger,
6972 "Initial counterparty commitment signature not available, waiting on async signer"
6973 );
6974 self.signer_pending_funding = true;
6975 None
6976 }
6977 }
6978
6979 fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
6980 let minimum_depth = self
6981 .minimum_depth(funding)
6982 .expect("ChannelContext::minimum_depth should be set for FundedChannel");
6983
6984 if minimum_depth == 0 {
6986 return true;
6987 }
6988
6989 if funding.funding_tx_confirmation_height == 0 {
6990 return false;
6991 }
6992
6993 let funding_tx_confirmations =
6994 height as i64 - funding.funding_tx_confirmation_height as i64 + 1;
6995 if funding_tx_confirmations < minimum_depth as i64 {
6996 return false;
6997 }
6998
6999 return true;
7000 }
7001
7002 #[rustfmt::skip]
7003 fn check_for_funding_tx_confirmed<L: Logger>(
7004 &mut self, funding: &mut FundingScope, block_hash: &BlockHash, height: u32,
7005 index_in_block: usize, tx: &mut ConfirmedTransaction, logger: &L,
7006 ) -> Result<bool, ClosureReason> {
7007 let funding_txo = match funding.get_funding_txo() {
7008 Some(funding_txo) => funding_txo,
7009 None => {
7010 debug_assert!(false);
7011 return Ok(false);
7012 },
7013 };
7014
7015 if funding.funding_tx_confirmation_height == 0 {
7018 if tx.txid() == funding_txo.txid {
7019 let tx = tx.tx();
7020 let txo_idx = funding_txo.index as usize;
7021 if txo_idx >= tx.output.len() || tx.output[txo_idx].script_pubkey != funding.get_funding_redeemscript().to_p2wsh() ||
7022 tx.output[txo_idx].value.to_sat() != funding.get_value_satoshis() {
7023 if funding.is_outbound() {
7024 #[cfg(not(fuzzing))]
7030 panic!("Client called ChannelManager::funding_transaction_generated with bogus transaction!");
7031 }
7032 self.update_time_counter += 1;
7033 let err_reason = "funding tx had wrong script/value or output index";
7034 return Err(ClosureReason::ProcessingError { err: err_reason.to_owned() });
7035 } else {
7036 if funding.is_outbound() {
7037 if !tx.is_coinbase() {
7038 for input in tx.input.iter() {
7039 if input.witness.is_empty() {
7040 #[cfg(not(fuzzing))]
7043 panic!("Client called ChannelManager::funding_transaction_generated with bogus transaction!");
7044 }
7045 }
7046 }
7047 }
7048
7049 funding.funding_tx_confirmation_height = height;
7050 funding.funding_tx_confirmed_in = Some(*block_hash);
7051 funding.short_channel_id = match scid_from_parts(height as u64, index_in_block as u64, txo_idx as u64) {
7052 Ok(scid) => Some(scid),
7053 Err(_) => panic!("Block was bogus - either height was > 16 million, had > 16 million transactions, or had > 65k outputs"),
7054 };
7055
7056 log_info!(
7057 logger,
7058 "Funding txid {} confirmed in block {}",
7059 funding_txo.txid,
7060
7061 block_hash,
7062 );
7063
7064 return Ok(true);
7065 }
7066 }
7067 }
7068
7069 Ok(false)
7070 }
7071
7072 pub fn historical_scids(&self) -> &[u64] {
7074 &self.historical_scids[..]
7075 }
7076}
7077
7078fn get_holder_max_htlc_value_in_flight_msat(
7092 channel_value_satoshis: u64, is_announced_channel: bool, config: &ChannelHandshakeConfig,
7093) -> u64 {
7094 let config_setting = if is_announced_channel {
7095 config.announced_channel_max_inbound_htlc_value_in_flight_percentage
7096 } else {
7097 config.unannounced_channel_max_inbound_htlc_value_in_flight_percentage
7098 };
7099 let configured_percent = if config_setting < 1 {
7100 1
7101 } else if config_setting > 100 {
7102 100
7103 } else {
7104 config_setting as u64
7105 };
7106 channel_value_satoshis * 10 * configured_percent
7107}
7108
7109fn get_legacy_default_holder_max_htlc_value_in_flight_msat(channel_value_satoshis: u64) -> u64 {
7114 channel_value_satoshis * 10 * MAX_IN_FLIGHT_PERCENT_LEGACY as u64
7115}
7116
7117pub(crate) fn get_holder_selected_channel_reserve_satoshis(
7131 channel_value_satoshis: u64, their_dust_limit_satoshis: u64, config: &UserConfig,
7132 is_0reserve: bool,
7133) -> Result<u64, ()> {
7134 if channel_value_satoshis < MIN_THEIR_CHAN_RESERVE_SATOSHIS
7135 || channel_value_satoshis < their_dust_limit_satoshis
7136 {
7137 return Err(());
7138 }
7139 if is_0reserve {
7140 return Ok(0);
7141 }
7142 let counterparty_chan_reserve_prop_mil = cmp::min(
7144 config.channel_handshake_config.their_channel_reserve_proportional_millionths as u64,
7145 1_000_000,
7146 );
7147 let calculated_reserve =
7148 channel_value_satoshis.saturating_mul(counterparty_chan_reserve_prop_mil) / 1_000_000;
7149 let channel_reserve_satoshis = cmp::max(calculated_reserve, MIN_THEIR_CHAN_RESERVE_SATOSHIS);
7150 let channel_reserve_satoshis = cmp::max(channel_reserve_satoshis, their_dust_limit_satoshis);
7151 Ok(channel_reserve_satoshis)
7152}
7153
7154pub(crate) fn get_legacy_default_holder_selected_channel_reserve_satoshis(
7159 channel_value_satoshis: u64,
7160) -> u64 {
7161 let (q, _) = channel_value_satoshis.overflowing_div(100);
7162 cmp::min(channel_value_satoshis, cmp::max(q, 1000))
7163}
7164
7165pub(crate) fn get_v2_channel_reserve_satoshis(
7175 channel_value_satoshis: u64, dust_limit_satoshis: u64, is_0reserve: bool,
7176) -> Result<u64, ()> {
7177 if channel_value_satoshis < dust_limit_satoshis {
7178 return Err(());
7179 }
7180 if is_0reserve {
7181 return Ok(0);
7182 }
7183 let (q, _) = channel_value_satoshis.overflowing_div(100);
7185 Ok(cmp::max(q, dust_limit_satoshis))
7186}
7187
7188#[derive(Debug)]
7190pub(super) struct FundingNegotiationContext {
7191 pub is_initiator: bool,
7193 pub our_funding_contribution: SignedAmount,
7195 pub funding_tx_locktime: LockTime,
7198 #[allow(dead_code)] pub funding_feerate_sat_per_1000_weight: u32,
7201 #[allow(dead_code)] pub shared_funding_input: Option<SharedOwnedInput>,
7204 #[allow(dead_code)] pub our_funding_inputs: Vec<ConfirmedUtxo>,
7207 #[allow(dead_code)] pub our_funding_outputs: Vec<TxOut>,
7210}
7211
7212impl FundingNegotiationContext {
7213 fn into_interactive_tx_constructor<SP: SignerProvider, ES: EntropySource>(
7216 self, context: &ChannelContext<SP>, funding: &FundingScope, entropy_source: &ES,
7217 holder_node_id: PublicKey,
7218 ) -> (InteractiveTxConstructor, Option<InteractiveTxMessageSend>) {
7219 debug_assert_eq!(
7220 self.shared_funding_input.is_some(),
7221 funding.channel_transaction_parameters.splice_parent_funding_txid.is_some(),
7222 );
7223
7224 if self.shared_funding_input.is_some() {
7225 debug_assert!(matches!(context.channel_state, ChannelState::ChannelReady(_)));
7226 } else {
7227 debug_assert!(matches!(context.channel_state, ChannelState::NegotiatingFunding(_)));
7228 }
7229
7230 let shared_funding_output = TxOut {
7231 value: Amount::from_sat(funding.get_value_satoshis()),
7232 script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
7233 };
7234
7235 let constructor_args = InteractiveTxConstructorArgs {
7236 entropy_source,
7237 holder_node_id,
7238 counterparty_node_id: context.counterparty_node_id,
7239 channel_id: context.channel_id(),
7240 feerate_sat_per_kw: self.funding_feerate_sat_per_1000_weight,
7241 funding_tx_locktime: self.funding_tx_locktime,
7242 inputs_to_contribute: self.our_funding_inputs,
7243 shared_funding_input: self.shared_funding_input,
7244 shared_funding_output: SharedOwnedOutput::new(
7245 shared_funding_output,
7246 funding.value_to_self_msat / 1000,
7247 ),
7248 outputs_to_contribute: self.our_funding_outputs,
7249 };
7250 if self.is_initiator {
7251 InteractiveTxConstructor::new_for_outbound(constructor_args)
7252 } else {
7253 (InteractiveTxConstructor::new_for_inbound(constructor_args), None)
7254 }
7255 }
7256
7257 fn contributed_inputs(&self) -> impl Iterator<Item = bitcoin::OutPoint> + '_ {
7258 self.our_funding_inputs.iter().map(|input| input.utxo.outpoint)
7259 }
7260
7261 fn contributed_outputs(&self) -> impl Iterator<Item = &bitcoin::Script> + '_ {
7262 self.our_funding_outputs.iter().map(|output| output.script_pubkey.as_script())
7263 }
7264}
7265
7266#[cfg_attr(test, derive(Debug))]
7269pub(super) struct FundedChannel<SP: SignerProvider> {
7270 pub funding: FundingScope,
7271 pub context: ChannelContext<SP>,
7272 holder_commitment_point: HolderCommitmentPoint,
7273
7274 pending_splice: Option<PendingFunding>,
7276
7277 quiescent_action: Option<QuiescentAction>,
7282}
7283
7284#[cfg(any(test, fuzzing))]
7285#[derive(Clone, Copy, Default, Debug)]
7286struct PredictedNextFee {
7287 predicted_feerate: u32,
7288 predicted_nondust_htlc_count: usize,
7289 predicted_fee_sat: u64,
7290}
7291
7292trait FailHTLCContents {
7295 type Message: FailHTLCMessageName;
7296 fn to_message(self, htlc_id: u64, channel_id: ChannelId) -> Self::Message;
7297 fn to_inbound_htlc_state(self) -> InboundHTLCState;
7298 fn to_htlc_update_awaiting_ack(self, htlc_id: u64) -> HTLCUpdateAwaitingACK;
7299}
7300impl FailHTLCContents for msgs::OnionErrorPacket {
7301 type Message = msgs::UpdateFailHTLC;
7302 fn to_message(self, htlc_id: u64, channel_id: ChannelId) -> Self::Message {
7303 msgs::UpdateFailHTLC {
7304 htlc_id,
7305 channel_id,
7306 reason: self.data,
7307 attribution_data: self.attribution_data,
7308 }
7309 }
7310 fn to_inbound_htlc_state(self) -> InboundHTLCState {
7311 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(self))
7312 }
7313 fn to_htlc_update_awaiting_ack(self, htlc_id: u64) -> HTLCUpdateAwaitingACK {
7314 HTLCUpdateAwaitingACK::FailHTLC { htlc_id, err_packet: self }
7315 }
7316}
7317impl FailHTLCContents for ([u8; 32], u16) {
7318 type Message = msgs::UpdateFailMalformedHTLC;
7319 fn to_message(self, htlc_id: u64, channel_id: ChannelId) -> Self::Message {
7320 msgs::UpdateFailMalformedHTLC {
7321 htlc_id,
7322 channel_id,
7323 sha256_of_onion: self.0,
7324 failure_code: self.1,
7325 }
7326 }
7327 fn to_inbound_htlc_state(self) -> InboundHTLCState {
7328 InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailMalformed {
7329 sha256_of_onion: self.0,
7330 failure_code: self.1,
7331 })
7332 }
7333 fn to_htlc_update_awaiting_ack(self, htlc_id: u64) -> HTLCUpdateAwaitingACK {
7334 HTLCUpdateAwaitingACK::FailMalformedHTLC {
7335 htlc_id,
7336 sha256_of_onion: self.0,
7337 failure_code: self.1,
7338 }
7339 }
7340}
7341
7342trait FailHTLCMessageName {
7343 fn name() -> &'static str;
7344}
7345impl FailHTLCMessageName for msgs::UpdateFailHTLC {
7346 fn name() -> &'static str {
7347 "update_fail_htlc"
7348 }
7349}
7350impl FailHTLCMessageName for msgs::UpdateFailMalformedHTLC {
7351 fn name() -> &'static str {
7352 "update_fail_malformed_htlc"
7353 }
7354}
7355
7356type BestBlockUpdatedRes = (
7357 Option<FundingConfirmedMessage>,
7358 Vec<(HTLCSource, PaymentHash)>,
7359 Option<msgs::AnnouncementSignatures>,
7360 Option<SpliceRbfAbort>,
7361);
7362
7363pub(super) struct TxCompleteResult {
7365 pub interactive_tx_msg_send: Option<InteractiveTxMessageSend>,
7367
7368 pub event_unsigned_tx: Option<Transaction>,
7371
7372 pub funding_tx_signed: Option<FundingTxSigned>,
7375}
7376
7377#[derive(Default)]
7379pub(super) struct FundingTxSigned {
7380 pub commitment_signed: Option<msgs::CommitmentSigned>,
7382
7383 pub counterparty_initial_commitment_signed_result:
7386 Option<Result<Option<ChannelMonitorUpdate>, ChannelError>>,
7387
7388 pub tx_signatures: Option<msgs::TxSignatures>,
7390
7391 pub funding_tx: Option<(Transaction, TransactionType)>,
7393
7394 pub splice_negotiated: Option<SpliceFundingNegotiated>,
7396
7397 pub splice_locked: Option<msgs::SpliceLocked>,
7399}
7400
7401pub struct SpliceFundingNegotiated {
7403 pub funding_txo: bitcoin::OutPoint,
7405
7406 pub has_local_contribution: bool,
7408
7409 pub channel_type: ChannelTypeFeatures,
7411
7412 pub funding_redeem_script: ScriptBuf,
7414}
7415
7416pub struct SpliceFundingFailed {
7418 contributed_inputs: Vec<bitcoin::OutPoint>,
7421
7422 contributed_outputs: Vec<TxOut>,
7425
7426 contribution: FundingContribution,
7428}
7429
7430pub(super) struct SpliceRbfAbort {
7432 pub tx_abort: msgs::TxAbort,
7433 pub splice_funding_failed: Option<SpliceFundingFailed>,
7434}
7435
7436impl SpliceFundingFailed {
7437 fn from_contribution(contribution: FundingContribution) -> Self {
7441 let (contributed_inputs, contributed_outputs) = contribution
7442 .unique_contributions()
7443 .map(|(inputs, outputs)| (inputs, outputs.into_iter().cloned().collect()))
7444 .unwrap_or_default();
7445 Self { contributed_inputs, contributed_outputs, contribution }
7446 }
7447
7448 pub(super) fn into_parts(self) -> (Option<FundingInfo>, FailedSpliceContribution) {
7451 let funding_info = FundingInfo::contribution(
7452 self.contributed_inputs.clone(),
7453 self.contributed_outputs.iter().map(|output| output.script_pubkey.clone()).collect(),
7454 );
7455 let contribution = FailedSpliceContribution::new(
7456 self.contributed_inputs,
7457 self.contributed_outputs,
7458 self.contribution,
7459 );
7460 (funding_info, contribution)
7461 }
7462}
7463
7464pub struct SpliceFundingPromotion {
7465 pub funding_txo: OutPoint,
7466 pub monitor_update: Option<ChannelMonitorUpdate>,
7467 pub announcement_sigs: Option<msgs::AnnouncementSignatures>,
7468 pub discarded_funding: Vec<FundingInfo>,
7469 pub splice_funding_failed: Option<SpliceFundingFailed>,
7470}
7471
7472impl<SP: SignerProvider> FundedChannel<SP>
7473where
7474 SP::EcdsaSigner: EcdsaChannelSigner,
7475{
7476 pub fn context(&self) -> &ChannelContext<SP> {
7477 &self.context
7478 }
7479
7480 pub fn force_shutdown(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
7481 let (splice_funding_failed, splice_funding_negotiated) =
7482 self.resolve_pending_splice_on_close();
7483
7484 let mut shutdown_result = self.context.force_shutdown(&self.funding, closure_reason);
7485 shutdown_result.splice_funding_failed = splice_funding_failed;
7486 shutdown_result.splice_funding_negotiated = splice_funding_negotiated;
7487 shutdown_result
7488 }
7489
7490 fn abandon_quiescent_action(&mut self) -> Option<SpliceFundingFailed> {
7491 match self.quiescent_action.take()? {
7492 QuiescentAction::Splice { contribution, .. } => {
7493 Some(SpliceFundingFailed::from_contribution(contribution))
7494 },
7495 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
7496 QuiescentAction::DoNothing => None,
7497 }
7498 }
7499
7500 fn resolve_pending_splice_on_close(
7501 &mut self,
7502 ) -> (Vec<SpliceFundingFailed>, Option<SpliceFundingNegotiated>) {
7503 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
7504 return (Vec::new(), None);
7505 }
7506 let queued_failed = self.abandon_quiescent_action();
7509 let (negotiation_failed, splice_funding_negotiated) = self.reset_pending_splice_state();
7510 let splice_funding_failed = negotiation_failed.into_iter().chain(queued_failed).collect();
7511 (splice_funding_failed, splice_funding_negotiated)
7512 }
7513
7514 fn interactive_tx_constructor_mut(&mut self) -> Option<&mut InteractiveTxConstructor> {
7515 self.pending_splice
7516 .as_mut()
7517 .and_then(|pending_splice| pending_splice.funding_negotiation.as_mut())
7518 .and_then(|funding_negotiation| {
7519 if let FundingNegotiation::ConstructingTransaction {
7520 interactive_tx_constructor,
7521 ..
7522 } = funding_negotiation
7523 {
7524 Some(interactive_tx_constructor)
7525 } else {
7526 None
7527 }
7528 })
7529 }
7530
7531 fn negotiated_candidates(&self) -> &[NegotiatedCandidate] {
7532 self.pending_splice
7533 .as_ref()
7534 .map(|pending_splice| pending_splice.negotiated_candidates.as_slice())
7535 .unwrap_or(&[])
7536 }
7537
7538 fn pending_funding(&self) -> impl ExactSizeIterator<Item = &FundingScope> + '_ {
7539 self.negotiated_candidates().iter().map(|candidate| &candidate.funding)
7540 }
7541
7542 fn funding_and_pending_funding_iter_mut(&mut self) -> impl Iterator<Item = &mut FundingScope> {
7543 core::iter::once(&mut self.funding).chain(
7544 self.pending_splice
7545 .as_mut()
7546 .map(|pending_splice| pending_splice.negotiated_candidates.as_mut_slice())
7547 .unwrap_or(&mut [])
7548 .iter_mut()
7549 .map(|candidate| &mut candidate.funding),
7550 )
7551 }
7552
7553 pub fn pending_splice_details(&self, best_block_height: u32) -> Option<SpliceDetails> {
7556 let mut details = self
7557 .pending_splice
7558 .as_ref()
7559 .map(|pending_splice| pending_splice.to_details(&self.context, best_block_height));
7560
7561 if let Some(contribution) = self.queued_funding_contribution() {
7565 let status = if self.pending_splice.is_none()
7570 || self.queued_contribution_can_rbf(contribution)
7571 {
7572 SpliceCandidateStatus::WaitingOnQuiescence
7573 } else {
7574 SpliceCandidateStatus::WaitingOnLock
7575 };
7576 let candidate =
7577 SpliceCandidateDetails { contribution: Some(contribution.clone()), status };
7578 match &mut details {
7579 Some(details) => details.candidates.push(candidate),
7580 None => {
7583 details = Some(SpliceDetails {
7584 candidates: vec![candidate],
7585 confirmed_candidate: None,
7586 received_splice_locked_txid: None,
7587 });
7588 },
7589 }
7590 }
7591
7592 details
7593 }
7594
7595 fn has_pending_splice_awaiting_signatures(&self) -> bool {
7596 self.pending_splice
7597 .as_ref()
7598 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
7599 .map(|funding_negotiation| {
7600 matches!(funding_negotiation, FundingNegotiation::AwaitingSignatures { .. })
7601 })
7602 .unwrap_or(false)
7603 }
7604
7605 fn should_reset_pending_splice_state(&self, allow_resumption: bool) -> bool {
7608 self.pending_splice
7609 .as_ref()
7610 .map(|pending_splice| {
7611 pending_splice
7612 .funding_negotiation
7613 .as_ref()
7614 .map(|funding_negotiation| {
7615 let is_awaiting_signatures = matches!(
7616 funding_negotiation,
7617 FundingNegotiation::AwaitingSignatures { .. }
7618 );
7619 if allow_resumption {
7620 !is_awaiting_signatures
7623 } else {
7624 !is_awaiting_signatures
7625 || !self
7626 .context()
7627 .interactive_tx_signing_session
7628 .as_ref()
7629 .expect("We have a pending splice awaiting signatures")
7630 .has_received_commitment_signed()
7631 }
7632 })
7633 .unwrap_or_else(|| {
7634 let has_negotiated_candidates =
7635 !pending_splice.negotiated_candidates.is_empty();
7636 debug_assert!(has_negotiated_candidates);
7637 !has_negotiated_candidates
7638 })
7639 })
7640 .unwrap_or(false)
7641 }
7642
7643 fn reset_pending_splice_state(
7646 &mut self,
7647 ) -> (Option<SpliceFundingFailed>, Option<SpliceFundingNegotiated>) {
7648 let funding_negotiation = self
7649 .pending_splice
7650 .as_mut()
7651 .and_then(|pending_splice| pending_splice.funding_negotiation.take());
7652
7653 let (counterparty_committed, splice_funding_negotiated) = match funding_negotiation.as_ref()
7654 {
7655 Some(FundingNegotiation::AwaitingSignatures { funding, .. }) => {
7656 let signing_session = self
7657 .context
7658 .interactive_tx_signing_session
7659 .as_ref()
7660 .expect("We have a pending splice awaiting signatures");
7661 let splice_funding_negotiated =
7662 signing_session.holder_tx_signatures().map(|_| SpliceFundingNegotiated {
7663 funding_txo: funding
7664 .get_funding_txo()
7665 .expect("Negotiated funding has an outpoint")
7666 .into_bitcoin_outpoint(),
7667 has_local_contribution: signing_session.has_local_contribution(),
7668 channel_type: funding.get_channel_type().clone(),
7669 funding_redeem_script: funding.get_funding_redeemscript(),
7670 });
7671 (signing_session.has_received_commitment_signed(), splice_funding_negotiated)
7672 },
7673 _ => (false, None),
7674 };
7675 let splice_funding_failed =
7676 if funding_negotiation.is_some() && splice_funding_negotiated.is_none() {
7677 self.pending_splice.as_mut().and_then(|pending_splice| {
7678 if let Some(ref contribution) = pending_splice.negotiation_contribution {
7679 debug_assert!(
7680 pending_splice
7681 .last_funding_feerate_sat_per_1000_weight
7682 .map(|f| contribution.feerate() > FeeRate::from_sat_per_kwu(f as u64))
7683 .unwrap_or(true),
7684 "current round's feerate should be greater than the last negotiated feerate",
7685 );
7686 }
7687 pending_splice.negotiation_contribution.take().map(|contribution| {
7688 if counterparty_committed {
7689 SpliceFundingFailed {
7692 contributed_inputs: Vec::new(),
7693 contributed_outputs: Vec::new(),
7694 contribution,
7695 }
7696 } else {
7697 SpliceFundingFailed::from_contribution(contribution)
7698 }
7699 })
7700 })
7701 } else {
7702 None
7703 };
7704
7705 if self.negotiated_candidates().is_empty() {
7706 self.pending_splice.take();
7707 }
7708 if funding_negotiation.is_some() {
7709 self.exit_quiescence();
7710 }
7711 if matches!(funding_negotiation, Some(FundingNegotiation::AwaitingSignatures { .. })) {
7712 self.context.interactive_tx_signing_session.take();
7717 self.context.signer_pending_funding = false;
7718 }
7719
7720 (splice_funding_failed, splice_funding_negotiated)
7721 }
7722
7723 fn abort_ongoing_rbf_after_splice_confirmation<L: Logger>(
7724 &mut self, logger: &L,
7725 ) -> Option<SpliceRbfAbort> {
7726 let has_ongoing_rbf = self
7727 .pending_splice
7728 .as_ref()
7729 .map(|pending_splice| {
7730 pending_splice.has_confirmed_candidate()
7731 && pending_splice.funding_negotiation.is_some()
7732 })
7733 .unwrap_or(false);
7734 if !has_ongoing_rbf {
7735 return None;
7736 }
7737
7738 let has_provided_funding_signatures = self.has_pending_splice_awaiting_signatures()
7741 && self
7742 .context
7743 .interactive_tx_signing_session
7744 .as_ref()
7745 .map(|signing_session| signing_session.has_holder_witnesses())
7746 .unwrap_or(false);
7747 if has_provided_funding_signatures {
7748 debug_assert!(!self.should_reset_pending_splice_state(true));
7752 log_debug!(
7753 logger,
7754 "Continuing an RBF negotiation after another splice candidate confirmed because signing has advanced too far to abort safely",
7755 );
7756 return None;
7757 }
7758
7759 log_info!(logger, "Aborting an active RBF negotiation after a splice candidate confirmed");
7760 let (splice_funding_failed, splice_funding_negotiated) = self.reset_pending_splice_state();
7761 debug_assert!(splice_funding_negotiated.is_none());
7762 let tx_abort =
7763 AbortReason::RbfUnavailable("A negotiated splice candidate has confirmed".to_owned())
7764 .into_tx_abort_msg(self.context.channel_id());
7765 Some(SpliceRbfAbort { tx_abort, splice_funding_failed })
7766 }
7767
7768 pub(super) fn on_restart_splice_failures(&self) -> impl Iterator<Item = SpliceFundingFailed> {
7772 let mut negotiation_failure = None;
7773 if self.should_reset_pending_splice_state(true) {
7774 let pending_splice = self
7775 .pending_splice
7776 .as_ref()
7777 .expect("should_reset_pending_splice_state requires pending_splice");
7778 debug_assert!(
7779 pending_splice.funding_negotiation.is_some(),
7780 "a pending splice to reset requires an active funding negotiation"
7781 );
7782 negotiation_failure = pending_splice
7783 .negotiation_contribution
7784 .clone()
7785 .map(SpliceFundingFailed::from_contribution);
7786 }
7787
7788 let queued_failure =
7791 self.queued_funding_contribution().cloned().map(SpliceFundingFailed::from_contribution);
7792
7793 negotiation_failure.into_iter().chain(queued_failure)
7794 }
7795
7796 #[rustfmt::skip]
7797 fn check_remote_fee<F: FeeEstimator, L: Logger>(
7798 channel_type: &ChannelTypeFeatures, fee_estimator: &LowerBoundedFeeEstimator<F>,
7799 feerate_per_kw: u32, cur_feerate_per_kw: Option<u32>, logger: &L
7800 ) -> Result<(), ChannelError> {
7801 if channel_type.supports_anchor_zero_fee_commitments() {
7802 if feerate_per_kw != 0 {
7803 let err = "Zero Fee Channels must never attempt to use a fee".to_owned();
7804 return Err(ChannelError::close(err));
7805 } else {
7806 return Ok(());
7807 }
7808 }
7809
7810 let lower_limit_conf_target = if channel_type.supports_anchors_zero_fee_htlc_tx() {
7811 ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
7812 } else {
7813 ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
7814 };
7815 let lower_limit = fee_estimator.bounded_sat_per_1000_weight(lower_limit_conf_target);
7816 if feerate_per_kw < lower_limit {
7817 if let Some(cur_feerate) = cur_feerate_per_kw {
7818 if feerate_per_kw > cur_feerate {
7819 log_warn!(logger,
7820 "Accepting feerate that may prevent us from closing this channel because it's higher than what we have now. Had {} s/kW, now {} s/kW.",
7821 cur_feerate, feerate_per_kw);
7822 return Ok(());
7823 }
7824 }
7825 return Err(ChannelError::Close((format!(
7826 "Peer's feerate much too low. Actual: {}. Our expected lower limit: {}", feerate_per_kw, lower_limit
7827 ), ClosureReason::PeerFeerateTooLow {
7828 peer_feerate_sat_per_kw: feerate_per_kw,
7829 required_feerate_sat_per_kw: lower_limit,
7830 })));
7831 }
7832 Ok(())
7833 }
7834
7835 #[inline]
7836 fn get_closing_scriptpubkey(&self) -> ScriptBuf {
7837 self.context.shutdown_scriptpubkey.clone().unwrap().into_inner()
7841 }
7842
7843 #[inline]
7844 fn get_closing_transaction_weight(
7845 &self, a_scriptpubkey: Option<&Script>, b_scriptpubkey: Option<&Script>,
7846 ) -> u64 {
7847 let mut ret = (4 + 1 + 36 + 1 + 4 + 1 + 4 )*4 + 2 + 1 + 4 + self.funding.get_funding_redeemscript().len() as u64 + 2*(1 + 71); if let Some(spk) = a_scriptpubkey {
7861 ret += ((8+1) + spk.len() as u64) * 4; }
7865 if let Some(spk) = b_scriptpubkey {
7866 ret += ((8+1) + spk.len() as u64) * 4; }
7870 ret
7871 }
7872
7873 #[inline]
7874 fn build_closing_transaction(
7875 &self, proposed_total_fee_satoshis: u64, skip_remote_output: bool,
7876 ) -> Result<(ClosingTransaction, u64), ChannelError> {
7877 assert!(self.context.pending_inbound_htlcs.is_empty());
7878 assert!(self.context.pending_outbound_htlcs.is_empty());
7879 assert!(self.context.pending_update_fee.is_none());
7880
7881 let mut total_fee_satoshis = proposed_total_fee_satoshis;
7882 let mut value_to_holder: i64 = (self.funding.value_to_self_msat as i64) / 1000
7883 - if self.funding.is_outbound() { total_fee_satoshis as i64 } else { 0 };
7884 let mut value_to_counterparty: i64 =
7885 ((self.funding.get_value_satoshis() * 1000 - self.funding.value_to_self_msat) as i64
7886 / 1000) - if self.funding.is_outbound() { 0 } else { total_fee_satoshis as i64 };
7887
7888 if value_to_holder < 0 {
7889 assert!(self.funding.is_outbound());
7890 total_fee_satoshis += (-value_to_holder) as u64;
7891 } else if value_to_counterparty < 0 {
7892 assert!(!self.funding.is_outbound());
7893 total_fee_satoshis += (-value_to_counterparty) as u64;
7894 }
7895
7896 debug_assert!(value_to_counterparty >= 0);
7897 if value_to_counterparty < 0 {
7898 return Err(ChannelError::close(format!(
7899 "Value to counterparty below 0: {}",
7900 value_to_counterparty
7901 )));
7902 }
7903 if skip_remote_output
7904 || value_to_counterparty as u64 <= self.context.holder_dust_limit_satoshis
7905 {
7906 value_to_counterparty = 0;
7907 }
7908
7909 debug_assert!(value_to_holder >= 0);
7910 if value_to_holder < 0 {
7911 return Err(ChannelError::close(format!(
7912 "Value to holder below 0: {}",
7913 value_to_holder
7914 )));
7915 }
7916 if value_to_holder as u64 <= self.context.holder_dust_limit_satoshis {
7917 value_to_holder = 0;
7918 }
7919
7920 assert!(self.context.shutdown_scriptpubkey.is_some());
7921 let holder_shutdown_script = self.get_closing_scriptpubkey();
7922 let counterparty_shutdown_script =
7923 self.context.counterparty_shutdown_scriptpubkey.clone().unwrap();
7924 let funding_outpoint = self.funding_outpoint().into_bitcoin_outpoint();
7925
7926 let closing_transaction = ClosingTransaction::new(
7927 value_to_holder as u64,
7928 value_to_counterparty as u64,
7929 holder_shutdown_script,
7930 counterparty_shutdown_script,
7931 funding_outpoint,
7932 );
7933 Ok((closing_transaction, total_fee_satoshis))
7934 }
7935
7936 pub fn funding_outpoint(&self) -> OutPoint {
7937 self.funding.channel_transaction_parameters.funding_outpoint.unwrap()
7938 }
7939
7940 pub fn claim_htlc_while_disconnected_dropping_mon_update_legacy<L: Logger>(
7951 &mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage, logger: &L,
7952 ) {
7953 assert!(!self.context.channel_state.can_generate_new_commitment());
7956 let mon_update_id = self.context.latest_monitor_update_id; let fulfill_resp =
7958 self.get_update_fulfill_htlc(htlc_id_arg, payment_preimage_arg, None, None, logger);
7959 self.context.latest_monitor_update_id = mon_update_id;
7960 if let UpdateFulfillFetch::NewClaim { update_blocked, .. } = fulfill_resp {
7961 assert!(update_blocked); }
7963 }
7964
7965 fn get_update_fulfill_htlc<L: Logger>(
7966 &mut self, htlc_id_arg: u64, payment_preimage_arg: PaymentPreimage,
7967 payment_info: Option<PaymentClaimDetails>, attribution_data: Option<AttributionData>,
7968 logger: &L,
7969 ) -> UpdateFulfillFetch {
7970 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
7975 panic!("Was asked to fulfill an HTLC when channel was not in an operational state");
7976 }
7977
7978 let mut pending_idx = core::usize::MAX;
7983 let mut htlc_value_msat = 0;
7984 for (idx, htlc) in self.context.pending_inbound_htlcs.iter().enumerate() {
7985 if htlc.htlc_id == htlc_id_arg {
7986 let expected_hash =
7987 PaymentHash(Sha256::hash(&payment_preimage_arg.0[..]).to_byte_array());
7988 debug_assert_eq!(htlc.payment_hash, expected_hash);
7989 log_debug!(
7990 logger,
7991 "Claiming inbound HTLC id {} with payment hash {} with preimage {}",
7992 htlc.htlc_id,
7993 htlc.payment_hash,
7994 payment_preimage_arg
7995 );
7996 match htlc.state {
7997 InboundHTLCState::Committed { .. } => {},
7998 InboundHTLCState::LocalRemoved(ref reason) => {
7999 if let &InboundHTLCRemovalReason::Fulfill { .. } = reason {
8000 } else {
8001 log_warn!(logger, "Have preimage and want to fulfill HTLC with payment hash {} we already failed against channel {}", &htlc.payment_hash, &self.context.channel_id());
8002 debug_assert!(
8003 false,
8004 "Tried to fulfill an HTLC that was already failed"
8005 );
8006 }
8007 return UpdateFulfillFetch::DuplicateClaim {};
8008 },
8009 _ => {
8010 debug_assert!(false, "Have an inbound HTLC we tried to claim before it was fully committed to");
8011 },
8013 }
8014 pending_idx = idx;
8015 htlc_value_msat = htlc.amount_msat;
8016 break;
8017 }
8018 }
8019 if pending_idx == core::usize::MAX {
8020 return UpdateFulfillFetch::DuplicateClaim {};
8021 }
8022
8023 self.context.latest_monitor_update_id += 1;
8028 let monitor_update = ChannelMonitorUpdate {
8029 update_id: self.context.latest_monitor_update_id,
8030 updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
8031 payment_preimage: payment_preimage_arg.clone(),
8032 payment_info,
8033 }],
8034 channel_id: Some(self.context.channel_id()),
8035 };
8036
8037 if !self.context.channel_state.can_generate_new_commitment() {
8038 for pending_update in self.context.holding_cell_htlc_updates.iter() {
8043 match pending_update {
8044 &HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => {
8045 if htlc_id_arg == htlc_id {
8046 self.context.latest_monitor_update_id -= 1;
8048 return UpdateFulfillFetch::DuplicateClaim {};
8049 }
8050 },
8051 &HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. }
8052 | &HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, .. } => {
8053 if htlc_id_arg == htlc_id {
8054 log_warn!(logger, "Have preimage and want to fulfill HTLC with pending failure against channel {}", &self.context.channel_id());
8055 debug_assert!(
8058 false,
8059 "Tried to fulfill an HTLC that was already failed"
8060 );
8061 return UpdateFulfillFetch::NewClaim {
8062 monitor_update,
8063 htlc_value_msat,
8064 update_blocked: true,
8065 };
8066 }
8067 },
8068 _ => {},
8069 }
8070 }
8071 log_trace!(
8072 logger,
8073 "Adding HTLC claim to holding_cell! Current state: {}",
8074 self.context.channel_state.to_u32()
8075 );
8076 self.context.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::ClaimHTLC {
8077 payment_preimage: payment_preimage_arg,
8078 htlc_id: htlc_id_arg,
8079 attribution_data,
8080 });
8081 return UpdateFulfillFetch::NewClaim {
8082 monitor_update,
8083 htlc_value_msat,
8084 update_blocked: true,
8085 };
8086 }
8087
8088 {
8089 let htlc = &mut self.context.pending_inbound_htlcs[pending_idx];
8090 if let InboundHTLCState::Committed { .. } = htlc.state {
8091 } else {
8092 debug_assert!(
8093 false,
8094 "Have an inbound HTLC we tried to claim before it was fully committed to"
8095 );
8096 return UpdateFulfillFetch::NewClaim {
8097 monitor_update,
8098 htlc_value_msat,
8099 update_blocked: true,
8100 };
8101 }
8102 log_trace!(
8103 logger,
8104 "Upgrading HTLC {} to LocalRemoved with a Fulfill!",
8105 &htlc.payment_hash,
8106 );
8107 htlc.state = InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill {
8108 preimage: payment_preimage_arg.clone(),
8109 attribution_data,
8110 });
8111 }
8112
8113 UpdateFulfillFetch::NewClaim { monitor_update, htlc_value_msat, update_blocked: false }
8114 }
8115
8116 pub fn get_update_fulfill_htlc_and_commit<L: Logger>(
8117 &mut self, htlc_id: u64, payment_preimage: PaymentPreimage,
8118 payment_info: Option<PaymentClaimDetails>, attribution_data: Option<AttributionData>,
8119 logger: &L,
8120 ) -> UpdateFulfillCommitFetch {
8121 let release_cs_monitor = self.context.blocked_monitor_updates.is_empty();
8122 match self.get_update_fulfill_htlc(
8123 htlc_id,
8124 payment_preimage,
8125 payment_info,
8126 attribution_data,
8127 logger,
8128 ) {
8129 UpdateFulfillFetch::NewClaim {
8130 mut monitor_update,
8131 htlc_value_msat,
8132 update_blocked,
8133 } => {
8134 if release_cs_monitor && !update_blocked {
8140 let mut additional_update = self.build_commitment_no_status_check(logger);
8141 self.context.latest_monitor_update_id = monitor_update.update_id;
8144 monitor_update.updates.append(&mut additional_update.updates);
8145 } else {
8146 let blocked_upd = self.context.blocked_monitor_updates.get(0);
8147 let new_mon_id = blocked_upd
8148 .map(|upd| upd.update.update_id)
8149 .unwrap_or(monitor_update.update_id);
8150 monitor_update.update_id = new_mon_id;
8151 for held_update in self.context.blocked_monitor_updates.iter_mut() {
8152 held_update.update.update_id += 1;
8153 }
8154 if !update_blocked {
8155 debug_assert!(false, "If there is a pending blocked monitor we should have MonitorUpdateInProgress set");
8156 let update = self.build_commitment_no_status_check(logger);
8157 self.context
8158 .blocked_monitor_updates
8159 .push(PendingChannelMonitorUpdate { update });
8160 }
8161 }
8162
8163 self.monitor_updating_paused(
8164 false,
8165 !update_blocked,
8166 false,
8167 Vec::new(),
8168 Vec::new(),
8169 Vec::new(),
8170 logger,
8171 );
8172 UpdateFulfillCommitFetch::NewClaim { monitor_update, htlc_value_msat }
8173 },
8174 UpdateFulfillFetch::DuplicateClaim {} => UpdateFulfillCommitFetch::DuplicateClaim {},
8175 }
8176 }
8177
8178 pub fn queue_fail_htlc<L: Logger>(
8181 &mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket, logger: &L,
8182 ) -> Result<(), ChannelError> {
8183 self.fail_htlc(htlc_id_arg, err_packet, true, logger)
8184 .map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?"))
8185 }
8186
8187 pub fn queue_fail_malformed_htlc<L: Logger>(
8192 &mut self, htlc_id_arg: u64, failure_code: u16, sha256_of_onion: [u8; 32], logger: &L,
8193 ) -> Result<(), ChannelError> {
8194 self.fail_htlc(htlc_id_arg, (sha256_of_onion, failure_code), true, logger)
8195 .map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?"))
8196 }
8197
8198 #[rustfmt::skip]
8201 fn fail_htlc<L: Logger, E: FailHTLCContents + Clone>(
8202 &mut self, htlc_id_arg: u64, err_contents: E, mut force_holding_cell: bool,
8203 logger: &L
8204 ) -> Result<Option<E::Message>, ChannelError> {
8205 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
8206 panic!("Was asked to fail an HTLC when channel was not in an operational state");
8207 }
8208
8209 let mut pending_idx = core::usize::MAX;
8214 for (idx, htlc) in self.context.pending_inbound_htlcs.iter().enumerate() {
8215 if htlc.htlc_id == htlc_id_arg {
8216 match htlc.state {
8217 InboundHTLCState::Committed { .. } => {},
8218 InboundHTLCState::LocalRemoved(_) => {
8219 return Err(ChannelError::Ignore(format!("HTLC {} was already resolved", htlc.htlc_id)));
8220 },
8221 _ => {
8222 debug_assert!(false, "Have an inbound HTLC we tried to claim before it was fully committed to");
8223 return Err(ChannelError::Ignore(format!("Unable to find a pending HTLC which matched the given HTLC ID ({})", htlc.htlc_id)));
8224 }
8225 }
8226 pending_idx = idx;
8227 }
8228 }
8229 if pending_idx == core::usize::MAX {
8230 return Err(ChannelError::Ignore(format!("Unable to find a pending HTLC which matched the given HTLC ID ({})", htlc_id_arg)));
8231 }
8232
8233 if !self.context.channel_state.can_generate_new_commitment() {
8234 debug_assert!(force_holding_cell, "!force_holding_cell is only called when emptying the holding cell, so we shouldn't end up back in it!");
8235 force_holding_cell = true;
8236 }
8237
8238 if force_holding_cell {
8240 for pending_update in self.context.holding_cell_htlc_updates.iter() {
8241 match pending_update {
8242 &HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => {
8243 if htlc_id_arg == htlc_id {
8244 return Err(ChannelError::Ignore(format!("HTLC {} was already claimed!", htlc_id)));
8245 }
8246 },
8247 &HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } |
8248 &HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, .. } =>
8249 {
8250 if htlc_id_arg == htlc_id {
8251 return Err(ChannelError::Ignore(format!("HTLC {} was already pending failure", htlc_id)));
8252 }
8253 },
8254 _ => {}
8255 }
8256 }
8257 log_trace!(logger, "Placing failure for HTLC ID {} in holding cell.", htlc_id_arg);
8258 self.context.holding_cell_htlc_updates.push(err_contents.to_htlc_update_awaiting_ack(htlc_id_arg));
8259 return Ok(None);
8260 }
8261
8262 log_trace!(logger, "Failing HTLC ID {} back with {} message.", htlc_id_arg,
8263 E::Message::name());
8264 {
8265 let htlc = &mut self.context.pending_inbound_htlcs[pending_idx];
8266 htlc.state = err_contents.clone().to_inbound_htlc_state();
8267 }
8268
8269 Ok(Some(err_contents.to_message(htlc_id_arg, self.context.channel_id())))
8270 }
8271
8272 pub fn set_batch_ready(&mut self) {
8278 self.context.is_batch_funding = None;
8279 self.context.channel_state.clear_waiting_for_batch();
8280 }
8281
8282 pub fn unset_funding_info(&mut self) {
8289 let sent_or_received_tx_signatures = self
8290 .context
8291 .interactive_tx_signing_session
8292 .as_ref()
8293 .map(|signing_session| {
8294 signing_session.has_holder_witnesses()
8295 || signing_session.has_received_tx_signatures()
8296 })
8297 .unwrap_or(false);
8298 debug_assert!(
8299 matches!(
8300 self.context.channel_state,
8301 ChannelState::FundingNegotiated(_) if !sent_or_received_tx_signatures
8302 ) || matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(_))
8303 );
8304 self.context.unset_funding_info(&mut self.funding);
8305 }
8306
8307 #[rustfmt::skip]
8311 pub fn channel_ready<NS: NodeSigner, L: Logger>(
8312 &mut self, msg: &msgs::ChannelReady, node_signer: &NS, chain_hash: ChainHash,
8313 user_config: &UserConfig, best_block: &BlockLocator, logger: &L
8314 ) -> Result<Option<msgs::AnnouncementSignatures>, ChannelError> {
8315 if self.context.channel_state.is_peer_disconnected() {
8316 self.context.workaround_lnd_bug_4006 = Some(msg.clone());
8317 return Err(ChannelError::Ignore("Peer sent channel_ready when we needed a channel_reestablish. The peer is likely lnd, see https://github.com/lightningnetwork/lnd/issues/4006".to_owned()));
8318 }
8319
8320 if let Some(scid_alias) = msg.short_channel_id_alias {
8321 if Some(scid_alias) != self.funding.short_channel_id {
8322 self.context.latest_inbound_scid_alias = Some(scid_alias);
8326 }
8327 }
8328
8329 let mut check_reconnection = false;
8332 match &self.context.channel_state {
8333 ChannelState::AwaitingChannelReady(flags) => {
8334 let flags = flags.clone().clear(FundedStateFlags::ALL.into());
8335 debug_assert!(!flags.is_set(AwaitingChannelReadyFlags::OUR_CHANNEL_READY) || !flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH));
8336 if flags.clone().clear(AwaitingChannelReadyFlags::WAITING_FOR_BATCH) == AwaitingChannelReadyFlags::THEIR_CHANNEL_READY {
8337 check_reconnection = true;
8339 } else if flags.clone().clear(AwaitingChannelReadyFlags::WAITING_FOR_BATCH).is_empty() {
8340 self.context.channel_state.set_their_channel_ready();
8341 } else if flags == AwaitingChannelReadyFlags::OUR_CHANNEL_READY {
8342 self.context.channel_state = ChannelState::ChannelReady(self.context.channel_state.with_funded_state_flags_mask().into());
8343 self.context.update_time_counter += 1;
8344 } else {
8345 debug_assert!(flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH));
8347 }
8348 }
8349 ChannelState::ChannelReady(_) => check_reconnection = true,
8351 _ => return Err(ChannelError::close("Peer sent a channel_ready at a strange time".to_owned())),
8352 }
8353 if check_reconnection {
8354 let expected_point =
8357 if self.context.counterparty_next_commitment_transaction_number == INITIAL_COMMITMENT_NUMBER - 1 {
8358 self.context.counterparty_next_commitment_point
8361 } else if self.context.counterparty_next_commitment_transaction_number == INITIAL_COMMITMENT_NUMBER - 2 {
8362 debug_assert!(self.context.counterparty_current_commitment_point.is_some());
8365 self.context.counterparty_current_commitment_point
8366 } else {
8367 Some(PublicKey::from_secret_key(&self.context.secp_ctx, &SecretKey::from_slice(
8370 &self.context.commitment_secrets.get_secret(INITIAL_COMMITMENT_NUMBER - 1).expect("We should have all prev secrets available")
8371 ).expect("We already advanced, so previous secret keys should have been validated already")))
8372 };
8373 if expected_point != Some(msg.next_per_commitment_point) {
8374 return Err(ChannelError::close("Peer sent a reconnect channel_ready with a different point".to_owned()));
8375 }
8376 return Ok(None);
8377 }
8378
8379 self.context.counterparty_current_commitment_point = self.context.counterparty_next_commitment_point;
8380 self.context.counterparty_next_commitment_point = Some(msg.next_per_commitment_point);
8381 self.context.interactive_tx_signing_session = None;
8382
8383 log_info!(logger, "Received channel_ready from peer for channel {}", &self.context.channel_id());
8384
8385 Ok(self.get_announcement_sigs(node_signer, chain_hash, user_config, best_block.height, logger))
8386 }
8387
8388 #[rustfmt::skip]
8389 pub fn update_add_htlc<F: FeeEstimator>(
8390 &mut self, msg: &msgs::UpdateAddHTLC, fee_estimator: &LowerBoundedFeeEstimator<F>,
8391 ) -> Result<(), ChannelError> {
8392 if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() {
8393 return Err(ChannelError::WarnAndDisconnect("Got add HTLC message while quiescent".to_owned()));
8394 }
8395 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
8396 return Err(ChannelError::close("Got add HTLC message when channel was not in an operational state".to_owned()));
8397 }
8398 if self.context.channel_state.is_remote_shutdown_sent() {
8400 return Err(ChannelError::close("Got add HTLC message when channel was not in an operational state".to_owned()));
8401 }
8402 if self.context.channel_state.is_peer_disconnected() {
8403 return Err(ChannelError::close("Peer sent update_add_htlc when we needed a channel_reestablish".to_owned()));
8404 }
8405 if msg.amount_msat == 0 {
8406 return Err(ChannelError::close("Remote side tried to send a 0-msat HTLC".to_owned()));
8407 }
8408 if msg.amount_msat < self.context.holder_htlc_minimum_msat {
8409 return Err(ChannelError::close(format!("Remote side tried to send less than our minimum HTLC value. Lower limit: ({}). Actual: ({})", self.context.holder_htlc_minimum_msat, msg.amount_msat)));
8410 }
8411 if self.context.next_counterparty_htlc_id != msg.htlc_id {
8412 return Err(ChannelError::close(format!("Remote skipped HTLC ID (skipped ID: {})", self.context.next_counterparty_htlc_id)));
8413 }
8414 if msg.cltv_expiry >= 500000000 {
8415 return Err(ChannelError::close("Remote provided CLTV expiry in seconds instead of block height".to_owned()));
8416 }
8417
8418 core::iter::once(&self.funding)
8419 .chain(self.pending_funding())
8420 .try_for_each(|funding| self.context.validate_update_add_htlc(funding, msg, fee_estimator))?;
8421
8422 self.context.next_counterparty_htlc_id += 1;
8424 self.context.pending_inbound_htlcs.push(InboundHTLCOutput {
8425 htlc_id: msg.htlc_id,
8426 amount_msat: msg.amount_msat,
8427 payment_hash: msg.payment_hash,
8428 cltv_expiry: msg.cltv_expiry,
8429 state: InboundHTLCState::RemoteAnnounced(InboundHTLCResolution::Pending {
8430 update_add_htlc: msg.clone(),
8431 }),
8432 });
8433 Ok(())
8434 }
8435
8436 pub(super) fn has_legacy_inbound_htlcs(&self) -> bool {
8440 self.context.pending_inbound_htlcs.iter().any(|htlc| {
8441 matches!(
8442 &htlc.state,
8443 InboundHTLCState::Committed { update_add_htlc: InboundUpdateAdd::Legacy }
8444 )
8445 })
8446 }
8447
8448 pub(super) fn inbound_htlcs_pending_decode(
8451 &self,
8452 ) -> impl Iterator<Item = msgs::UpdateAddHTLC> + '_ {
8453 self.context.pending_inbound_htlcs.iter().filter_map(|htlc| match &htlc.state {
8454 InboundHTLCState::Committed {
8455 update_add_htlc: InboundUpdateAdd::WithOnion { update_add_htlc },
8456 } => Some(update_add_htlc.clone()),
8457 _ => None,
8458 })
8459 }
8460
8461 pub(super) fn inbound_forwarded_htlcs(
8464 &self,
8465 ) -> impl Iterator<Item = (PaymentHash, HTLCPreviousHopData, OutboundHop)> + '_ {
8466 let htlc_resolution_in_holding_cell = |id: u64| -> bool {
8469 self.context.holding_cell_htlc_updates.iter().any(|holding_cell_htlc| {
8470 match holding_cell_htlc {
8471 HTLCUpdateAwaitingACK::ClaimHTLC { htlc_id, .. } => *htlc_id == id,
8472 HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => *htlc_id == id,
8473 HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, .. } => *htlc_id == id,
8474 HTLCUpdateAwaitingACK::AddHTLC { .. } => false,
8475 }
8476 })
8477 };
8478
8479 let prev_outbound_scid_alias = self.context.outbound_scid_alias();
8480 let user_channel_id = self.context.get_user_id();
8481 let channel_id = self.context.channel_id();
8482 let outpoint = self.funding_outpoint();
8483 let counterparty_node_id = self.context.get_counterparty_node_id();
8484
8485 self.context.pending_inbound_htlcs.iter().filter_map(move |htlc| match &htlc.state {
8486 InboundHTLCState::Committed {
8487 update_add_htlc:
8488 InboundUpdateAdd::Forwarded {
8489 incoming_packet_shared_secret,
8490 phantom_shared_secret,
8491 trampoline_shared_secret,
8492 blinded_failure,
8493 outbound_hop,
8494 },
8495 } => {
8496 if htlc_resolution_in_holding_cell(htlc.htlc_id) {
8497 return None;
8498 }
8499 let prev_hop_data = HTLCPreviousHopData {
8502 prev_outbound_scid_alias,
8503 user_channel_id: Some(user_channel_id),
8504 amount_msat: Some(htlc.amount_msat),
8505 htlc_id: htlc.htlc_id,
8506 incoming_packet_shared_secret: *incoming_packet_shared_secret,
8507 phantom_shared_secret: *phantom_shared_secret,
8508 trampoline_shared_secret: *trampoline_shared_secret,
8509 blinded_failure: *blinded_failure,
8510 channel_id,
8511 outpoint,
8512 counterparty_node_id: Some(counterparty_node_id),
8513 cltv_expiry: Some(htlc.cltv_expiry),
8514 };
8515 Some((htlc.payment_hash, prev_hop_data, *outbound_hop))
8516 },
8517 _ => None,
8518 })
8519 }
8520
8521 pub(super) fn outbound_htlc_forwards(
8525 &self,
8526 ) -> impl Iterator<Item = (PaymentHash, HTLCPreviousHopData)> + '_ {
8527 let holding_cell_outbounds =
8528 self.context.holding_cell_htlc_updates.iter().filter_map(|htlc| match htlc {
8529 HTLCUpdateAwaitingACK::AddHTLC { source, payment_hash, .. } => match source {
8530 HTLCSource::PreviousHopData(prev_hop_data) => {
8531 Some((*payment_hash, prev_hop_data.clone()))
8532 },
8533 _ => None,
8534 },
8535 _ => None,
8536 });
8537 let committed_outbounds =
8538 self.context.pending_outbound_htlcs.iter().filter_map(|htlc| match &htlc.source {
8539 HTLCSource::PreviousHopData(prev_hop_data) => {
8540 Some((htlc.payment_hash, prev_hop_data.clone()))
8541 },
8542 _ => None,
8543 });
8544 holding_cell_outbounds.chain(committed_outbounds)
8545 }
8546
8547 #[cfg(test)]
8548 pub(super) fn test_holding_cell_outbound_htlc_forwards_count(&self) -> usize {
8549 self.context
8550 .holding_cell_htlc_updates
8551 .iter()
8552 .filter_map(|htlc| match htlc {
8553 HTLCUpdateAwaitingACK::AddHTLC { source, .. } => match source {
8554 HTLCSource::PreviousHopData(prev_hop_data) => Some(prev_hop_data.clone()),
8555 _ => None,
8556 },
8557 _ => None,
8558 })
8559 .count()
8560 }
8561
8562 pub(super) fn prune_inbound_htlc_onion(
8565 &mut self, htlc_id: u64, prev_hop_data: &HTLCPreviousHopData,
8566 outbound_hop_data: OutboundHop,
8567 ) {
8568 for htlc in self.context.pending_inbound_htlcs.iter_mut() {
8569 if htlc.htlc_id == htlc_id {
8570 if let InboundHTLCState::Committed { ref mut update_add_htlc } = htlc.state {
8571 *update_add_htlc = InboundUpdateAdd::Forwarded {
8572 incoming_packet_shared_secret: prev_hop_data.incoming_packet_shared_secret,
8573 phantom_shared_secret: prev_hop_data.phantom_shared_secret,
8574 trampoline_shared_secret: prev_hop_data.trampoline_shared_secret,
8575 blinded_failure: prev_hop_data.blinded_failure,
8576 outbound_hop: outbound_hop_data,
8577 };
8578 return;
8579 }
8580 }
8581 }
8582 debug_assert!(false, "If we go to prune an inbound HTLC it should be present")
8583 }
8584
8585 pub(super) fn release_pending_inbound_held_htlc(&mut self, htlc_id: u64) -> bool {
8591 for update_add in self.context.monitor_pending_update_adds.iter_mut() {
8592 if update_add.htlc_id == htlc_id {
8593 update_add.hold_htlc.take();
8594 return true;
8595 }
8596 }
8597 for htlc in self.context.pending_inbound_htlcs.iter_mut() {
8598 if htlc.htlc_id != htlc_id {
8599 continue;
8600 }
8601 match &mut htlc.state {
8602 InboundHTLCState::RemoteAnnounced(InboundHTLCResolution::Pending {
8605 update_add_htlc,
8606 })
8607 | InboundHTLCState::AwaitingRemoteRevokeToAnnounce(
8608 InboundHTLCResolution::Pending { update_add_htlc },
8609 )
8610 | InboundHTLCState::AwaitingAnnouncedRemoteRevoke(
8611 InboundHTLCResolution::Pending { update_add_htlc },
8612 ) => {
8613 update_add_htlc.hold_htlc.take();
8614 return true;
8615 },
8616 _ => return false,
8617 }
8618 }
8619 false
8620 }
8621
8622 #[cfg(test)]
8624 pub(super) fn test_clear_holding_cell(&mut self) {
8625 self.context.holding_cell_htlc_updates.clear()
8626 }
8627
8628 #[inline]
8630 fn mark_outbound_htlc_removed(
8631 &mut self, htlc_id: u64, outcome: OutboundHTLCOutcome,
8632 ) -> Result<&OutboundHTLCOutput, ChannelError> {
8633 for htlc in self.context.pending_outbound_htlcs.iter_mut() {
8634 if htlc.htlc_id == htlc_id {
8635 if let OutboundHTLCOutcome::Success { ref preimage, .. } = outcome {
8636 let payment_hash = PaymentHash(Sha256::hash(&preimage.0[..]).to_byte_array());
8637 if payment_hash != htlc.payment_hash {
8638 return Err(ChannelError::close(format!(
8639 "Remote tried to fulfill HTLC ({}) with an incorrect preimage",
8640 htlc_id
8641 )));
8642 }
8643 }
8644 match htlc.state {
8645 OutboundHTLCState::LocalAnnounced(_) =>
8646 return Err(ChannelError::close(format!("Remote tried to fulfill/fail HTLC ({}) before it had been committed", htlc_id))),
8647 OutboundHTLCState::Committed => {
8648 htlc.state = OutboundHTLCState::RemoteRemoved(outcome);
8649 },
8650 OutboundHTLCState::AwaitingRemoteRevokeToRemove(_) | OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) | OutboundHTLCState::RemoteRemoved(_) =>
8651 return Err(ChannelError::close(format!("Remote tried to fulfill/fail HTLC ({}) that they'd already fulfilled/failed", htlc_id))),
8652 }
8653 return Ok(htlc);
8654 }
8655 }
8656 Err(ChannelError::close("Remote tried to fulfill/fail an HTLC we couldn't find".to_owned()))
8657 }
8658
8659 pub fn update_fulfill_htlc(
8660 &mut self, msg: &msgs::UpdateFulfillHTLC,
8661 ) -> Result<(HTLCSource, u64, Option<u64>, Option<Duration>), ChannelError> {
8662 if self.context.channel_state.is_remote_stfu_sent()
8663 || self.context.channel_state.is_quiescent()
8664 {
8665 return Err(ChannelError::WarnAndDisconnect(
8666 "Got fulfill HTLC message while quiescent".to_owned(),
8667 ));
8668 }
8669 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
8670 return Err(ChannelError::close(
8671 "Got fulfill HTLC message when channel was not in an operational state".to_owned(),
8672 ));
8673 }
8674 if self.context.channel_state.is_peer_disconnected() {
8675 return Err(ChannelError::close(
8676 "Peer sent update_fulfill_htlc when we needed a channel_reestablish".to_owned(),
8677 ));
8678 }
8679
8680 let outcome = OutboundHTLCOutcome::Success {
8681 preimage: msg.payment_preimage,
8682 attribution_data: msg.attribution_data.clone(),
8683 };
8684 self.mark_outbound_htlc_removed(msg.htlc_id, outcome).map(|htlc| {
8685 (htlc.source.clone(), htlc.amount_msat, htlc.skimmed_fee_msat, htlc.send_timestamp)
8686 })
8687 }
8688
8689 #[rustfmt::skip]
8690 pub fn update_fail_htlc(&mut self, msg: &msgs::UpdateFailHTLC, fail_reason: HTLCFailReason) -> Result<(), ChannelError> {
8691 if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() {
8692 return Err(ChannelError::WarnAndDisconnect("Got fail HTLC message while quiescent".to_owned()));
8693 }
8694 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
8695 return Err(ChannelError::close("Got fail HTLC message when channel was not in an operational state".to_owned()));
8696 }
8697 if self.context.channel_state.is_peer_disconnected() {
8698 return Err(ChannelError::close("Peer sent update_fail_htlc when we needed a channel_reestablish".to_owned()));
8699 }
8700
8701 self.mark_outbound_htlc_removed(msg.htlc_id, OutboundHTLCOutcome::Failure(fail_reason))?;
8702 Ok(())
8703 }
8704
8705 #[rustfmt::skip]
8706 pub fn update_fail_malformed_htlc(&mut self, msg: &msgs::UpdateFailMalformedHTLC, fail_reason: HTLCFailReason) -> Result<(), ChannelError> {
8707 if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() {
8708 return Err(ChannelError::WarnAndDisconnect("Got fail malformed HTLC message while quiescent".to_owned()));
8709 }
8710 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
8711 return Err(ChannelError::close("Got fail malformed HTLC message when channel was not in an operational state".to_owned()));
8712 }
8713 if self.context.channel_state.is_peer_disconnected() {
8714 return Err(ChannelError::close("Peer sent update_fail_malformed_htlc when we needed a channel_reestablish".to_owned()));
8715 }
8716
8717 self.mark_outbound_htlc_removed(msg.htlc_id, OutboundHTLCOutcome::Failure(fail_reason))?;
8718 Ok(())
8719 }
8720
8721 pub fn initial_commitment_signed_v2<L: Logger>(
8722 &mut self, msg: &msgs::CommitmentSigned, best_block: BlockLocator, signer_provider: &SP,
8723 logger: &L,
8724 ) -> Result<ChannelMonitor<SP::EcdsaSigner>, ChannelError> {
8725 if let Some(signing_session) = self.context.interactive_tx_signing_session.as_ref() {
8726 if signing_session.has_received_tx_signatures() {
8727 let msg = "Received initial commitment_signed after peer's tx_signatures received!";
8728 let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
8729 return Err(ChannelError::Close((msg.to_owned(), reason)));
8730 }
8731 } else {
8732 let msg = "Received initial commitment_signed before funding transaction constructed!";
8733 let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
8734 return Err(ChannelError::Close((msg.to_owned(), reason)));
8735 };
8736
8737 let holder_commitment_point = &mut self.holder_commitment_point.clone();
8738 self.context.assert_no_commitment_advancement(
8739 holder_commitment_point.next_transaction_number(),
8740 "initial commitment_signed",
8741 );
8742
8743 let (channel_monitor, _) = self.initial_commitment_signed(
8744 self.context.channel_id(),
8745 msg.signature,
8746 holder_commitment_point,
8747 best_block,
8748 signer_provider,
8749 logger,
8750 )?;
8751 self.holder_commitment_point = *holder_commitment_point;
8752
8753 log_info!(
8754 logger,
8755 "Received initial commitment_signed from peer for channel {}",
8756 &self.context.channel_id()
8757 );
8758
8759 self.monitor_updating_paused(
8760 false,
8761 false,
8762 false,
8763 Vec::new(),
8764 Vec::new(),
8765 Vec::new(),
8766 logger,
8767 );
8768 self.context
8769 .interactive_tx_signing_session
8770 .as_mut()
8771 .expect("signing session should be present")
8772 .received_commitment_signed();
8773 Ok(channel_monitor)
8774 }
8775
8776 fn splice_initial_commitment_signed<F: FeeEstimator, L: Logger>(
8789 &mut self, msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator<F>,
8790 logger: &L,
8791 ) -> Result<Option<ChannelMonitorUpdate>, ChannelError> {
8792 debug_assert!(self
8793 .context
8794 .interactive_tx_signing_session
8795 .as_ref()
8796 .map(|signing_session| !signing_session.has_received_tx_signatures())
8797 .unwrap_or(false));
8798
8799 let pending_splice_funding = self
8800 .pending_splice
8801 .as_ref()
8802 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
8803 .filter(|funding_negotiation| {
8804 matches!(funding_negotiation, FundingNegotiation::AwaitingSignatures { .. })
8805 })
8806 .and_then(|funding_negotiation| funding_negotiation.as_funding())
8807 .expect("Funding must exist for negotiated pending splice");
8808
8809 let transaction_number = self.holder_commitment_point.current_transaction_number();
8810 let commitment_point = self.holder_commitment_point.current_point().ok_or_else(|| {
8811 debug_assert!(false);
8812 ChannelError::close(
8813 "current_point should be set for channels initiating splicing".to_owned(),
8814 )
8815 })?;
8816 let (holder_commitment_tx, _) = self.context.validate_commitment_signed(
8817 pending_splice_funding,
8818 transaction_number,
8819 commitment_point,
8820 msg,
8821 fee_estimator,
8822 logger,
8823 )?;
8824 let counterparty_commitment_tx = self
8827 .context
8828 .build_commitment_transaction(
8829 pending_splice_funding,
8830 self.context.counterparty_next_commitment_transaction_number + 1,
8831 &self.context.counterparty_current_commitment_point.unwrap(),
8832 false,
8833 false,
8834 logger,
8835 )
8836 .tx;
8837
8838 {
8839 let counterparty_trusted_tx = counterparty_commitment_tx.trust();
8840 let counterparty_bitcoin_tx = counterparty_trusted_tx.built_transaction();
8841 log_trace!(
8842 logger,
8843 "Splice initial counterparty tx is: txid {} tx {}",
8844 counterparty_bitcoin_tx.txid,
8845 encode::serialize_hex(&counterparty_bitcoin_tx.transaction)
8846 );
8847 }
8848
8849 let funding_contribution = self
8850 .pending_splice
8851 .as_ref()
8852 .and_then(|pending_splice| pending_splice.negotiation_contribution.as_ref())
8853 .cloned();
8854
8855 log_info!(
8856 logger,
8857 "Received splice initial commitment_signed from peer with funding txid {}",
8858 pending_splice_funding.get_funding_txo().unwrap().txid
8859 );
8860
8861 self.context.latest_monitor_update_id += 1;
8862 let monitor_update = ChannelMonitorUpdate {
8863 update_id: self.context.latest_monitor_update_id,
8864 updates: vec![ChannelMonitorUpdateStep::RenegotiatedFunding {
8865 channel_parameters: pending_splice_funding.channel_transaction_parameters.clone(),
8866 holder_commitment_tx,
8867 counterparty_commitment_tx,
8868 funding_contribution,
8869 }],
8870 channel_id: Some(self.context.channel_id()),
8871 };
8872
8873 self.context
8874 .interactive_tx_signing_session
8875 .as_mut()
8876 .expect("Signing session must exist for negotiated pending splice")
8877 .received_commitment_signed();
8878 self.monitor_updating_paused(
8879 false,
8880 false,
8881 false,
8882 Vec::new(),
8883 Vec::new(),
8884 Vec::new(),
8885 logger,
8886 );
8887 self.context.monitor_pending_tx_signatures = true;
8888
8889 Ok(self.push_ret_blockable_mon_update(monitor_update))
8890 }
8891
8892 fn get_commitment_htlc_data<'a>(
8893 htlcs_included: &'a [(HTLCOutputInCommitment, Option<&HTLCSource>)],
8894 ) -> (
8895 impl Iterator<Item = HTLCSource> + 'a,
8896 impl Iterator<Item = (HTLCOutputInCommitment, Option<HTLCSource>)> + 'a,
8897 ) {
8898 let nondust_htlc_sources = htlcs_included
8899 .iter()
8900 .filter(|(htlc, _)| htlc.transaction_output_index.is_some() && htlc.offered)
8901 .map(|(_, source_opt)| source_opt.cloned().expect("Missing outbound HTLC source"));
8902 let dust_htlcs = htlcs_included
8903 .iter()
8904 .filter(|(htlc, _)| htlc.transaction_output_index.is_none())
8905 .map(|(htlc, source_opt)| (htlc.clone(), source_opt.cloned()));
8906 (nondust_htlc_sources, dust_htlcs)
8907 }
8908
8909 pub fn commitment_signed<F: FeeEstimator, L: Logger>(
8910 &mut self, msg: &msgs::CommitmentSigned, fee_estimator: &LowerBoundedFeeEstimator<F>,
8911 logger: &L,
8912 ) -> Result<Option<ChannelMonitorUpdate>, ChannelError> {
8913 self.commitment_signed_check_state()?;
8914
8915 if let Some(funding_txid) = msg.funding_txid {
8916 let is_known_funding = core::iter::once(&self.funding)
8919 .chain(self.pending_funding())
8920 .any(|funding| funding.get_funding_txid() == Some(funding_txid));
8921 if !is_known_funding {
8922 return Err(ChannelError::Ignore(format!(
8923 "Ignoring commitment_signed for stale funding txid {funding_txid}"
8924 )));
8925 }
8926 }
8927
8928 if !self.negotiated_candidates().is_empty() {
8929 return Err(ChannelError::close(
8930 "Got a single commitment_signed message when expecting a batch".to_owned(),
8931 ));
8932 }
8933
8934 let transaction_number = self.holder_commitment_point.next_transaction_number();
8935 let commitment_point = self.holder_commitment_point.next_point();
8936 let update = self
8937 .context
8938 .validate_commitment_signed(
8939 &self.funding,
8940 transaction_number,
8941 commitment_point,
8942 msg,
8943 fee_estimator,
8944 logger,
8945 )
8946 .map(|(commitment_tx, htlcs_included)| {
8947 let (nondust_htlc_sources, dust_htlcs) =
8948 Self::get_commitment_htlc_data(&htlcs_included);
8949 let htlc_outputs =
8950 dust_htlcs.into_iter().map(|(htlc, source)| (htlc, None, source)).collect();
8951 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
8952 commitment_tx,
8953 htlc_outputs,
8954 claimed_htlcs: vec![],
8955 nondust_htlc_sources: nondust_htlc_sources.collect(),
8956 }
8957 })?;
8958
8959 self.commitment_signed_update_monitor(update, logger)
8960 }
8961
8962 pub fn commitment_signed_batch<F: FeeEstimator, L: Logger>(
8963 &mut self, batch: Vec<msgs::CommitmentSigned>, fee_estimator: &LowerBoundedFeeEstimator<F>,
8964 logger: &L,
8965 ) -> Result<Option<ChannelMonitorUpdate>, ChannelError> {
8966 self.commitment_signed_check_state()?;
8967
8968 let mut messages = BTreeMap::new();
8969 for msg in batch {
8970 let funding_txid = match msg.funding_txid {
8971 Some(funding_txid) => funding_txid,
8972 None => {
8973 return Err(ChannelError::close(
8974 "Peer sent batched commitment_signed without a funding_txid".to_string(),
8975 ));
8976 },
8977 };
8978
8979 match messages.entry(funding_txid) {
8980 btree_map::Entry::Vacant(entry) => {
8981 entry.insert(msg);
8982 },
8983 btree_map::Entry::Occupied(_) => {
8984 return Err(ChannelError::close(format!(
8985 "Peer sent batched commitment_signed with duplicate funding_txid {}",
8986 funding_txid
8987 )));
8988 },
8989 }
8990 }
8991
8992 let mut commitment_txs = Vec::with_capacity(self.pending_funding().len() + 1);
8995 let mut htlc_data = None;
8996 for funding in core::iter::once(&self.funding).chain(self.pending_funding()) {
8997 let funding_txid =
8998 funding.get_funding_txid().expect("Funding txid must be known for pending scope");
8999 let msg = messages.get(&funding_txid).ok_or_else(|| {
9000 ChannelError::close(format!(
9001 "Peer did not send a commitment_signed for pending splice transaction: {}",
9002 funding_txid
9003 ))
9004 })?;
9005 let transaction_number = self.holder_commitment_point.next_transaction_number();
9006 let commitment_point = self.holder_commitment_point.next_point();
9007 let (commitment_tx, htlcs_included) = self.context.validate_commitment_signed(
9008 funding,
9009 transaction_number,
9010 commitment_point,
9011 msg,
9012 fee_estimator,
9013 logger,
9014 )?;
9015 commitment_txs.push(commitment_tx);
9016 if htlc_data.is_none() {
9017 let (nondust_htlc_sources, dust_htlcs) =
9018 Self::get_commitment_htlc_data(&htlcs_included);
9019 htlc_data = Some(CommitmentHTLCData {
9020 nondust_htlc_sources: nondust_htlc_sources.collect(),
9021 dust_htlcs: dust_htlcs.collect(),
9022 });
9023 }
9024 }
9025
9026 let update = ChannelMonitorUpdateStep::LatestHolderCommitment {
9027 commitment_txs,
9028 htlc_data: htlc_data.expect("At least one funding scope must have been considered"),
9029 claimed_htlcs: Vec::new(),
9030 };
9031 self.commitment_signed_update_monitor(update, logger)
9032 }
9033
9034 fn commitment_signed_check_state(&self) -> Result<(), ChannelError> {
9035 if self.context.channel_state.is_quiescent() {
9036 return Err(ChannelError::WarnAndDisconnect(
9037 "Got commitment_signed message while quiescent".to_owned(),
9038 ));
9039 }
9040 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
9041 return Err(ChannelError::close(
9042 "Got commitment signed message when channel was not in an operational state"
9043 .to_owned(),
9044 ));
9045 }
9046 if self.context.channel_state.is_peer_disconnected() {
9047 return Err(ChannelError::close(
9048 "Peer sent commitment_signed when we needed a channel_reestablish".to_owned(),
9049 ));
9050 }
9051 if self.context.channel_state.is_both_sides_shutdown()
9052 && self.context.last_sent_closing_fee.is_some()
9053 {
9054 return Err(ChannelError::close(
9055 "Peer sent commitment_signed after we'd started exchanging closing_signeds"
9056 .to_owned(),
9057 ));
9058 }
9059
9060 Ok(())
9061 }
9062
9063 fn commitment_signed_update_monitor<L: Logger>(
9064 &mut self, mut update: ChannelMonitorUpdateStep, logger: &L,
9065 ) -> Result<Option<ChannelMonitorUpdate>, ChannelError> {
9066 if self
9067 .holder_commitment_point
9068 .advance(&self.context.holder_signer, &self.context.secp_ctx, logger)
9069 .is_err()
9070 {
9071 debug_assert!(false, "We should be ready to advance our commitment point by the time we receive commitment_signed");
9081 return Err(ChannelError::close("Failed to advance our commitment point".to_owned()));
9082 }
9083
9084 let mut need_commitment = false;
9086 if let &mut Some((_, ref mut update_state)) = &mut self.context.pending_update_fee {
9087 if *update_state == FeeUpdateState::RemoteAnnounced {
9088 *update_state = FeeUpdateState::AwaitingRemoteRevokeToAnnounce;
9089 need_commitment = true;
9090 }
9091 }
9092
9093 for htlc in self.context.pending_inbound_htlcs.iter_mut() {
9094 if let &InboundHTLCState::RemoteAnnounced(ref htlc_resolution) = &htlc.state {
9095 log_trace!(logger, "Updating HTLC {} to AwaitingRemoteRevokeToAnnounce due to commitment_signed in channel {}.",
9096 &htlc.payment_hash, &self.context.channel_id);
9097 htlc.state =
9098 InboundHTLCState::AwaitingRemoteRevokeToAnnounce(htlc_resolution.clone());
9099 need_commitment = true;
9100 }
9101 }
9102 let mut claimed_htlcs = Vec::new();
9103 for htlc in self.context.pending_outbound_htlcs.iter_mut() {
9104 if let &mut OutboundHTLCState::RemoteRemoved(ref mut outcome) = &mut htlc.state {
9105 log_trace!(logger, "Updating HTLC {} to AwaitingRemoteRevokeToRemove due to commitment_signed in channel {}.",
9106 &htlc.payment_hash, &self.context.channel_id);
9107 let mut reason = OutboundHTLCOutcome::Success {
9109 preimage: PaymentPreimage([0u8; 32]),
9110 attribution_data: None,
9111 };
9112 mem::swap(outcome, &mut reason);
9113 if let OutboundHTLCOutcome::Success { preimage, .. } = reason {
9114 claimed_htlcs.push((SentHTLCId::from_source(&htlc.source), preimage));
9121 }
9122 htlc.state = OutboundHTLCState::AwaitingRemoteRevokeToRemove(reason);
9123 need_commitment = true;
9124 }
9125 }
9126
9127 match &mut update {
9128 ChannelMonitorUpdateStep::LatestHolderCommitment {
9129 claimed_htlcs: ref mut update_claimed_htlcs,
9130 ..
9131 } => {
9132 debug_assert!(update_claimed_htlcs.is_empty());
9133 *update_claimed_htlcs = claimed_htlcs.clone();
9134 },
9135 ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo {
9136 claimed_htlcs: ref mut update_claimed_htlcs,
9137 ..
9138 } => {
9139 debug_assert!(update_claimed_htlcs.is_empty());
9140 *update_claimed_htlcs = claimed_htlcs.clone();
9141 },
9142 _ => debug_assert!(false),
9143 }
9144
9145 self.context.latest_monitor_update_id += 1;
9146 let mut monitor_update = ChannelMonitorUpdate {
9147 update_id: self.context.latest_monitor_update_id,
9148 updates: vec![update],
9149 channel_id: Some(self.context.channel_id()),
9150 };
9151
9152 self.context.expecting_peer_commitment_signed = false;
9153 self.context.resend_order = RAACommitmentOrder::CommitmentFirst;
9156
9157 if self.context.channel_state.is_monitor_update_in_progress() {
9158 self.context.monitor_pending_revoke_and_ack = true;
9161 if need_commitment && !self.context.channel_state.is_awaiting_remote_revoke() {
9162 self.context.monitor_pending_commitment_signed = true;
9166 let mut additional_update = self.build_commitment_no_status_check(logger);
9167 self.context.latest_monitor_update_id = monitor_update.update_id;
9170 monitor_update.updates.append(&mut additional_update.updates);
9171 }
9172 log_debug!(logger, "Received valid commitment_signed from peer, updated HTLC state but awaiting a monitor update resolution to reply.",
9173 );
9174 return Ok(self.push_ret_blockable_mon_update(monitor_update));
9175 }
9176
9177 let need_commitment_signed =
9178 if need_commitment && !self.context.channel_state.is_awaiting_remote_revoke() {
9179 let mut additional_update = self.build_commitment_no_status_check(logger);
9183 self.context.latest_monitor_update_id = monitor_update.update_id;
9186 monitor_update.updates.append(&mut additional_update.updates);
9187 true
9188 } else {
9189 false
9190 };
9191
9192 log_debug!(logger, "Received valid commitment_signed from peer in channel {}, updating HTLC state and responding with{} a revoke_and_ack.",
9193 &self.context.channel_id(), if need_commitment_signed { " our own commitment_signed and" } else { "" });
9194 self.monitor_updating_paused(
9195 true,
9196 need_commitment_signed,
9197 false,
9198 Vec::new(),
9199 Vec::new(),
9200 Vec::new(),
9201 logger,
9202 );
9203 return Ok(self.push_ret_blockable_mon_update(monitor_update));
9204 }
9205
9206 pub fn maybe_free_holding_cell_htlcs<F: FeeEstimator, L: Logger>(
9210 &mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
9211 ) -> (Option<ChannelMonitorUpdate>, Vec<(HTLCSource, PaymentHash)>) {
9212 if matches!(self.context.channel_state, ChannelState::ChannelReady(_))
9213 && self.context.channel_state.can_generate_new_commitment()
9214 {
9215 self.free_holding_cell_htlcs(fee_estimator, logger)
9216 } else {
9217 (None, Vec::new())
9218 }
9219 }
9220
9221 fn free_holding_cell_htlcs<F: FeeEstimator, L: Logger>(
9224 &mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
9225 ) -> (Option<ChannelMonitorUpdate>, Vec<(HTLCSource, PaymentHash)>) {
9226 assert!(matches!(self.context.channel_state, ChannelState::ChannelReady(_)));
9227 assert!(!self.context.channel_state.is_monitor_update_in_progress());
9228 assert!(!self.context.channel_state.is_quiescent());
9229 if self.context.holding_cell_htlc_updates.len() != 0
9230 || self.context.holding_cell_update_fee.is_some()
9231 {
9232 log_trace!(
9233 logger,
9234 "Freeing holding cell with {} HTLC updates{}",
9235 self.context.holding_cell_htlc_updates.len(),
9236 if self.context.holding_cell_update_fee.is_some() {
9237 " and a fee update"
9238 } else {
9239 ""
9240 },
9241 );
9242
9243 let mut monitor_update = ChannelMonitorUpdate {
9244 update_id: self.context.latest_monitor_update_id + 1, updates: Vec::new(),
9246 channel_id: Some(self.context.channel_id()),
9247 };
9248
9249 let mut htlc_updates = Vec::new();
9250 mem::swap(&mut htlc_updates, &mut self.context.holding_cell_htlc_updates);
9251 let mut update_add_count = 0;
9252 let mut update_fulfill_count = 0;
9253 let mut update_fail_count = 0;
9254 let mut htlcs_to_fail = Vec::new();
9255 for htlc_update in htlc_updates.drain(..) {
9256 let fail_htlc_res = match &htlc_update {
9262 &HTLCUpdateAwaitingACK::AddHTLC {
9263 amount_msat,
9264 cltv_expiry,
9265 ref payment_hash,
9266 ref source,
9267 ref onion_routing_packet,
9268 skimmed_fee_msat,
9269 blinding_point,
9270 hold_htlc,
9271 accountable,
9272 } => {
9273 match self.send_htlc(
9274 amount_msat,
9275 *payment_hash,
9276 cltv_expiry,
9277 source.clone(),
9278 onion_routing_packet.clone(),
9279 false,
9280 skimmed_fee_msat,
9281 blinding_point,
9282 hold_htlc.is_some(),
9283 accountable,
9284 fee_estimator,
9285 logger,
9286 ) {
9287 Ok(can_add_htlc) => {
9288 debug_assert!(
9292 can_add_htlc,
9293 "Must generate new update if we're freeing the holding cell"
9294 );
9295 update_add_count += 1;
9296 },
9297 Err((_, msg)) => {
9298 log_info!(
9299 logger,
9300 "Failed to send HTLC with payment_hash {} due to {}",
9301 &payment_hash,
9302 msg
9303 );
9304 htlcs_to_fail.push((source.clone(), *payment_hash));
9310 },
9311 }
9312 None
9313 },
9314 &HTLCUpdateAwaitingACK::ClaimHTLC {
9315 ref payment_preimage,
9316 htlc_id,
9317 ref attribution_data,
9318 } => {
9319 let fulfill = self.get_update_fulfill_htlc(
9330 htlc_id,
9331 *payment_preimage,
9332 None,
9333 attribution_data.clone(),
9334 logger,
9335 );
9336 let mut additional_monitor_update =
9337 if let UpdateFulfillFetch::NewClaim { monitor_update, .. } = fulfill {
9338 monitor_update
9339 } else {
9340 unreachable!()
9341 };
9342 update_fulfill_count += 1;
9343 monitor_update.updates.append(&mut additional_monitor_update.updates);
9344 None
9345 },
9346 &HTLCUpdateAwaitingACK::FailHTLC { htlc_id, ref err_packet } => Some(
9347 self.fail_htlc(htlc_id, err_packet.clone(), false, logger)
9348 .map(|fail_msg_opt| fail_msg_opt.map(|_| ())),
9349 ),
9350 &HTLCUpdateAwaitingACK::FailMalformedHTLC {
9351 htlc_id,
9352 failure_code,
9353 sha256_of_onion,
9354 } => Some(
9355 self.fail_htlc(htlc_id, (sha256_of_onion, failure_code), false, logger)
9356 .map(|fail_msg_opt| fail_msg_opt.map(|_| ())),
9357 ),
9358 };
9359 if let Some(res) = fail_htlc_res {
9360 match res {
9361 Ok(fail_msg_opt) => {
9362 debug_assert!(fail_msg_opt.is_some());
9368 update_fail_count += 1;
9369 },
9370 Err(ChannelError::Ignore(_)) => {},
9371 Err(_) => {
9372 panic!("Got a non-IgnoreError action trying to fail holding cell HTLC");
9373 },
9374 }
9375 }
9376 }
9377 let update_fee =
9378 self.context.holding_cell_update_fee.take().and_then(|feerate| {
9379 self.send_update_fee(feerate, false, fee_estimator, logger)
9380 });
9381
9382 if update_add_count == 0
9383 && update_fulfill_count == 0
9384 && update_fail_count == 0
9385 && update_fee.is_none()
9386 {
9387 return (None, htlcs_to_fail);
9388 }
9389
9390 let mut additional_update = self.build_commitment_no_status_check(logger);
9391 self.context.latest_monitor_update_id = monitor_update.update_id;
9394 monitor_update.updates.append(&mut additional_update.updates);
9395
9396 log_debug!(logger, "Freeing holding cell resulted in {}{} HTLCs added, {} HTLCs fulfilled, and {} HTLCs failed.",
9397 if update_fee.is_some() { "a fee update, " } else { "" },
9398 update_add_count, update_fulfill_count, update_fail_count);
9399
9400 self.monitor_updating_paused(
9401 false,
9402 true,
9403 false,
9404 Vec::new(),
9405 Vec::new(),
9406 Vec::new(),
9407 logger,
9408 );
9409 (self.push_ret_blockable_mon_update(monitor_update), htlcs_to_fail)
9410 } else {
9411 (None, Vec::new())
9412 }
9413 }
9414
9415 pub fn revoke_and_ack<F: FeeEstimator, L: Logger>(
9429 &mut self, msg: &msgs::RevokeAndACK, fee_estimator: &LowerBoundedFeeEstimator<F>,
9430 logger: &L, hold_mon_update: bool,
9431 ) -> Result<
9432 (
9433 Vec<(HTLCSource, PaymentHash)>,
9434 Vec<(StaticInvoice, BlindedMessagePath)>,
9435 Option<ChannelMonitorUpdate>,
9436 ),
9437 ChannelError,
9438 > {
9439 if self.context.channel_state.is_quiescent() {
9440 return Err(ChannelError::WarnAndDisconnect(
9441 "Got revoke_and_ack message while quiescent".to_owned(),
9442 ));
9443 }
9444 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_)) {
9445 return Err(ChannelError::close(
9446 "Got revoke/ACK message when channel was not in an operational state".to_owned(),
9447 ));
9448 }
9449 if self.context.channel_state.is_peer_disconnected() {
9450 return Err(ChannelError::close(
9451 "Peer sent revoke_and_ack when we needed a channel_reestablish".to_owned(),
9452 ));
9453 }
9454 if self.context.channel_state.is_both_sides_shutdown()
9455 && self.context.last_sent_closing_fee.is_some()
9456 {
9457 return Err(ChannelError::close(
9458 "Peer sent revoke_and_ack after we'd started exchanging closing_signeds".to_owned(),
9459 ));
9460 }
9461
9462 let secret = secp_check!(
9463 SecretKey::from_slice(&msg.per_commitment_secret),
9464 "Peer provided an invalid per_commitment_secret".to_owned()
9465 );
9466
9467 if let Some(counterparty_current_commitment_point) =
9468 self.context.counterparty_current_commitment_point
9469 {
9470 if PublicKey::from_secret_key(&self.context.secp_ctx, &secret)
9471 != counterparty_current_commitment_point
9472 {
9473 return Err(ChannelError::close("Got a revoke commitment secret which didn't correspond to their current pubkey".to_owned()));
9474 }
9475 }
9476
9477 if !self.context.channel_state.is_awaiting_remote_revoke() {
9478 return Err(ChannelError::close("Received an unexpected revoke_and_ack".to_owned()));
9486 }
9487
9488 self.context
9489 .holder_signer
9490 .validate_counterparty_revocation(
9491 self.context.counterparty_next_commitment_transaction_number + 1,
9492 &secret,
9493 )
9494 .map_err(|_| {
9495 ChannelError::close("Failed to validate revocation from peer".to_owned())
9496 })?;
9497
9498 self.context
9499 .commitment_secrets
9500 .provide_secret(
9501 self.context.counterparty_next_commitment_transaction_number + 1,
9502 msg.per_commitment_secret,
9503 )
9504 .map_err(|_| {
9505 ChannelError::close("Previous secrets did not match new one".to_owned())
9506 })?;
9507 self.context.latest_monitor_update_id += 1;
9508 let mut monitor_update = ChannelMonitorUpdate {
9509 update_id: self.context.latest_monitor_update_id,
9510 updates: vec![ChannelMonitorUpdateStep::CommitmentSecret {
9511 idx: self.context.counterparty_next_commitment_transaction_number + 1,
9512 secret: msg.per_commitment_secret,
9513 }],
9514 channel_id: Some(self.context.channel_id()),
9515 };
9516
9517 self.context.channel_state.clear_awaiting_remote_revoke();
9522 self.mark_response_received();
9523 self.context.counterparty_current_commitment_point =
9524 self.context.counterparty_next_commitment_point;
9525 self.context.counterparty_next_commitment_point = Some(msg.next_per_commitment_point);
9526 self.context.counterparty_next_commitment_transaction_number -= 1;
9527
9528 if self.context.announcement_sigs_state == AnnouncementSigsState::Committed {
9529 self.context.announcement_sigs_state = AnnouncementSigsState::PeerReceived;
9530 }
9531
9532 log_trace!(logger, "Updating HTLCs on receipt of RAA...");
9533 let mut to_forward_infos = Vec::new();
9534 let mut pending_update_adds = Vec::new();
9535 let mut revoked_htlcs = Vec::new();
9536 let mut finalized_claimed_htlcs = Vec::new();
9537 let mut update_fail_htlcs = Vec::new();
9538 let mut update_fail_malformed_htlcs = Vec::new();
9539 let mut static_invoices = Vec::new();
9540 let mut require_commitment = false;
9541 let mut value_to_self_msat_diff: i64 = 0;
9542
9543 {
9544 let pending_inbound_htlcs: &mut Vec<_> = &mut self.context.pending_inbound_htlcs;
9546 let pending_outbound_htlcs: &mut Vec<_> = &mut self.context.pending_outbound_htlcs;
9547 let expecting_peer_commitment_signed =
9548 &mut self.context.expecting_peer_commitment_signed;
9549
9550 pending_inbound_htlcs.retain(|htlc| {
9552 if let &InboundHTLCState::LocalRemoved(ref reason) = &htlc.state {
9553 log_trace!(logger, " ...removing inbound LocalRemoved {}", &htlc.payment_hash);
9554 if let &InboundHTLCRemovalReason::Fulfill { .. } = reason {
9555 value_to_self_msat_diff += htlc.amount_msat as i64;
9556 }
9557 *expecting_peer_commitment_signed = true;
9558 false
9559 } else {
9560 true
9561 }
9562 });
9563 pending_outbound_htlcs.retain(|htlc| {
9564 if let &OutboundHTLCState::AwaitingRemovedRemoteRevoke(ref outcome) = &htlc.state {
9565 log_trace!(
9566 logger,
9567 " ...removing outbound AwaitingRemovedRemoteRevoke {}",
9568 &htlc.payment_hash
9569 );
9570 match outcome.clone() {
9572 OutboundHTLCOutcome::Failure(mut reason) => {
9573 hold_time_since(htlc.send_timestamp).map(|hold_time| {
9574 reason.set_hold_time(hold_time);
9575 });
9576 revoked_htlcs.push((htlc.source.clone(), htlc.payment_hash, reason));
9577 },
9578 OutboundHTLCOutcome::Success { attribution_data, .. } => {
9579 finalized_claimed_htlcs.push((htlc.source.clone(), attribution_data));
9583 value_to_self_msat_diff -= htlc.amount_msat as i64;
9585 },
9586 }
9587 false
9588 } else {
9589 true
9590 }
9591 });
9592 for htlc in pending_inbound_htlcs.iter_mut() {
9593 let swap = if let &InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) = &htlc.state
9594 {
9595 true
9596 } else if let &InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) = &htlc.state {
9597 true
9598 } else {
9599 false
9600 };
9601 if swap {
9602 let mut state =
9603 InboundHTLCState::Committed { update_add_htlc: InboundUpdateAdd::Legacy };
9604 mem::swap(&mut state, &mut htlc.state);
9605
9606 if let InboundHTLCState::AwaitingRemoteRevokeToAnnounce(resolution) = state {
9607 log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to AwaitingAnnouncedRemoteRevoke", &htlc.payment_hash);
9608 htlc.state = InboundHTLCState::AwaitingAnnouncedRemoteRevoke(resolution);
9609 require_commitment = true;
9610 } else if let InboundHTLCState::AwaitingAnnouncedRemoteRevoke(resolution) =
9611 state
9612 {
9613 match resolution {
9614 InboundHTLCResolution::Resolved { pending_htlc_status } => {
9615 match pending_htlc_status {
9616 PendingHTLCStatus::Fail(fail_msg) => {
9617 log_trace!(logger, " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to LocalRemoved due to PendingHTLCStatus indicating failure", &htlc.payment_hash);
9618 require_commitment = true;
9619 match fail_msg {
9620 HTLCFailureMsg::Relay(msg) => {
9621 htlc.state = InboundHTLCState::LocalRemoved(
9622 InboundHTLCRemovalReason::FailRelay(
9623 msg.clone().into(),
9624 ),
9625 );
9626 update_fail_htlcs.push(msg)
9627 },
9628 HTLCFailureMsg::Malformed(msg) => {
9629 htlc.state = InboundHTLCState::LocalRemoved(
9630 InboundHTLCRemovalReason::FailMalformed {
9631 sha256_of_onion: msg.sha256_of_onion,
9632 failure_code: msg.failure_code,
9633 },
9634 );
9635 update_fail_malformed_htlcs.push(msg)
9636 },
9637 }
9638 },
9639 PendingHTLCStatus::Forward(forward_info) => {
9640 log_trace!(logger, " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed, attempting to forward", &htlc.payment_hash);
9641 to_forward_infos.push((forward_info, htlc.htlc_id));
9642 htlc.state = InboundHTLCState::Committed {
9643 update_add_htlc: InboundUpdateAdd::Legacy,
9646 };
9647 },
9648 }
9649 },
9650 InboundHTLCResolution::Pending { update_add_htlc } => {
9651 log_trace!(logger, " ...promoting inbound AwaitingAnnouncedRemoteRevoke {} to Committed", &htlc.payment_hash);
9652 pending_update_adds.push(update_add_htlc.clone());
9653 htlc.state = InboundHTLCState::Committed {
9654 update_add_htlc: InboundUpdateAdd::WithOnion {
9655 update_add_htlc,
9656 },
9657 };
9658 },
9659 }
9660 }
9661 }
9662 }
9663 for htlc in pending_outbound_htlcs.iter_mut() {
9664 for (htlc_id, blinded_path) in &msg.release_htlc_message_paths {
9665 if htlc.htlc_id != *htlc_id {
9666 continue;
9667 }
9668 let static_invoice = match htlc.source.static_invoice() {
9669 Some(inv) if htlc.hold_htlc.is_some() => inv,
9670 _ => {
9671 log_trace!(logger, "Counterparty included release_htlc_message_path for non-async payment HTLC {}", htlc_id);
9677 continue;
9678 },
9679 };
9680 static_invoices.push((static_invoice, blinded_path.clone()));
9681 }
9682 if let OutboundHTLCState::LocalAnnounced(_) = htlc.state {
9683 log_trace!(
9684 logger,
9685 " ...promoting outbound LocalAnnounced {} to Committed",
9686 &htlc.payment_hash
9687 );
9688 htlc.state = OutboundHTLCState::Committed;
9689 *expecting_peer_commitment_signed = true;
9690 }
9691 if let &mut OutboundHTLCState::AwaitingRemoteRevokeToRemove(ref mut outcome) =
9692 &mut htlc.state
9693 {
9694 log_trace!(logger, " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", &htlc.payment_hash);
9695 let mut reason = OutboundHTLCOutcome::Success {
9697 preimage: PaymentPreimage([0u8; 32]),
9698 attribution_data: None,
9699 };
9700 mem::swap(outcome, &mut reason);
9701 htlc.state = OutboundHTLCState::AwaitingRemovedRemoteRevoke(reason);
9702 require_commitment = true;
9703 }
9704 }
9705 }
9706
9707 for funding in self.funding_and_pending_funding_iter_mut() {
9708 funding.value_to_self_msat =
9709 (funding.value_to_self_msat as i64 + value_to_self_msat_diff) as u64;
9710 }
9711
9712 if let Some((feerate, update_state)) = self.context.pending_update_fee {
9713 match update_state {
9714 FeeUpdateState::Outbound => {
9715 debug_assert!(self.funding.is_outbound());
9716 log_trace!(
9717 logger,
9718 " ...promoting outbound fee update {} to Committed",
9719 feerate
9720 );
9721 self.context.feerate_per_kw = feerate;
9722 self.context.pending_update_fee = None;
9723 self.context.expecting_peer_commitment_signed = true;
9724 },
9725 FeeUpdateState::RemoteAnnounced => {
9726 debug_assert!(!self.funding.is_outbound());
9727 },
9728 FeeUpdateState::AwaitingRemoteRevokeToAnnounce => {
9729 debug_assert!(!self.funding.is_outbound());
9730 log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce fee update {} to Committed", feerate);
9731 require_commitment = true;
9732 self.context.feerate_per_kw = feerate;
9733 self.context.pending_update_fee = None;
9734 },
9735 }
9736 }
9737
9738 let release_monitor = self.context.blocked_monitor_updates.is_empty() && !hold_mon_update;
9739 let release_state_str = if hold_mon_update {
9740 "Holding"
9741 } else if release_monitor {
9742 "Releasing"
9743 } else {
9744 "Blocked"
9745 };
9746 macro_rules! return_with_htlcs_to_fail {
9747 ($htlcs_to_fail: expr) => {
9748 if !release_monitor {
9749 self.context
9750 .blocked_monitor_updates
9751 .push(PendingChannelMonitorUpdate { update: monitor_update });
9752 return Ok(($htlcs_to_fail, static_invoices, None));
9753 } else {
9754 return Ok(($htlcs_to_fail, static_invoices, Some(monitor_update)));
9755 }
9756 };
9757 }
9758
9759 self.context.monitor_pending_update_adds.append(&mut pending_update_adds);
9760
9761 match self.maybe_free_holding_cell_htlcs(fee_estimator, logger) {
9762 (Some(mut additional_update), htlcs_to_fail) => {
9763 self.context.latest_monitor_update_id = monitor_update.update_id;
9766 monitor_update.updates.append(&mut additional_update.updates);
9767
9768 log_debug!(logger, "Received a valid revoke_and_ack with holding cell HTLCs freed. {} monitor update.",
9769 release_state_str);
9770
9771 self.monitor_updating_paused(
9772 false,
9773 true,
9774 false,
9775 to_forward_infos,
9776 revoked_htlcs,
9777 finalized_claimed_htlcs,
9778 logger,
9779 );
9780 return_with_htlcs_to_fail!(htlcs_to_fail);
9781 },
9782 (None, htlcs_to_fail) => {
9783 if require_commitment {
9784 let mut additional_update = self.build_commitment_no_status_check(logger);
9790
9791 self.context.latest_monitor_update_id = monitor_update.update_id;
9794 monitor_update.updates.append(&mut additional_update.updates);
9795
9796 log_debug!(
9797 logger,
9798 "Received a valid revoke_and_ack. {} monitor update.",
9799 release_state_str
9800 );
9801 if self.context.channel_state.can_generate_new_commitment() {
9802 log_debug!(logger, "Responding with a commitment update with {} HTLCs failed for channel {}",
9803 update_fail_htlcs.len() + update_fail_malformed_htlcs.len(),
9804 &self.context.channel_id);
9805 } else {
9806 let reason = if self.context.channel_state.is_local_stfu_sent() {
9807 "exits quiescence"
9808 } else if self.context.channel_state.is_monitor_update_in_progress() {
9809 "completes pending monitor update"
9810 } else {
9811 "can continue progress"
9812 };
9813 log_debug!(logger, "Holding back commitment update until {}", reason);
9814 }
9815
9816 self.monitor_updating_paused(
9817 false,
9818 true,
9819 false,
9820 to_forward_infos,
9821 revoked_htlcs,
9822 finalized_claimed_htlcs,
9823 logger,
9824 );
9825 return_with_htlcs_to_fail!(htlcs_to_fail);
9826 } else {
9827 log_debug!(logger, "Received a valid revoke_and_ack with no reply necessary. {} monitor update {}.",
9828 release_state_str, monitor_update.update_id);
9829
9830 self.monitor_updating_paused(
9831 false,
9832 false,
9833 false,
9834 to_forward_infos,
9835 revoked_htlcs,
9836 finalized_claimed_htlcs,
9837 logger,
9838 );
9839 return_with_htlcs_to_fail!(htlcs_to_fail);
9840 }
9841 },
9842 }
9843 }
9844
9845 fn on_tx_signatures_exchange<'a, L: Logger>(
9846 &mut self, funding_tx_signed: &mut FundingTxSigned, funding_tx: Transaction,
9847 best_block_height: u32, logger: &WithChannelContext<'a, L>,
9848 ) {
9849 debug_assert!(
9850 !self.is_awaiting_monitor_update() || !self.context.monitor_pending_tx_signatures
9851 );
9852 debug_assert!(!self.context.is_waiting_on_peer_pending_channel_update());
9853
9854 if self.pending_splice.is_some() {
9855 self.exit_quiescence();
9856
9857 let pending_splice = self.pending_splice.as_mut().expect("We just checked it above");
9858 if let Some(FundingNegotiation::AwaitingSignatures {
9859 mut funding,
9860 funding_feerate_sat_per_1000_weight,
9861 ..
9862 }) = pending_splice.funding_negotiation.take()
9863 {
9864 funding.funding_transaction = Some(funding_tx.clone());
9865 pending_splice.last_funding_feerate_sat_per_1000_weight =
9866 Some(funding_feerate_sat_per_1000_weight);
9867
9868 let funding_txo =
9869 funding.get_funding_txo().expect("funding outpoint should be set");
9870 let channel_type = funding.get_channel_type().clone();
9871 let funding_redeem_script = funding.get_funding_redeemscript();
9872 let has_local_contribution = self
9873 .context
9874 .interactive_tx_signing_session
9875 .as_ref()
9876 .map(|signing_session| signing_session.has_local_contribution())
9877 .unwrap_or(false);
9878
9879 let contribution = pending_splice.negotiation_contribution.take();
9880 pending_splice
9881 .negotiated_candidates
9882 .push(NegotiatedCandidate { funding, contribution });
9883 debug_assert!(
9884 pending_splice.contributions_form_suffix(),
9885 "a round following one we contributed to must carry our contribution",
9886 );
9887
9888 let splice_negotiated = SpliceFundingNegotiated {
9889 funding_txo: funding_txo.into_bitcoin_outpoint(),
9890 has_local_contribution,
9891 channel_type,
9892 funding_redeem_script,
9893 };
9894
9895 let splice_locked = pending_splice.check_get_splice_locked(
9896 &self.context,
9897 pending_splice.negotiated_candidates.len() - 1,
9898 best_block_height,
9899 );
9900 if let Some(splice_txid) =
9901 splice_locked.as_ref().map(|splice_locked| splice_locked.splice_txid)
9902 {
9903 log_info!(
9904 logger,
9905 "Sending 0conf splice_locked txid {} to our peer",
9906 splice_txid,
9907 );
9908 }
9909
9910 let candidates = pending_splice
9911 .negotiated_candidates
9912 .iter()
9913 .map(|candidate| {
9914 let txid = candidate
9915 .funding
9916 .get_funding_txid()
9917 .expect("negotiated candidates should have a funding txid");
9918 FundingCandidate {
9919 txid,
9920 channels: vec![ChannelFunding {
9921 counterparty_node_id: self.context.counterparty_node_id,
9922 channel_id: self.context.channel_id,
9923 purpose: FundingPurpose::Splice,
9924 contribution: candidate.contribution.clone(),
9925 }],
9926 }
9927 })
9928 .collect();
9929 let tx_type = TransactionType::InteractiveFunding { candidates };
9930 funding_tx_signed.funding_tx = Some((funding_tx, tx_type));
9931 funding_tx_signed.splice_negotiated = Some(splice_negotiated);
9932 funding_tx_signed.splice_locked = splice_locked;
9933 } else {
9934 debug_assert!(false);
9935 }
9936 } else {
9937 self.funding.funding_transaction = Some(funding_tx.clone());
9938 self.context.channel_state =
9939 ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new());
9940 let tx_type = TransactionType::Funding {
9941 channels: vec![(self.context.counterparty_node_id, self.context.channel_id)],
9942 };
9943 funding_tx_signed.funding_tx = Some((funding_tx, tx_type));
9944 }
9945 }
9946
9947 pub fn tx_signatures<L: Logger>(
9948 &mut self, msg: &msgs::TxSignatures, best_block_height: u32, logger: &L,
9949 ) -> Result<FundingTxSigned, ChannelError> {
9950 let signing_session = if let Some(signing_session) =
9951 self.context.interactive_tx_signing_session.as_mut()
9952 {
9953 if signing_session.has_received_tx_signatures() {
9954 return Err(ChannelError::Ignore("Ignoring duplicate tx_signatures".to_owned()));
9955 }
9956 if !signing_session.has_received_commitment_signed() {
9957 return Err(ChannelError::close(
9958 "Received tx_signatures before initial commitment_signed".to_owned(),
9959 ));
9960 }
9961
9962 if let Some(pending_splice) = self.pending_splice.as_ref() {
9963 debug_assert!(pending_splice
9964 .funding_negotiation
9965 .as_ref()
9966 .map(|funding_negotiation| matches!(
9967 funding_negotiation,
9968 FundingNegotiation::AwaitingSignatures { .. }
9969 ))
9970 .unwrap_or(false));
9971 }
9972
9973 signing_session
9974 } else {
9975 return Err(ChannelError::Ignore("Ignoring unexpected tx_signatures".to_owned()));
9976 };
9977
9978 if msg.tx_hash != signing_session.unsigned_tx().compute_txid() {
9979 let msg = "The txid for the transaction does not match";
9980 let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
9981 return Err(ChannelError::Close((msg.to_owned(), reason)));
9982 }
9983
9984 for witness in &msg.witnesses {
9985 if witness.is_empty() {
9986 let msg = "Unexpected empty witness in tx_signatures received";
9987 let reason = ClosureReason::ProcessingError { err: msg.to_owned() };
9988 return Err(ChannelError::Close((msg.to_owned(), reason)));
9989 }
9990 }
9991
9992 let awaiting_holder_shared_input_signature =
9993 signing_session.awaiting_holder_shared_input_signature();
9994 let (holder_tx_signatures, funding_tx) =
9995 signing_session.received_tx_signatures(msg).map_err(|msg| ChannelError::Warn(msg))?;
9996
9997 let logger = WithChannelContext::from(logger, &self.context, None);
9998 log_info!(
9999 logger,
10000 "Received tx_signatures for interactive funding transaction {}",
10001 msg.tx_hash
10002 );
10003
10004 let mut funding_tx_signed = FundingTxSigned {
10005 commitment_signed: None,
10006 counterparty_initial_commitment_signed_result: None,
10007 tx_signatures: None,
10008 funding_tx: None,
10009 splice_negotiated: None,
10010 splice_locked: None,
10011 };
10012 if self.is_awaiting_monitor_update() && self.context.monitor_pending_tx_signatures {
10013 debug_assert!(holder_tx_signatures.is_some());
10017 log_debug!(
10018 logger,
10019 "Waiting for async monitor update to complete prior to releasing our tx_signatures"
10020 );
10021 return Ok(funding_tx_signed);
10022 }
10023
10024 funding_tx_signed.tx_signatures = holder_tx_signatures;
10025 if let Some(funding_tx) = funding_tx {
10026 self.on_tx_signatures_exchange(
10027 &mut funding_tx_signed,
10028 funding_tx,
10029 best_block_height,
10030 &logger,
10031 );
10032 } else if awaiting_holder_shared_input_signature {
10033 log_debug!(
10034 logger,
10035 "Waiting for funding transaction shared input signature before finalizing negotiation"
10036 );
10037 } else {
10038 debug_assert!(
10039 false,
10040 "Signed funding transaction should be available upon tx_signatures exchange"
10041 );
10042 }
10043 Ok(funding_tx_signed)
10044 }
10045
10046 pub fn queue_update_fee<F: FeeEstimator, L: Logger>(
10050 &mut self, feerate_per_kw: u32, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
10051 ) {
10052 let msg_opt = self.send_update_fee(feerate_per_kw, true, fee_estimator, logger);
10053 assert!(msg_opt.is_none(), "We forced holding cell?");
10054 }
10055
10056 #[rustfmt::skip]
10064 fn send_update_fee<F: FeeEstimator, L: Logger>(
10065 &mut self, feerate_per_kw: u32, mut force_holding_cell: bool,
10066 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L
10067 ) -> Option<msgs::UpdateFee> {
10068 if !self.funding.is_outbound() {
10069 panic!("Cannot send fee from inbound channel");
10070 }
10071 if !self.context.is_usable() {
10072 panic!("Cannot update fee until channel is fully established and we haven't started shutting down");
10073 }
10074 if !self.context.is_live() {
10075 panic!("Cannot update fee while peer is disconnected/we're awaiting a monitor update (ChannelManager should have caught this)");
10076 }
10077
10078 debug_assert!(!self.funding.get_channel_type().supports_anchor_zero_fee_commitments());
10081
10082 let can_send_update_fee = core::iter::once(&self.funding)
10083 .chain(self.pending_funding())
10084 .all(|funding| self.context.can_send_update_fee(funding, feerate_per_kw, fee_estimator, logger));
10085 if !can_send_update_fee {
10086 return None;
10087 }
10088
10089 if !self.context.channel_state.can_generate_new_commitment() {
10093 force_holding_cell = true;
10094 }
10095
10096 if force_holding_cell {
10097 self.context.holding_cell_update_fee = Some(feerate_per_kw);
10098 return None;
10099 }
10100
10101 debug_assert!(self.context.pending_update_fee.is_none());
10102 self.context.pending_update_fee = Some((feerate_per_kw, FeeUpdateState::Outbound));
10103
10104 Some(msgs::UpdateFee {
10105 channel_id: self.context.channel_id,
10106 feerate_per_kw,
10107 })
10108 }
10109
10110 #[rustfmt::skip]
10117 fn remove_uncommitted_htlcs_and_mark_paused<L: Logger>(&mut self, logger: &L) -> Result<(), ()> {
10118 assert!(!matches!(self.context.channel_state, ChannelState::ShutdownComplete));
10119 if !self.context.can_resume_on_reconnect() {
10120 return Err(())
10121 }
10122
10123 self.context.sent_message_awaiting_response = None;
10126
10127 if self.context.channel_state.is_peer_disconnected() {
10128 return Ok(());
10131 }
10132
10133 if self.context.announcement_sigs_state == AnnouncementSigsState::MessageSent || self.context.announcement_sigs_state == AnnouncementSigsState::Committed {
10134 self.context.announcement_sigs_state = AnnouncementSigsState::NotSent;
10135 }
10136
10137 self.context.last_sent_closing_fee = None;
10140 self.context.pending_counterparty_closing_signed = None;
10141 self.context.closing_fee_limits = None;
10142
10143 let mut inbound_drop_count = 0;
10144 self.context.pending_inbound_htlcs.retain(|htlc| {
10145 match htlc.state {
10146 InboundHTLCState::RemoteAnnounced(_) => {
10147 inbound_drop_count += 1;
10151 false
10152 },
10153 InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_)|InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => {
10154 true
10158 },
10159 InboundHTLCState::Committed { .. } => true,
10160 InboundHTLCState::LocalRemoved(_) => {
10161 true
10166 },
10167 }
10168 });
10169 self.context.next_counterparty_htlc_id -= inbound_drop_count;
10170
10171 if let Some((_, update_state)) = self.context.pending_update_fee {
10172 if update_state == FeeUpdateState::RemoteAnnounced {
10173 debug_assert!(!self.funding.is_outbound());
10174 self.context.pending_update_fee = None;
10175 }
10176 }
10177
10178 for htlc in self.context.pending_outbound_htlcs.iter_mut() {
10179 if let OutboundHTLCState::RemoteRemoved(_) = htlc.state {
10180 htlc.state = OutboundHTLCState::Committed;
10184 }
10185 }
10186
10187 self.context.channel_state.set_peer_disconnected();
10188 log_trace!(logger, "Peer disconnection resulted in {} remote-announced HTLC drops on channel {}", inbound_drop_count, &self.context.channel_id());
10189 Ok(())
10190 }
10191
10192 fn monitor_updating_paused<L: Logger>(
10204 &mut self, resend_raa: bool, resend_commitment: bool, resend_channel_ready: bool,
10205 pending_forwards: Vec<(PendingHTLCInfo, u64)>,
10206 pending_fails: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
10207 pending_finalized_claimed_htlcs: Vec<(HTLCSource, Option<AttributionData>)>, logger: &L,
10208 ) {
10209 log_trace!(logger, "Pausing channel monitor updates");
10210
10211 self.context.monitor_pending_revoke_and_ack |= resend_raa;
10212 self.context.monitor_pending_commitment_signed |= resend_commitment;
10213 self.context.monitor_pending_channel_ready |= resend_channel_ready;
10214 self.context.monitor_pending_forwards.extend(pending_forwards);
10215 self.context.monitor_pending_failures.extend(pending_fails);
10216 self.context.monitor_pending_finalized_fulfills.extend(pending_finalized_claimed_htlcs);
10217 self.context.channel_state.set_monitor_update_in_progress();
10218 }
10219
10220 #[rustfmt::skip]
10224 pub fn monitor_updating_restored<'a, L: Logger, NS: NodeSigner, CBP>(
10225 &mut self, logger: &WithChannelContext<'a, L>, node_signer: &NS, chain_hash: ChainHash,
10226 user_config: &UserConfig, best_block_height: u32, path_for_release_htlc: CBP
10227 ) -> MonitorRestoreUpdates
10228 where
10229 CBP: Fn(u64) -> BlindedMessagePath
10230 {
10231 assert!(self.context.channel_state.is_monitor_update_in_progress());
10232 self.context.channel_state.clear_monitor_update_in_progress();
10233 assert_eq!(self.blocked_monitor_updates_pending(), 0);
10234 let mut requires_channel_manager_persistence = false;
10237
10238 let mut tx_signatures = self
10241 .context
10242 .monitor_pending_tx_signatures
10243 .then(|| ())
10244 .and_then(|_| self.context.interactive_tx_signing_session.as_ref())
10245 .and_then(|signing_session| signing_session.holder_tx_signatures());
10246 self.context.monitor_pending_tx_signatures = false;
10247
10248 let mut funding_tx_signed = None;
10249 if tx_signatures.is_some() {
10250 let signing_session = self.context.interactive_tx_signing_session.as_ref()
10251 .expect("We have a tx_signatures message so we must have a valid signing session");
10252 if self.context.signer_pending_funding {
10253 tx_signatures.take();
10254 } else {
10255 debug_assert!(tx_signatures.is_some());
10256 funding_tx_signed = Some(FundingTxSigned {
10257 commitment_signed: None,
10258 counterparty_initial_commitment_signed_result: None,
10259 tx_signatures,
10260 funding_tx: None,
10261 splice_negotiated: None,
10262 splice_locked: None,
10263 });
10264 requires_channel_manager_persistence = true;
10265 if let Some(funding_tx) = signing_session.signed_tx() {
10266 self.on_tx_signatures_exchange(
10267 funding_tx_signed.as_mut().unwrap(),
10268 funding_tx,
10269 best_block_height,
10270 logger,
10271 );
10272 } else if signing_session.has_received_tx_signatures() {
10273 debug_assert!(false, "Signed funding transaction should be available upon tx_signatures exchange");
10274 }
10275 }
10276 }
10277
10278 let mut funding_broadcastable = None;
10282 if let Some(funding_transaction) = &self.funding.funding_transaction {
10283 if (self.funding.is_outbound() || self.is_v2_established()) &&
10284 (matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(flags) if !flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH)) ||
10285 matches!(self.context.channel_state, ChannelState::ChannelReady(_)))
10286 {
10287 if self.funding.get_funding_tx_confirmation_height().is_none() {
10289 funding_broadcastable = Some(funding_transaction.clone());
10290 requires_channel_manager_persistence = true;
10291 }
10292 }
10293 }
10294
10295 let channel_ready_order = if self.context.interactive_tx_signing_session.is_some() {
10299 ChannelReadyOrder::SignaturesFirst
10300 } else if matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(_)) {
10301 ChannelReadyOrder::SignaturesFirst
10302 } else {
10303 ChannelReadyOrder::ChannelReadyFirst
10304 };
10305
10306 let channel_ready = if self.context.monitor_pending_channel_ready {
10313 assert!(!self.funding.is_outbound() || self.context.minimum_depth == Some(0),
10314 "Funding transaction broadcast by the local client before it should have - LDK didn't do it!");
10315 self.context.monitor_pending_channel_ready = false;
10316 let channel_ready = self.get_channel_ready(logger);
10317 requires_channel_manager_persistence |= channel_ready.is_some();
10318 channel_ready
10319 } else { None };
10320
10321 let announcement_sigs = self.get_announcement_sigs(node_signer, chain_hash, user_config, best_block_height, logger);
10322 requires_channel_manager_persistence |= announcement_sigs.is_some();
10323
10324 let mut accepted_htlcs = Vec::new();
10325 mem::swap(&mut accepted_htlcs, &mut self.context.monitor_pending_forwards);
10326 requires_channel_manager_persistence |= !accepted_htlcs.is_empty();
10327 let mut failed_htlcs = Vec::new();
10328 mem::swap(&mut failed_htlcs, &mut self.context.monitor_pending_failures);
10329 requires_channel_manager_persistence |= !failed_htlcs.is_empty();
10330 let mut finalized_claimed_htlcs = Vec::new();
10331 mem::swap(&mut finalized_claimed_htlcs, &mut self.context.monitor_pending_finalized_fulfills);
10332 requires_channel_manager_persistence |= !finalized_claimed_htlcs.is_empty();
10333 let mut pending_update_adds = Vec::new();
10334 mem::swap(&mut pending_update_adds, &mut self.context.monitor_pending_update_adds);
10335 requires_channel_manager_persistence |= !pending_update_adds.is_empty();
10336 let committed_outbound_htlc_sources: Vec<(HTLCPreviousHopData, u64)> = self.context.pending_outbound_htlcs.iter().filter_map(|htlc| {
10337 if let &OutboundHTLCState::LocalAnnounced(_) = &htlc.state {
10338 if let HTLCSource::PreviousHopData(prev_hop_data) = &htlc.source {
10339 return Some((prev_hop_data.clone(), htlc.amount_msat))
10340 }
10341 }
10342 None
10343 }).collect();
10344 requires_channel_manager_persistence |= !committed_outbound_htlc_sources.is_empty();
10345
10346 if self.context.channel_state.is_peer_disconnected() {
10347 self.context.monitor_pending_revoke_and_ack = false;
10348 self.context.monitor_pending_commitment_signed = false;
10349 return MonitorRestoreUpdates {
10350 raa: None, commitment_update: None, commitment_order: RAACommitmentOrder::RevokeAndACKFirst,
10351 accepted_htlcs, failed_htlcs, finalized_claimed_htlcs, pending_update_adds,
10352 funding_broadcastable, channel_ready, channel_ready_order, announcement_sigs,
10353 funding_tx_signed, committed_outbound_htlc_sources,
10354 requires_channel_manager_persistence,
10355 };
10356 }
10357
10358 let mut raa = if self.context.monitor_pending_revoke_and_ack {
10359 self.get_last_revoke_and_ack(path_for_release_htlc, logger)
10360 } else { None };
10361 let mut commitment_update = if self.context.monitor_pending_commitment_signed {
10362 self.get_last_commitment_update_for_send(logger).ok()
10363 } else { None };
10364 if self.context.resend_order == RAACommitmentOrder::CommitmentFirst
10365 && self.context.signer_pending_commitment_update && raa.is_some() {
10366 self.context.signer_pending_revoke_and_ack = true;
10367 raa = None;
10368 }
10369 if self.context.resend_order == RAACommitmentOrder::RevokeAndACKFirst
10370 && self.context.signer_pending_revoke_and_ack && commitment_update.is_some() {
10371 self.context.signer_pending_commitment_update = true;
10372 commitment_update = None;
10373 }
10374
10375 self.context.monitor_pending_revoke_and_ack = false;
10376 self.context.monitor_pending_commitment_signed = false;
10377 let commitment_order = self.context.resend_order.clone();
10378 log_debug!(logger, "Restored monitor updating in channel {} resulting in {}{} commitment update and {} RAA, with {} first",
10379 &self.context.channel_id(), if funding_broadcastable.is_some() { "a funding broadcastable, " } else { "" },
10380 if commitment_update.is_some() { "a" } else { "no" }, if raa.is_some() { "an" } else { "no" },
10381 match commitment_order { RAACommitmentOrder::CommitmentFirst => "commitment", RAACommitmentOrder::RevokeAndACKFirst => "RAA"});
10382 MonitorRestoreUpdates {
10383 raa, commitment_update, commitment_order, accepted_htlcs, failed_htlcs, finalized_claimed_htlcs,
10384 pending_update_adds, funding_broadcastable, channel_ready, channel_ready_order,
10385 announcement_sigs, funding_tx_signed, committed_outbound_htlc_sources,
10386 requires_channel_manager_persistence,
10387 }
10388 }
10389
10390 pub fn check_for_stale_feerate<L: Logger>(
10391 &mut self, logger: &L, min_feerate: u32,
10392 ) -> Result<(), ClosureReason> {
10393 if self.funding.is_outbound() {
10394 return Ok(());
10397 }
10398
10399 if self.funding.get_channel_type().supports_anchor_zero_fee_commitments() {
10400 debug_assert_eq!(self.context.feerate_per_kw, 0);
10401 return Ok(());
10402 }
10403
10404 if self.context.feerate_per_kw < min_feerate {
10405 log_info!(logger,
10406 "Closing channel as feerate of {} is below required {} (the minimum required rate over the past day)",
10407 self.context.feerate_per_kw, min_feerate
10408 );
10409 Err(ClosureReason::PeerFeerateTooLow {
10410 peer_feerate_sat_per_kw: self.context.feerate_per_kw,
10411 required_feerate_sat_per_kw: min_feerate,
10412 })
10413 } else {
10414 Ok(())
10415 }
10416 }
10417
10418 #[rustfmt::skip]
10419 pub fn update_fee<F: FeeEstimator, L: Logger>(&mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, msg: &msgs::UpdateFee, logger: &L) -> Result<(), ChannelError> {
10420 if self.funding.is_outbound() {
10421 return Err(ChannelError::close("Non-funding remote tried to update channel fee".to_owned()));
10422 }
10423 if self.context.channel_state.is_peer_disconnected() {
10424 return Err(ChannelError::close("Peer sent update_fee when we needed a channel_reestablish".to_owned()));
10425 }
10426 if self.context.channel_state.is_remote_stfu_sent() || self.context.channel_state.is_quiescent() {
10427 return Err(ChannelError::WarnAndDisconnect("Got fee update message while quiescent".to_owned()));
10428 }
10429 if self.funding.get_channel_type().supports_anchor_zero_fee_commitments() {
10430 return Err(ChannelError::WarnAndDisconnect("Update fee message received for zero fee commitment channel".to_owned()));
10431 }
10432
10433 core::iter::once(&self.funding)
10434 .chain(self.pending_funding())
10435 .try_for_each(|funding| FundedChannel::<SP>::check_remote_fee(funding.get_channel_type(), fee_estimator, msg.feerate_per_kw, Some(self.context.feerate_per_kw), logger))?;
10436
10437 self.context.pending_update_fee = Some((msg.feerate_per_kw, FeeUpdateState::RemoteAnnounced));
10438 self.context.update_time_counter += 1;
10439 Ok(())
10440 }
10441
10442 #[rustfmt::skip]
10445 pub fn signer_maybe_unblocked<L: Logger, CBP>(
10446 &mut self, best_block_height: u32, logger: &L, path_for_release_htlc: CBP
10447 ) -> Result<SignerResumeUpdates, ChannelError> where CBP: Fn(u64) -> BlindedMessagePath {
10448 if let Some((commitment_number, commitment_secret)) = self.context.signer_pending_stale_state_verification.clone() {
10449 if let Ok(expected_point) = self
10450 .context
10451 .holder_signer
10452 .get_per_commitment_point(commitment_number, &self.context.secp_ctx)
10453 {
10454 self.context.signer_pending_stale_state_verification.take();
10455 if expected_point != PublicKey::from_secret_key(&self.context.secp_ctx, &commitment_secret) {
10456 return Err(ChannelError::close("Peer sent a channel_reestablish indicating we're stale with an invalid commitment secret".to_owned()));
10457 }
10458 Self::panic_on_stale_state(logger);
10459 }
10460 }
10461 if !self.holder_commitment_point.can_advance() {
10462 log_trace!(logger, "Attempting to update holder per-commitment point...");
10463 self.holder_commitment_point.try_resolve_pending(&self.context.holder_signer, &self.context.secp_ctx, logger);
10464 }
10465
10466 let funding_signed = if self.context.signer_pending_funding
10467 && !self.is_v2_established()
10468 && !self.funding.is_outbound()
10469 && self.pending_splice.is_none()
10470 {
10471 let commitment_data = self.context.build_commitment_transaction(&self.funding,
10472 self.context.counterparty_next_commitment_transaction_number + 1,
10476 &self.context.counterparty_next_commitment_point.unwrap(), false, false, logger);
10477 let counterparty_initial_commitment_tx = commitment_data.tx;
10478 self.context.get_funding_signed_msg(&self.funding.channel_transaction_parameters, logger, counterparty_initial_commitment_tx)
10479 } else { None };
10480
10481 let funding_commit_sig = if self.context.signer_pending_funding
10482 && (self.is_v2_established() || self.pending_splice.is_some())
10483 {
10484 log_debug!(logger, "Attempting to generate pending initial commitment_signed...");
10485 let funding = self
10486 .pending_splice
10487 .as_ref()
10488 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
10489 .and_then(|funding_negotiation| {
10490 debug_assert!(matches!(
10491 funding_negotiation,
10492 FundingNegotiation::AwaitingSignatures { .. }
10493 ));
10494 funding_negotiation.as_funding()
10495 })
10496 .unwrap_or(&self.funding);
10497 self.context.get_initial_commitment_signed_v2(funding, logger)
10498 } else {
10499 None
10500 };
10501
10502 let mut shared_input_signature_unblocked = false;
10503 {
10504 if let Some(signing_session) = self.context.interactive_tx_signing_session.as_mut() {
10505 if signing_session.awaiting_holder_shared_input_signature() {
10506 let splice_input_index = signing_session
10507 .unsigned_tx()
10508 .shared_input_index()
10509 .expect("Missing shared input index while awaiting a splice signature");
10510 log_trace!(logger, "Attempting to generate pending splice shared input signature...");
10511 if let Ok(shared_input_signature) = self.context.holder_signer.sign_splice_shared_input(
10512 &self.funding.channel_transaction_parameters,
10513 signing_session.unsigned_tx().tx(),
10514 splice_input_index as usize,
10515 &self.context.secp_ctx,
10516 ) {
10517 shared_input_signature_unblocked = true;
10518 signing_session
10519 .provide_holder_shared_input_signature(shared_input_signature)
10520 .map_err(ChannelError::close)?;
10521 }
10522 }
10523 }
10524 }
10525
10526 let mut tx_signatures = None;
10527 let mut funding_tx = None;
10528 if funding_commit_sig.is_some() || shared_input_signature_unblocked {
10529 if let Some(signing_session) = self.context.interactive_tx_signing_session.as_ref() {
10530 if !self.is_awaiting_monitor_update() && !self.context.signer_pending_funding {
10531 tx_signatures = signing_session.holder_tx_signatures();
10532 funding_tx = tx_signatures.as_ref().and_then(|_| signing_session.signed_tx());
10533 }
10534 } else {
10535 debug_assert!(false);
10536 }
10537 }
10538
10539 let mut funding_tx_signed = None;
10540 if funding_commit_sig.is_some() || tx_signatures.is_some() || funding_tx.is_some() {
10541 let mut resumed = FundingTxSigned {
10542 commitment_signed: funding_commit_sig,
10543 counterparty_initial_commitment_signed_result: None,
10544 tx_signatures,
10545 funding_tx: None,
10546 splice_negotiated: None,
10547 splice_locked: None,
10548 };
10549 if let Some(funding_tx) = funding_tx {
10550 let funding_logger = WithChannelContext::from(logger, &self.context, None);
10551 debug_assert!(resumed.tx_signatures.is_some());
10552 self.on_tx_signatures_exchange(
10553 &mut resumed,
10554 funding_tx,
10555 best_block_height,
10556 &funding_logger,
10557 );
10558 }
10559 funding_tx_signed = Some(resumed);
10560 }
10561
10562 let channel_ready = if self.context.signer_pending_channel_ready && !self.context.signer_pending_funding {
10565 log_trace!(logger, "Attempting to generate pending channel_ready...");
10566 self.get_channel_ready(logger)
10567 } else { None };
10568
10569 let mut commitment_update = if self.context.signer_pending_commitment_update {
10570 log_trace!(logger, "Attempting to generate pending commitment update...");
10571 self.get_last_commitment_update_for_send(logger).ok()
10572 } else { None };
10573 let mut revoke_and_ack = if self.context.signer_pending_revoke_and_ack {
10574 log_trace!(logger, "Attempting to generate pending revoke and ack...");
10575 self.get_last_revoke_and_ack(path_for_release_htlc, logger)
10576 } else { None };
10577
10578 if self.context.resend_order == RAACommitmentOrder::CommitmentFirst
10579 && self.context.signer_pending_commitment_update && revoke_and_ack.is_some() {
10580 log_trace!(logger, "Signer unblocked for revoke and ack, but unable to send due to resend order, waiting on signer for commitment update");
10581 self.context.signer_pending_revoke_and_ack = true;
10582 revoke_and_ack = None;
10583 }
10584 if self.context.resend_order == RAACommitmentOrder::RevokeAndACKFirst
10585 && self.context.signer_pending_revoke_and_ack && commitment_update.is_some() {
10586 log_trace!(logger, "Signer unblocked for commitment update, but unable to send due to resend order, waiting on signer for revoke and ack");
10587 self.context.signer_pending_commitment_update = true;
10588 commitment_update = None;
10589 }
10590 if revoke_and_ack.is_some() {
10591 self.context.monitor_pending_revoke_and_ack = false;
10596 }
10597
10598 let (closing_signed, signed_closing_tx, shutdown_result) = if self.context.signer_pending_closing {
10599 debug_assert!(self.context.last_sent_closing_fee.is_some());
10600 if let Some((fee, skip_remote_output, fee_range, holder_sig)) = self.context.last_sent_closing_fee.clone() {
10601 debug_assert!(holder_sig.is_none());
10602 log_trace!(logger, "Attempting to generate pending closing_signed...");
10603 let closing_transaction_result = self.build_closing_transaction(fee, skip_remote_output);
10604 match closing_transaction_result {
10605 Ok((closing_tx, fee)) => {
10606 let closing_signed = self.get_closing_signed_msg(&closing_tx, skip_remote_output,
10607 fee, fee_range.min_fee_satoshis, fee_range.max_fee_satoshis, logger);
10608 let signed_tx = if let (Some(ClosingSigned { signature, .. }), Some(counterparty_sig)) =
10609 (closing_signed.as_ref(), self.context.last_received_closing_sig) {
10610 let funding_redeemscript = self.funding.get_funding_redeemscript();
10611 let sighash = closing_tx.trust().get_sighash_all(&funding_redeemscript, self.funding.get_value_satoshis());
10612 debug_assert!(self.context.secp_ctx.verify_ecdsa(&sighash, &counterparty_sig,
10613 &self.funding.get_counterparty_pubkeys().funding_pubkey).is_ok());
10614 Some(self.build_signed_closing_transaction(&closing_tx, &counterparty_sig, signature))
10615 } else { None };
10616 let shutdown_result = signed_tx.as_ref().map(|_| self.shutdown_result_coop_close());
10617 (closing_signed, signed_tx, shutdown_result)
10618 }
10619 Err(err) => {
10620 let shutdown = self.context.force_shutdown(&self.funding, ClosureReason::ProcessingError {err: err.to_string()});
10621 (None, None, Some(shutdown))
10622 }
10623 }
10624 } else { (None, None, None) }
10625 } else { (None, None, None) };
10626
10627 log_trace!(logger, "Signer unblocked with {} commitment_update, {} revoke_and_ack, with resend order {:?}, {} funding_signed, \
10628 {} funding commit_sig, {} tx_signatures, {} channel_ready, {} closing_signed, {} signed_closing_tx, and {} shutdown result",
10629 if commitment_update.is_some() { "a" } else { "no" },
10630 if revoke_and_ack.is_some() { "a" } else { "no" },
10631 self.context.resend_order,
10632 if funding_signed.is_some() { "a" } else { "no" },
10633 if funding_tx_signed.as_ref().map(|v| v.commitment_signed.is_some()).unwrap_or(false) { "a" } else { "no" },
10634 if funding_tx_signed.as_ref().map(|v| v.tx_signatures.is_some()).unwrap_or(false) { "a" } else { "no" },
10635 if channel_ready.is_some() { "a" } else { "no" },
10636 if closing_signed.is_some() { "a" } else { "no" },
10637 if signed_closing_tx.is_some() { "a" } else { "no" },
10638 if shutdown_result.is_some() { "a" } else { "no" });
10639
10640 Ok(SignerResumeUpdates {
10641 commitment_update,
10642 revoke_and_ack,
10643 open_channel: None,
10644 accept_channel: None,
10645 funding_created: None,
10646 funding_signed,
10647 funding_tx_signed,
10648 channel_ready,
10649 order: self.context.resend_order.clone(),
10650 closing_signed,
10651 signed_closing_tx,
10652 shutdown_result,
10653 })
10654 }
10655
10656 fn get_last_revoke_and_ack<CBP, L: Logger>(
10657 &mut self, path_for_release_htlc: CBP, logger: &L,
10658 ) -> Option<msgs::RevokeAndACK>
10659 where
10660 CBP: Fn(u64) -> BlindedMessagePath,
10661 {
10662 debug_assert!(
10663 self.holder_commitment_point.next_transaction_number() <= INITIAL_COMMITMENT_NUMBER - 2
10664 );
10665 let signer = &self.context.holder_signer;
10666 self.holder_commitment_point.try_resolve_pending(signer, &self.context.secp_ctx, logger);
10667 let per_commitment_secret = signer
10668 .release_commitment_secret(self.holder_commitment_point.next_transaction_number() + 2)
10669 .ok();
10670 if let Some(per_commitment_secret) = per_commitment_secret {
10671 if self.holder_commitment_point.can_advance() {
10672 let mut release_htlc_message_paths = Vec::new();
10673 for htlc in &self.context.pending_inbound_htlcs {
10674 if htlc.state.should_hold_htlc() {
10675 let path = path_for_release_htlc(htlc.htlc_id);
10676 release_htlc_message_paths.push((htlc.htlc_id, path));
10677 }
10678 }
10679
10680 self.context.signer_pending_revoke_and_ack = false;
10681 return Some(msgs::RevokeAndACK {
10682 channel_id: self.context.channel_id,
10683 per_commitment_secret,
10684 next_per_commitment_point: self.holder_commitment_point.next_point(),
10685 release_htlc_message_paths,
10686 });
10687 }
10688 }
10689 if !self.holder_commitment_point.can_advance() {
10690 log_trace!(logger, "Last revoke-and-ack pending for sequence {} because the next per-commitment point is not available",
10691 self.holder_commitment_point.next_transaction_number());
10692 }
10693 if per_commitment_secret.is_none() {
10694 log_trace!(logger, "Last revoke-and-ack pending for sequence {} because the next per-commitment secret for {} is not available",
10695 self.holder_commitment_point.next_transaction_number(),
10696 self.holder_commitment_point.next_transaction_number() + 2);
10697 }
10698 log_trace!(logger, "Last revoke-and-ack pending for sequence {} because the next per-commitment point is not available",
10705 self.holder_commitment_point.next_transaction_number());
10706 self.context.signer_pending_revoke_and_ack = true;
10707 None
10708 }
10709
10710 fn get_last_commitment_update_for_send<L: Logger>(
10712 &mut self, logger: &L,
10713 ) -> Result<msgs::CommitmentUpdate, ()> {
10714 let mut update_add_htlcs = Vec::new();
10715 let mut update_fulfill_htlcs = Vec::new();
10716 let mut update_fail_htlcs = Vec::new();
10717 let mut update_fail_malformed_htlcs = Vec::new();
10718
10719 for htlc in self.context.pending_outbound_htlcs.iter() {
10720 if let &OutboundHTLCState::LocalAnnounced(ref onion_packet) = &htlc.state {
10721 update_add_htlcs.push(msgs::UpdateAddHTLC {
10722 channel_id: self.context.channel_id(),
10723 htlc_id: htlc.htlc_id,
10724 amount_msat: htlc.amount_msat,
10725 payment_hash: htlc.payment_hash,
10726 cltv_expiry: htlc.cltv_expiry,
10727 onion_routing_packet: (**onion_packet).clone(),
10728 skimmed_fee_msat: htlc.skimmed_fee_msat,
10729 blinding_point: htlc.blinding_point,
10730 hold_htlc: htlc.hold_htlc,
10731 accountable: Some(htlc.accountable),
10732 });
10733 }
10734 }
10735
10736 for htlc in self.context.pending_inbound_htlcs.iter() {
10737 if let &InboundHTLCState::LocalRemoved(ref reason) = &htlc.state {
10738 match reason {
10739 &InboundHTLCRemovalReason::FailRelay(ref err_packet) => {
10740 update_fail_htlcs.push(msgs::UpdateFailHTLC {
10741 channel_id: self.context.channel_id(),
10742 htlc_id: htlc.htlc_id,
10743 reason: err_packet.data.clone(),
10744 attribution_data: err_packet.attribution_data.clone(),
10745 });
10746 },
10747 &InboundHTLCRemovalReason::FailMalformed {
10748 sha256_of_onion: ref hash,
10749 failure_code: ref code,
10750 } => {
10751 update_fail_malformed_htlcs.push(msgs::UpdateFailMalformedHTLC {
10752 channel_id: self.context.channel_id(),
10753 htlc_id: htlc.htlc_id,
10754 sha256_of_onion: hash.clone(),
10755 failure_code: code.clone(),
10756 });
10757 },
10758 &InboundHTLCRemovalReason::Fulfill { ref preimage, ref attribution_data } => {
10759 update_fulfill_htlcs.push(msgs::UpdateFulfillHTLC {
10760 channel_id: self.context.channel_id(),
10761 htlc_id: htlc.htlc_id,
10762 payment_preimage: preimage.clone(),
10763 attribution_data: attribution_data.clone(),
10764 });
10765 },
10766 }
10767 }
10768 }
10769
10770 let update_fee = if self.funding.is_outbound() && self.context.pending_update_fee.is_some()
10771 {
10772 Some(msgs::UpdateFee {
10773 channel_id: self.context.channel_id(),
10774 feerate_per_kw: self.context.pending_update_fee.unwrap().0,
10775 })
10776 } else {
10777 None
10778 };
10779
10780 log_trace!(logger, "Regenerating latest commitment update with{} {} update_adds, {} update_fulfills, {} update_fails, and {} update_fail_malformeds",
10781 if update_fee.is_some() { " update_fee," } else { "" },
10782 update_add_htlcs.len(), update_fulfill_htlcs.len(), update_fail_htlcs.len(), update_fail_malformed_htlcs.len());
10783 let commitment_signed = if let Ok(update) = self.send_commitment_no_state_update(logger) {
10784 if self.context.signer_pending_commitment_update {
10785 log_trace!(
10786 logger,
10787 "Commitment update generated: clearing signer_pending_commitment_update"
10788 );
10789 self.context.signer_pending_commitment_update = false;
10790 }
10791 update
10792 } else {
10793 if !self.context.signer_pending_commitment_update {
10794 log_trace!(
10795 logger,
10796 "Commitment update awaiting signer: setting signer_pending_commitment_update"
10797 );
10798 self.context.signer_pending_commitment_update = true;
10799 }
10800 return Err(());
10801 };
10802 Ok(msgs::CommitmentUpdate {
10803 update_add_htlcs,
10804 update_fulfill_htlcs,
10805 update_fail_htlcs,
10806 update_fail_malformed_htlcs,
10807 update_fee,
10808 commitment_signed,
10809 })
10810 }
10811
10812 pub fn get_outbound_shutdown(&self) -> Option<msgs::Shutdown> {
10814 if self.context.channel_state.is_local_shutdown_sent() {
10815 assert!(self.context.shutdown_scriptpubkey.is_some());
10816 Some(msgs::Shutdown {
10817 channel_id: self.context.channel_id,
10818 scriptpubkey: self.get_closing_scriptpubkey(),
10819 })
10820 } else {
10821 None
10822 }
10823 }
10824
10825 fn panic_on_stale_state<L: Logger>(logger: &L) {
10826 macro_rules! log_and_panic {
10827 ($err_msg: expr) => {
10828 log_error!(logger, $err_msg);
10829 panic!($err_msg);
10830 };
10831 }
10832 log_and_panic!("We have fallen behind - we have received proof that if we broadcast our counterparty is going to claim all our funds.\n\
10833 This implies you have restarted with lost ChannelMonitor and ChannelManager state, the first of which is a violation of the LDK chain::Watch requirements.\n\
10834 More specifically, this means you have a bug in your implementation that can cause loss of funds, or you are running with an old backup, which is unsafe.\n\
10835 If you have restored from an old backup and wish to claim any available funds, you should restart with\n\
10836 an empty ChannelManager and no ChannelMonitors, reconnect to peer(s), ensure they've force-closed all of your\n\
10837 previous channels and that the closure transaction(s) have confirmed on-chain,\n\
10838 then restart with an empty ChannelManager and the latest ChannelMonitors that you do have.");
10839 }
10840
10841 #[rustfmt::skip]
10844 pub fn channel_reestablish<L: Logger, NS: NodeSigner, CBP>(
10845 &mut self, msg: &msgs::ChannelReestablish, logger: &L, node_signer: &NS,
10846 chain_hash: ChainHash, user_config: &UserConfig, best_block: &BlockLocator,
10847 path_for_release_htlc: CBP,
10848 ) -> Result<ReestablishResponses, ChannelError>
10849 where
10850 CBP: Fn(u64) -> BlindedMessagePath
10851 {
10852 if !self.context.channel_state.is_peer_disconnected() {
10853 return Err(ChannelError::close("Peer sent a loose channel_reestablish not after reconnect".to_owned()));
10857 }
10858
10859 if msg.next_local_commitment_number == 0
10864 || msg.next_local_commitment_number >= INITIAL_COMMITMENT_NUMBER
10865 || msg.next_remote_commitment_number >= INITIAL_COMMITMENT_NUMBER
10866 {
10867 return Err(ChannelError::close("Peer sent an invalid channel_reestablish to force close in a non-standard way".to_owned()));
10868 }
10869
10870 let our_commitment_transaction = INITIAL_COMMITMENT_NUMBER - self.holder_commitment_point.current_transaction_number();
10871 if msg.next_remote_commitment_number > 0 {
10872 let given_secret = SecretKey::from_slice(&msg.your_last_per_commitment_secret)
10873 .map_err(|_| ChannelError::close("Peer sent a garbage channel_reestablish with unparseable secret key".to_owned()))?;
10874 if msg.next_remote_commitment_number > our_commitment_transaction {
10875 let given_commitment_number = INITIAL_COMMITMENT_NUMBER - msg.next_remote_commitment_number + 1;
10876 let expected_point = self.context.holder_signer
10877 .get_per_commitment_point(given_commitment_number, &self.context.secp_ctx)
10878 .ok();
10879 if expected_point.is_none() {
10880 self.context.signer_pending_stale_state_verification = Some((given_commitment_number, given_secret));
10881 log_info!(logger, "Waiting on async signer to verify stale state proof");
10882 return Err(ChannelError::WarnAndDisconnect("Channel is not ready to be reestablished yet".to_owned()));
10883 }
10884 if expected_point != Some(PublicKey::from_secret_key(&self.context.secp_ctx, &given_secret)) {
10885 return Err(ChannelError::close("Peer sent a channel_reestablish indicating we're stale with an invalid commitment secret".to_owned()));
10886 }
10887 Self::panic_on_stale_state(logger);
10888 } else if msg.next_remote_commitment_number == our_commitment_transaction {
10889 let expected_point = self.holder_commitment_point.last_revoked_point()
10890 .expect("The last revoked commitment point must exist when the state has advanced");
10891 if expected_point != PublicKey::from_secret_key(&self.context.secp_ctx, &given_secret) {
10892 return Err(ChannelError::close("Peer sent a garbage channel_reestablish with secret key not matching the commitment height provided".to_owned()));
10893 }
10894 } else if msg.next_remote_commitment_number + 1 == our_commitment_transaction {
10895 let expected_point = self.holder_commitment_point.previous_revoked_point()
10896 .expect("The previous revoked commitment point must exist when they are one state behind");
10897 if expected_point != PublicKey::from_secret_key(&self.context.secp_ctx, &given_secret) {
10898 return Err(ChannelError::close("Peer sent a garbage channel_reestablish with secret key not matching the commitment height provided".to_owned()));
10899 }
10900 }
10901 }
10902
10903 if msg.next_remote_commitment_number + 1 < our_commitment_transaction {
10906 return Err(ChannelError::Warn(format!(
10907 "Peer attempted to reestablish channel with a very old local commitment transaction: {} (received) vs {} (expected)",
10908 msg.next_remote_commitment_number,
10909 our_commitment_transaction
10910 )));
10911 }
10912
10913 self.context.channel_state.clear_peer_disconnected();
10916 self.mark_response_received();
10917 let funding_locked_txid_sent_in_reestablish =
10918 self.context.funding_locked_txid_sent_in_reestablish.take();
10919
10920 let shutdown_msg = self.get_outbound_shutdown();
10921
10922 if let Some(funding_locked) = &msg.my_current_funding_locked {
10929 if funding_locked.should_retransmit(msgs::FundingLockedFlags::AnnouncementSignatures) {
10930 if self.funding.get_funding_txid() == Some(funding_locked.txid) {
10931 self.context.announcement_sigs_state = AnnouncementSigsState::NotSent;
10932 }
10933 }
10934 }
10935
10936 let our_splice_txid =
10942 self.pending_splice.as_ref().and_then(|pending| pending.sent_funding_txid);
10943 let splice_promotion_pending = msg
10944 .my_current_funding_locked
10945 .as_ref()
10946 .map(|funding_locked| Some(funding_locked.txid) == our_splice_txid)
10947 .unwrap_or(false);
10948 let announcement_sigs = if splice_promotion_pending {
10949 None
10950 } else {
10951 self.get_announcement_sigs(node_signer, chain_hash, user_config, best_block.height, logger)
10952 };
10953
10954 let mut commitment_update = None;
10955 let mut tx_signatures = None;
10956 let mut tx_abort = None;
10957
10958 let mut retransmit_funding_commit_sig = None;
10961 if let Some(next_funding) = &msg.next_funding {
10962 if let Some(session) = &self.context.interactive_tx_signing_session {
10965 let our_next_funding_txid = session.unsigned_tx().compute_txid();
10966 if our_next_funding_txid != next_funding.txid {
10967 if !session.has_received_tx_signatures() {
10968 return Err(ChannelError::close(format!(
10969 "Unexpected next_funding txid: {}; expected: {}",
10970 next_funding.txid, our_next_funding_txid,
10971 )));
10972 }
10973 tx_abort = Some(msgs::TxAbort {
10974 channel_id: self.context.channel_id(),
10975 data: format!("Unknown funding with txid {}", next_funding.txid).as_bytes().to_vec(),
10976 });
10977 } else if !session.has_holder_witnesses() {
10978 log_debug!(logger, "Waiting for funding transaction signatures to be provided");
10979 } else {
10980 if !session.has_received_tx_signatures()
10983 && next_funding.should_retransmit(msgs::NextFundingFlag::CommitmentSigned)
10984 {
10985 retransmit_funding_commit_sig = Some(next_funding.txid);
10987 }
10988
10989 if let Some(holder_tx_signatures) = session.holder_tx_signatures() {
10995 let splice_signatures_exchange_complete = self
10998 .pending_splice
10999 .as_ref()
11000 .map(|pending_splice| {
11001 pending_splice.negotiated_candidates.iter().any(|candidate| {
11002 candidate.funding.get_funding_txid() == Some(next_funding.txid)
11003 })
11004 })
11005 .unwrap_or(false);
11006 if self.is_awaiting_monitor_update()
11007 && !splice_signatures_exchange_complete
11008 {
11009 log_debug!(logger, "Waiting for monitor update before providing funding transaction signatures");
11010 } else if self.context.signer_pending_funding {
11011 log_debug!(logger, "Waiting for signer to provide counterparty commitment_signed before releasing funding transaction signatures");
11012 } else {
11013 tx_signatures = Some(holder_tx_signatures);
11014 }
11015 }
11016 }
11017 } else {
11018 tx_abort = Some(msgs::TxAbort {
11022 channel_id: self.context.channel_id(),
11023 data:
11024 "Signing was not completed for this funding transaction; it may be forgotten.".as_bytes().to_vec() });
11025 }
11026 }
11027 if let Some(funding_txid) = retransmit_funding_commit_sig {
11028 let funding = self
11029 .pending_splice
11030 .as_ref()
11031 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
11032 .and_then(|funding_negotiation| {
11033 if let FundingNegotiation::AwaitingSignatures { funding, .. } = &funding_negotiation {
11034 Some(funding)
11035 } else {
11036 None
11037 }
11038 })
11039 .or_else(|| Some(&self.funding))
11040 .filter(|funding| funding.get_funding_txid() == Some(funding_txid))
11041 .ok_or_else(|| {
11042 let message = "Failed to find funding for new commitment_signed".to_owned();
11043 ChannelError::Close(
11044 (
11045 message.clone(),
11046 ClosureReason::HolderForceClosed { message, broadcasted_latest_txn: Some(false) },
11047 )
11048 )
11049 })?;
11050
11051 commitment_update = self
11052 .context
11053 .get_initial_commitment_signed_v2(&funding, logger)
11054 .map(|commitment_signed|
11055 msgs::CommitmentUpdate {
11056 commitment_signed: vec![commitment_signed],
11057 update_add_htlcs: vec![],
11058 update_fulfill_htlcs: vec![],
11059 update_fail_htlcs: vec![],
11060 update_fail_malformed_htlcs: vec![],
11061 update_fee: None,
11062 }
11063 );
11064 if commitment_update.is_none() {
11065 tx_signatures.take();
11066 }
11067 }
11068
11069 if matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(_)) {
11070 if !self.context.channel_state.is_our_channel_ready() ||
11072 self.context.channel_state.is_monitor_update_in_progress() {
11073 if msg.next_remote_commitment_number != 0 {
11074 return Err(ChannelError::close("Peer claimed they saw a revoke_and_ack but we haven't sent channel_ready yet".to_owned()));
11075 }
11076
11077 return Ok(ReestablishResponses {
11078 channel_ready: None,
11079 channel_ready_order: ChannelReadyOrder::SignaturesFirst,
11080 raa: None, commitment_update,
11081 commitment_order: self.context.resend_order.clone(),
11082 shutdown_msg, announcement_sigs,
11083 tx_signatures: tx_signatures
11084 .map(|msg| (TxSignaturesOrder::CommitmentFirst, msg)),
11085 tx_abort: None,
11086 splice_locked: None,
11087 inferred_splice_locked: None,
11088 });
11089 }
11090
11091 return Ok(ReestablishResponses {
11093 channel_ready: self.get_channel_ready(logger),
11094 channel_ready_order: ChannelReadyOrder::SignaturesFirst,
11095 raa: None, commitment_update,
11096 commitment_order: self.context.resend_order.clone(),
11097 shutdown_msg, announcement_sigs,
11098 tx_signatures: tx_signatures
11099 .map(|msg| (TxSignaturesOrder::CommitmentFirst, msg)),
11100 tx_abort,
11101 splice_locked: None,
11102 inferred_splice_locked: None,
11103 });
11104 }
11105
11106 let required_revoke = if msg.next_remote_commitment_number == our_commitment_transaction {
11107 self.context.monitor_pending_revoke_and_ack = false;
11112 None
11113 } else if msg.next_remote_commitment_number + 1 == our_commitment_transaction {
11114 if self.context.channel_state.is_monitor_update_in_progress() {
11115 self.context.monitor_pending_revoke_and_ack = true;
11116 None
11117 } else {
11118 self.get_last_revoke_and_ack(path_for_release_htlc, logger)
11119 }
11120 } else {
11121 debug_assert!(false, "All values should have been handled in the four cases above");
11122 return Err(ChannelError::close(format!(
11123 "Peer attempted to reestablish channel expecting a future local commitment transaction: {} (received) vs {} (expected)",
11124 msg.next_remote_commitment_number,
11125 our_commitment_transaction
11126 )));
11127 };
11128
11129 let is_awaiting_remote_revoke = self.context.channel_state.is_awaiting_remote_revoke();
11134 let next_counterparty_commitment_number = INITIAL_COMMITMENT_NUMBER - self.context.counterparty_next_commitment_transaction_number + if is_awaiting_remote_revoke { 1 } else { 0 };
11135
11136 let both_sides_on_initial_commitment_number = msg.next_local_commitment_number == 1
11145 && INITIAL_COMMITMENT_NUMBER - self.holder_commitment_point.next_transaction_number() == 1;
11146 let channel_ready = if both_sides_on_initial_commitment_number
11147 && self.pending_splice.is_none()
11148 && self.funding.channel_transaction_parameters.splice_parent_funding_txid.is_none()
11149 {
11150 self.get_channel_ready(logger)
11152 } else { None };
11153
11154 let inferred_splice_locked = msg.my_current_funding_locked.as_ref().and_then(|funding_locked| {
11160 self.pending_funding()
11161 .find(|funding| funding.get_funding_txid() == Some(funding_locked.txid))
11162 .and_then(|_| {
11163 self.pending_splice.as_ref().and_then(|pending_splice| {
11164 (Some(funding_locked.txid) != pending_splice.received_funding_txid)
11165 .then(|| funding_locked.txid)
11166 })
11167 })
11168 .map(|splice_txid| msgs::SpliceLocked {
11169 channel_id: self.context.channel_id,
11170 splice_txid,
11171 })
11172 });
11173 let splice_locked = self.pending_splice.as_ref().and_then(|pending_splice| {
11174 pending_splice
11175 .sent_funding_txid
11176 .filter(|splice_txid| {
11177 Some(*splice_txid) != funding_locked_txid_sent_in_reestablish
11182 || tx_signatures
11183 .as_ref()
11184 .is_some_and(|tx_signatures| tx_signatures.tx_hash == *splice_txid)
11185 })
11186 .map(|splice_txid| msgs::SpliceLocked {
11187 channel_id: self.context.channel_id,
11188 splice_txid,
11189 })
11190 }).or_else(|| {
11191 let current_funding_txid = self.funding.get_funding_txid()?;
11196 (self.pending_splice.is_none()
11197 && self.funding.channel_transaction_parameters.splice_parent_funding_txid.is_some()
11198 && Some(current_funding_txid) != funding_locked_txid_sent_in_reestablish)
11199 .then(|| msgs::SpliceLocked {
11200 channel_id: self.context.channel_id,
11201 splice_txid: current_funding_txid,
11202 })
11203 });
11204
11205 if msg.next_local_commitment_number == next_counterparty_commitment_number {
11206 self.context.monitor_pending_commitment_signed = false;
11209 if required_revoke.is_some() || self.context.signer_pending_revoke_and_ack {
11210 log_debug!(logger, "Reconnected with only lost outbound RAA");
11211 } else {
11212 log_debug!(logger, "Reconnected with no loss");
11213 }
11214
11215 let tx_signatures_order = if commitment_update.is_some() {
11219 TxSignaturesOrder::CommitmentFirst
11220 } else {
11221 TxSignaturesOrder::SignaturesFirst
11222 };
11223
11224 Ok(ReestablishResponses {
11225 channel_ready,
11226 channel_ready_order: ChannelReadyOrder::SignaturesFirst,
11227 shutdown_msg,
11228 announcement_sigs,
11229 raa: required_revoke,
11230 commitment_update,
11231 commitment_order: self.context.resend_order.clone(),
11232 tx_signatures: tx_signatures.map(|msg| (tx_signatures_order, msg)),
11233 tx_abort,
11234 splice_locked,
11235 inferred_splice_locked,
11236 })
11237 } else if msg.next_local_commitment_number == next_counterparty_commitment_number - 1
11238 && is_awaiting_remote_revoke
11239 {
11240 if retransmit_funding_commit_sig.is_some() {
11241 return Err(ChannelError::close(
11242 "Peer requested retransmission of an initial commitment_signed while claiming to have lost a later commitment_signed".to_owned(),
11243 ));
11244 }
11245
11246 if required_revoke.is_some() || self.context.signer_pending_revoke_and_ack {
11247 log_debug!(logger, "Reconnected channel with lost outbound RAA and lost remote commitment tx");
11248 } else {
11249 log_debug!(logger, "Reconnected channel with only lost remote commitment tx");
11250 }
11251
11252 if self.context.channel_state.is_monitor_update_in_progress() {
11253 self.context.monitor_pending_commitment_signed = true;
11254 Ok(ReestablishResponses {
11255 channel_ready,
11256 channel_ready_order: ChannelReadyOrder::ChannelReadyFirst,
11257 shutdown_msg, announcement_sigs,
11258 commitment_update: None, raa: None,
11259 commitment_order: self.context.resend_order.clone(),
11260 tx_signatures: tx_signatures
11261 .map(|msg| (TxSignaturesOrder::SignaturesFirst, msg)),
11262 tx_abort,
11263 splice_locked,
11264 inferred_splice_locked,
11265 })
11266 } else {
11267 let commitment_update = if self.context.resend_order == RAACommitmentOrder::RevokeAndACKFirst
11268 && self.context.signer_pending_revoke_and_ack {
11269 log_trace!(logger, "Reconnected channel with lost outbound RAA and lost remote commitment tx, but unable to send due to resend order, waiting on signer for revoke and ack");
11270 self.context.signer_pending_commitment_update = true;
11271 None
11272 } else {
11273 self.get_last_commitment_update_for_send(logger).ok()
11274 };
11275 let raa = if self.context.resend_order == RAACommitmentOrder::CommitmentFirst
11276 && self.context.signer_pending_commitment_update && required_revoke.is_some() {
11277 log_trace!(logger, "Reconnected channel with lost outbound RAA and lost remote commitment tx, but unable to send due to resend order, waiting on signer for commitment update");
11278 self.context.signer_pending_revoke_and_ack = true;
11279 None
11280 } else {
11281 required_revoke
11282 };
11283 Ok(ReestablishResponses {
11284 channel_ready,
11285 channel_ready_order: ChannelReadyOrder::ChannelReadyFirst,
11286 shutdown_msg, announcement_sigs,
11287 raa, commitment_update,
11288 commitment_order: self.context.resend_order.clone(),
11289 tx_signatures: tx_signatures
11290 .map(|msg| (TxSignaturesOrder::SignaturesFirst, msg)),
11291 tx_abort,
11292 splice_locked,
11293 inferred_splice_locked,
11294 })
11295 }
11296 } else if msg.next_local_commitment_number < next_counterparty_commitment_number {
11297 Err(ChannelError::close(format!(
11298 "Peer attempted to reestablish channel with a very old remote commitment transaction: {} (received) vs {} (expected)",
11299 msg.next_local_commitment_number,
11300 next_counterparty_commitment_number,
11301 )))
11302 } else {
11303 Err(ChannelError::close(format!(
11304 "Peer attempted to reestablish channel with a future remote commitment transaction: {} (received) vs {} (expected)",
11305 msg.next_local_commitment_number,
11306 next_counterparty_commitment_number,
11307 )))
11308 }
11309 }
11310
11311 fn calculate_closing_fee_limits<F: FeeEstimator>(
11315 &mut self, fee_estimator: &LowerBoundedFeeEstimator<F>,
11316 ) -> (u64, u64) {
11317 if let Some((min, max)) = self.context.closing_fee_limits {
11318 return (min, max);
11319 }
11320
11321 let mut proposed_feerate =
11325 fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::ChannelCloseMinimum);
11326 let normal_feerate =
11329 fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
11330 let mut proposed_max_feerate =
11331 if self.funding.is_outbound() { normal_feerate } else { u32::max_value() };
11332
11333 if let Some(target_feerate) = self.context.target_closing_feerate_sats_per_kw {
11340 let min_feerate = if self.funding.is_outbound() {
11341 target_feerate
11342 } else {
11343 cmp::min(self.context.feerate_per_kw, target_feerate)
11344 };
11345 proposed_feerate = cmp::max(proposed_feerate, min_feerate);
11346 proposed_max_feerate = cmp::max(proposed_max_feerate, min_feerate);
11347 }
11348
11349 let tx_weight = self.get_closing_transaction_weight(
11357 Some(&self.get_closing_scriptpubkey()),
11358 Some(self.context.counterparty_shutdown_scriptpubkey.as_ref().unwrap()),
11359 );
11360 let proposed_total_fee_satoshis = proposed_feerate as u64 * tx_weight / 1000;
11361 let proposed_max_total_fee_satoshis = if self.funding.is_outbound() {
11362 cmp::max(
11366 normal_feerate as u64 * tx_weight / 1000
11367 + self.context.config.options.force_close_avoidance_max_fee_satoshis,
11368 proposed_max_feerate as u64 * tx_weight / 1000,
11369 )
11370 } else {
11371 self.funding.get_value_satoshis() - self.funding.value_to_self_msat.div_ceil(1000)
11372 };
11373
11374 self.context.closing_fee_limits =
11375 Some((proposed_total_fee_satoshis, proposed_max_total_fee_satoshis));
11376 self.context.closing_fee_limits.clone().unwrap()
11377 }
11378
11379 fn closing_negotiation_ready(&self) -> bool {
11384 self.context.closing_negotiation_ready()
11385 }
11386
11387 pub fn timer_check_closing_negotiation_progress(&mut self) -> Result<(), ChannelError> {
11391 if self.closing_negotiation_ready() {
11392 if self.context.closing_signed_in_flight {
11393 return Err(ChannelError::close(
11394 "closing_signed negotiation failed to finish within two timer ticks".to_owned(),
11395 ));
11396 } else {
11397 self.context.closing_signed_in_flight = true;
11398 }
11399 }
11400 Ok(())
11401 }
11402
11403 pub fn maybe_propose_closing_signed<F: FeeEstimator, L: Logger>(
11404 &mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
11405 ) -> Result<(Option<msgs::ClosingSigned>, Option<(Transaction, ShutdownResult)>), ChannelError>
11406 {
11407 if self.context.last_sent_closing_fee.is_some() || !self.closing_negotiation_ready() {
11412 return Ok((None, None));
11413 }
11414
11415 if !self.funding.is_outbound() {
11416 if let Some(msg) = &self.context.pending_counterparty_closing_signed.take() {
11417 return self.closing_signed(fee_estimator, &msg, logger);
11418 }
11419 return Ok((None, None));
11420 }
11421
11422 if self.context.expecting_peer_commitment_signed {
11425 return Ok((None, None));
11426 }
11427
11428 let (our_min_fee, our_max_fee) = self.calculate_closing_fee_limits(fee_estimator);
11429
11430 assert!(self.context.shutdown_scriptpubkey.is_some());
11431 let (closing_tx, total_fee_satoshis) =
11432 self.build_closing_transaction(our_min_fee, false)?;
11433 log_trace!(logger, "Proposing initial closing_signed for our counterparty with a fee range of {}-{} sat (with initial proposal {} sats)",
11434 our_min_fee, our_max_fee, total_fee_satoshis);
11435
11436 let closing_signed = self.get_closing_signed_msg(
11437 &closing_tx,
11438 false,
11439 total_fee_satoshis,
11440 our_min_fee,
11441 our_max_fee,
11442 logger,
11443 );
11444 Ok((closing_signed, None))
11445 }
11446
11447 fn mark_response_received(&mut self) {
11448 self.context.sent_message_awaiting_response = None;
11449 }
11450
11451 #[allow(clippy::assertions_on_constants)]
11457 #[rustfmt::skip]
11458 pub fn should_disconnect_peer_awaiting_response(&mut self) -> bool {
11459 if let Some(ticks_elapsed) = self.context.sent_message_awaiting_response.as_mut() {
11460 *ticks_elapsed += 1;
11461 *ticks_elapsed >= DISCONNECT_PEER_AWAITING_RESPONSE_TICKS
11462 } else if
11463 self.context.channel_state.is_peer_disconnected()
11465 || self.context.channel_state.is_local_stfu_sent()
11467 || self.context.channel_state.is_quiescent()
11469 || (self.context.is_waiting_on_peer_pending_channel_update()
11473 && !self.context.is_monitor_or_signer_pending_channel_update())
11474 {
11475 self.context.sent_message_awaiting_response = Some(1);
11477 debug_assert!(DISCONNECT_PEER_AWAITING_RESPONSE_TICKS > 1);
11478 false
11479 } else {
11480 false
11482 }
11483 }
11484
11485 pub fn shutdown<L: Logger>(
11486 &mut self, logger: &L, signer_provider: &SP, their_features: &InitFeatures,
11487 msg: &msgs::Shutdown,
11488 ) -> (
11489 Result<
11490 (Option<msgs::Shutdown>, Option<ChannelMonitorUpdate>, Vec<(HTLCSource, PaymentHash)>),
11491 ChannelError,
11492 >,
11493 Option<SpliceFundingFailed>,
11494 ) {
11495 if self.context.channel_state.is_peer_disconnected() {
11496 return (
11497 Err(ChannelError::close(
11498 "Peer sent shutdown when we needed a channel_reestablish".to_owned(),
11499 )),
11500 None,
11501 );
11502 }
11503 let mut not_broadcasted_initial_funding =
11504 matches!(self.context.channel_state, ChannelState::NegotiatingFunding(_));
11505 if matches!(self.context.channel_state, ChannelState::FundingNegotiated(_)) {
11506 if let Some(signing_session) = self.context.interactive_tx_signing_session.as_ref() {
11507 if !signing_session.has_holder_witnesses() {
11508 not_broadcasted_initial_funding = true;
11512 }
11513 }
11514 }
11515 if not_broadcasted_initial_funding {
11516 return (
11520 Err(ChannelError::close("Shutdown before funding was broadcasted".to_owned())),
11521 None,
11522 );
11523 }
11524 for htlc in self.context.pending_inbound_htlcs.iter() {
11525 if let InboundHTLCState::RemoteAnnounced(_) = htlc.state {
11526 return (
11527 Err(ChannelError::close("Got shutdown with remote pending HTLCs".to_owned())),
11528 None,
11529 );
11530 }
11531 }
11532 assert!(!matches!(self.context.channel_state, ChannelState::ShutdownComplete));
11533
11534 if self.context.channel_state.is_local_stfu_sent()
11535 || self.context.channel_state.is_remote_stfu_sent()
11536 || self.context.channel_state.is_quiescent()
11537 {
11538 let splice_funding_failed = self.abandon_quiescent_action();
11539 return (
11540 Err(ChannelError::WarnAndDisconnect(
11541 "Got shutdown request while quiescent".to_owned(),
11542 )),
11543 splice_funding_failed,
11544 );
11545 }
11546
11547 if !script::is_bolt2_compliant(&msg.scriptpubkey, their_features) {
11548 return (
11549 Err(ChannelError::Warn(format!(
11550 "Got a nonstandard scriptpubkey ({}) from remote peer",
11551 msg.scriptpubkey.to_hex_string()
11552 ))),
11553 None,
11554 );
11555 }
11556
11557 if self.context.counterparty_shutdown_scriptpubkey.is_some() {
11558 if Some(&msg.scriptpubkey) != self.context.counterparty_shutdown_scriptpubkey.as_ref() {
11559 return (Err(ChannelError::Warn(format!("Got shutdown request with a scriptpubkey ({}) which did not match their previous scriptpubkey.", msg.scriptpubkey.to_hex_string()))), None);
11560 }
11561 } else {
11562 self.context.counterparty_shutdown_scriptpubkey = Some(msg.scriptpubkey.clone());
11563 }
11564
11565 let send_shutdown = !self.context.channel_state.is_local_shutdown_sent();
11569
11570 let update_shutdown_script = match self.context.shutdown_scriptpubkey {
11571 Some(_) => false,
11572 None => {
11573 assert!(send_shutdown);
11574 let shutdown_scriptpubkey = match signer_provider.get_shutdown_scriptpubkey() {
11575 Ok(scriptpubkey) => scriptpubkey,
11576 Err(_) => {
11577 return (
11578 Err(ChannelError::close(
11579 "Failed to get shutdown scriptpubkey".to_owned(),
11580 )),
11581 None,
11582 )
11583 },
11584 };
11585 if !shutdown_scriptpubkey.is_compatible(their_features) {
11586 return (
11587 Err(ChannelError::close(format!(
11588 "Provided a scriptpubkey format not accepted by peer: {}",
11589 shutdown_scriptpubkey
11590 ))),
11591 None,
11592 );
11593 }
11594 self.context.shutdown_scriptpubkey = Some(shutdown_scriptpubkey);
11595 true
11596 },
11597 };
11598
11599 self.context.channel_state.set_remote_shutdown_sent();
11602 self.context.update_time_counter += 1;
11603
11604 let monitor_update = if update_shutdown_script {
11605 self.context.latest_monitor_update_id += 1;
11606 let monitor_update = ChannelMonitorUpdate {
11607 update_id: self.context.latest_monitor_update_id,
11608 updates: vec![ChannelMonitorUpdateStep::ShutdownScript {
11609 scriptpubkey: self.get_closing_scriptpubkey(),
11610 }],
11611 channel_id: Some(self.context.channel_id()),
11612 };
11613 self.monitor_updating_paused(
11614 false,
11615 false,
11616 false,
11617 Vec::new(),
11618 Vec::new(),
11619 Vec::new(),
11620 logger,
11621 );
11622 self.push_ret_blockable_mon_update(monitor_update)
11623 } else {
11624 None
11625 };
11626 let shutdown = if send_shutdown {
11627 Some(msgs::Shutdown {
11628 channel_id: self.context.channel_id,
11629 scriptpubkey: self.get_closing_scriptpubkey(),
11630 })
11631 } else {
11632 None
11633 };
11634
11635 self.context.holding_cell_update_fee = None;
11639 let mut dropped_outbound_htlcs =
11640 Vec::with_capacity(self.context.holding_cell_htlc_updates.len());
11641 self.context.holding_cell_htlc_updates.retain(|htlc_update| match htlc_update {
11642 &HTLCUpdateAwaitingACK::AddHTLC { ref payment_hash, ref source, .. } => {
11643 dropped_outbound_htlcs.push((source.clone(), payment_hash.clone()));
11644 false
11645 },
11646 _ => true,
11647 });
11648
11649 self.context.channel_state.set_local_shutdown_sent();
11650 self.context.update_time_counter += 1;
11651
11652 let splice_funding_failed = self.abandon_quiescent_action();
11653
11654 (Ok((shutdown, monitor_update, dropped_outbound_htlcs)), splice_funding_failed)
11655 }
11656
11657 fn build_signed_closing_transaction(
11658 &self, closing_tx: &ClosingTransaction, counterparty_sig: &Signature, sig: &Signature,
11659 ) -> Transaction {
11660 let mut tx = closing_tx.trust().built_transaction().clone();
11661
11662 tx.input[0].witness.push(Vec::new()); let funding_key = self.funding.get_holder_pubkeys().funding_pubkey.serialize();
11665 let counterparty_funding_key = self.funding.counterparty_funding_pubkey().serialize();
11666 let mut holder_sig = sig.serialize_der().to_vec();
11667 holder_sig.push(EcdsaSighashType::All as u8);
11668 let mut cp_sig = counterparty_sig.serialize_der().to_vec();
11669 cp_sig.push(EcdsaSighashType::All as u8);
11670 if funding_key[..] < counterparty_funding_key[..] {
11671 tx.input[0].witness.push(holder_sig);
11672 tx.input[0].witness.push(cp_sig);
11673 } else {
11674 tx.input[0].witness.push(cp_sig);
11675 tx.input[0].witness.push(holder_sig);
11676 }
11677
11678 tx.input[0].witness.push(self.funding.get_funding_redeemscript().into_bytes());
11679 tx
11680 }
11681
11682 fn get_closing_signed_msg<L: Logger>(
11683 &mut self, closing_tx: &ClosingTransaction, skip_remote_output: bool, fee_satoshis: u64,
11684 min_fee_satoshis: u64, max_fee_satoshis: u64, logger: &L,
11685 ) -> Option<msgs::ClosingSigned> {
11686 let sig = self
11687 .context
11688 .holder_signer
11689 .sign_closing_transaction(
11690 &self.funding.channel_transaction_parameters,
11691 closing_tx,
11692 &self.context.secp_ctx,
11693 )
11694 .ok();
11695 if sig.is_none() {
11696 log_trace!(logger, "Closing transaction signature unavailable, waiting on signer");
11697 self.context.signer_pending_closing = true;
11698 } else {
11699 self.context.signer_pending_closing = false;
11700 }
11701 let fee_range = msgs::ClosingSignedFeeRange { min_fee_satoshis, max_fee_satoshis };
11702 self.context.last_sent_closing_fee =
11703 Some((fee_satoshis, skip_remote_output, fee_range.clone(), sig.clone()));
11704 sig.map(|signature| msgs::ClosingSigned {
11705 channel_id: self.context.channel_id,
11706 fee_satoshis,
11707 signature,
11708 fee_range: Some(fee_range),
11709 })
11710 }
11711
11712 fn shutdown_result_coop_close(&self) -> ShutdownResult {
11713 let closure_reason = if self.initiated_shutdown() {
11714 ClosureReason::LocallyInitiatedCooperativeClosure
11715 } else {
11716 ClosureReason::CounterpartyInitiatedCooperativeClosure
11717 };
11718 ShutdownResult {
11719 closure_reason,
11720 monitor_update: None,
11721 dropped_outbound_htlcs: Vec::new(),
11722 unbroadcasted_batch_funding_txid: self
11723 .context
11724 .unbroadcasted_batch_funding_txid(&self.funding),
11725 channel_id: self.context.channel_id,
11726 user_channel_id: self.context.user_id,
11727 channel_capacity_satoshis: self.funding.get_value_satoshis(),
11728 counterparty_node_id: self.context.counterparty_node_id,
11729 unbroadcasted_funding_tx: self.context.unbroadcasted_funding(&self.funding),
11730 is_manual_broadcast: self.context.is_manual_broadcast,
11731 channel_funding_txo: self.funding.get_funding_txo(),
11732 last_local_balance_msat: self.funding.value_to_self_msat,
11733 splice_funding_failed: Vec::new(),
11734 splice_funding_negotiated: None,
11735 }
11736 }
11737
11738 pub fn closing_signed<F: FeeEstimator, L: Logger>(
11739 &mut self, fee_estimator: &LowerBoundedFeeEstimator<F>, msg: &msgs::ClosingSigned,
11740 logger: &L,
11741 ) -> Result<(Option<msgs::ClosingSigned>, Option<(Transaction, ShutdownResult)>), ChannelError>
11742 {
11743 if self.is_shutdown_pending_signature() {
11744 return Err(ChannelError::Warn(String::from("Remote end sent us a closing_signed while fully shutdown and just waiting on the final closing signature")));
11745 }
11746 if !self.context.channel_state.is_both_sides_shutdown() {
11747 return Err(ChannelError::close(
11748 "Remote end sent us a closing_signed before both sides provided a shutdown"
11749 .to_owned(),
11750 ));
11751 }
11752 if self.context.channel_state.is_peer_disconnected() {
11753 return Err(ChannelError::close(
11754 "Peer sent closing_signed when we needed a channel_reestablish".to_owned(),
11755 ));
11756 }
11757 if !self.context.pending_inbound_htlcs.is_empty()
11758 || !self.context.pending_outbound_htlcs.is_empty()
11759 {
11760 return Err(ChannelError::close(
11761 "Remote end sent us a closing_signed while there were still pending HTLCs"
11762 .to_owned(),
11763 ));
11764 }
11765 if msg.fee_satoshis > TOTAL_BITCOIN_SUPPLY_SATOSHIS {
11766 return Err(ChannelError::close(
11768 "Remote tried to send us a closing tx with > 21 million BTC fee".to_owned(),
11769 ));
11770 }
11771
11772 if self.funding.is_outbound() && self.context.last_sent_closing_fee.is_none() {
11773 return Err(ChannelError::close("Remote tried to send a closing_signed when we were supposed to propose the first one".to_owned()));
11774 }
11775
11776 if self.context.channel_state.is_monitor_update_in_progress() {
11777 self.context.pending_counterparty_closing_signed = Some(msg.clone());
11778 return Ok((None, None));
11779 }
11780
11781 let funding_redeemscript = self.funding.get_funding_redeemscript();
11782 let mut skip_remote_output = false;
11783 let (mut closing_tx, used_total_fee) =
11784 self.build_closing_transaction(msg.fee_satoshis, skip_remote_output)?;
11785 if used_total_fee != msg.fee_satoshis {
11786 return Err(ChannelError::close(format!("Remote sent us a closing_signed with a fee other than the value they can claim. Fee in message: {}. Actual closing tx fee: {}", msg.fee_satoshis, used_total_fee)));
11787 }
11788 let sighash = closing_tx
11789 .trust()
11790 .get_sighash_all(&funding_redeemscript, self.funding.get_value_satoshis());
11791
11792 match self.context.secp_ctx.verify_ecdsa(
11793 &sighash,
11794 &msg.signature,
11795 &self.funding.get_counterparty_pubkeys().funding_pubkey,
11796 ) {
11797 Ok(_) => {},
11798 Err(_e) => {
11799 skip_remote_output = true;
11802 closing_tx =
11803 self.build_closing_transaction(msg.fee_satoshis, skip_remote_output)?.0;
11804 let sighash = closing_tx
11805 .trust()
11806 .get_sighash_all(&funding_redeemscript, self.funding.get_value_satoshis());
11807 let res = self.context.secp_ctx.verify_ecdsa(
11808 &sighash,
11809 &msg.signature,
11810 self.funding.counterparty_funding_pubkey(),
11811 );
11812 secp_check!(res, "Invalid closing tx signature from peer".to_owned());
11813 },
11814 };
11815
11816 for outp in closing_tx.trust().built_transaction().output.iter() {
11817 if !outp.script_pubkey.is_witness_program()
11818 && outp.value < Amount::from_sat(MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS)
11819 {
11820 return Err(ChannelError::close("Remote sent us a closing_signed with a dust output. Always use segwit closing scripts!".to_owned()));
11821 }
11822 }
11823
11824 assert!(self.context.shutdown_scriptpubkey.is_some());
11825 if let Some((last_fee, _, _, Some(sig))) = self.context.last_sent_closing_fee {
11826 if last_fee == msg.fee_satoshis {
11827 let shutdown_result = self.shutdown_result_coop_close();
11828 let tx =
11829 self.build_signed_closing_transaction(&mut closing_tx, &msg.signature, &sig);
11830 self.context.channel_state = ChannelState::ShutdownComplete;
11831 self.context.update_time_counter += 1;
11832 return Ok((None, Some((tx, shutdown_result))));
11833 }
11834 }
11835
11836 let (our_min_fee, our_max_fee) = self.calculate_closing_fee_limits(fee_estimator);
11837
11838 macro_rules! propose_fee {
11839 ($new_fee: expr) => {
11840 let (closing_tx, used_fee) = if $new_fee == msg.fee_satoshis {
11841 (closing_tx, $new_fee)
11842 } else {
11843 skip_remote_output = false;
11844 self.build_closing_transaction($new_fee, skip_remote_output)?
11845 };
11846
11847 let closing_signed = self.get_closing_signed_msg(
11848 &closing_tx,
11849 skip_remote_output,
11850 used_fee,
11851 our_min_fee,
11852 our_max_fee,
11853 logger,
11854 );
11855 let signed_tx_shutdown = if $new_fee == msg.fee_satoshis {
11856 self.context.update_time_counter += 1;
11857 self.context.last_received_closing_sig = Some(msg.signature.clone());
11858 if let Some(ClosingSigned { signature, .. }) = &closing_signed {
11859 let shutdown_result = self.shutdown_result_coop_close();
11860 self.context.channel_state = ChannelState::ShutdownComplete;
11861 let tx = self.build_signed_closing_transaction(
11862 &closing_tx,
11863 &msg.signature,
11864 signature,
11865 );
11866 Some((tx, shutdown_result))
11867 } else {
11868 None
11869 }
11870 } else {
11871 None
11872 };
11873 return Ok((closing_signed, signed_tx_shutdown))
11874 };
11875 }
11876
11877 if let Some(msgs::ClosingSignedFeeRange { min_fee_satoshis, max_fee_satoshis }) =
11878 msg.fee_range
11879 {
11880 if msg.fee_satoshis < min_fee_satoshis || msg.fee_satoshis > max_fee_satoshis {
11881 return Err(ChannelError::close(format!("Peer sent a bogus closing_signed - suggested fee of {} sat was not in their desired range of {} sat - {} sat", msg.fee_satoshis, min_fee_satoshis, max_fee_satoshis)));
11882 }
11883 if max_fee_satoshis < our_min_fee {
11884 return Err(ChannelError::Warn(format!("Unable to come to consensus about closing feerate, remote's max fee ({} sat) was smaller than our min fee ({} sat)", max_fee_satoshis, our_min_fee)));
11885 }
11886 if min_fee_satoshis > our_max_fee {
11887 return Err(ChannelError::Warn(format!("Unable to come to consensus about closing feerate, remote's min fee ({} sat) was greater than our max fee ({} sat)", min_fee_satoshis, our_max_fee)));
11888 }
11889
11890 if !self.funding.is_outbound() {
11891 debug_assert_eq!(
11894 our_max_fee,
11895 self.funding.get_value_satoshis()
11896 - self.funding.value_to_self_msat.div_ceil(1000)
11897 );
11898 propose_fee!(cmp::min(max_fee_satoshis, our_max_fee));
11899 } else {
11900 if msg.fee_satoshis < our_min_fee || msg.fee_satoshis > our_max_fee {
11901 return Err(ChannelError::close(format!("Peer sent a bogus closing_signed - suggested fee of {} sat was not in our desired range of {} sat - {} sat after we informed them of our range.",
11902 msg.fee_satoshis, our_min_fee, our_max_fee)));
11903 }
11904 propose_fee!(msg.fee_satoshis);
11906 }
11907 } else {
11908 if let Some((last_fee, _, _, _)) = self.context.last_sent_closing_fee {
11911 if msg.fee_satoshis > last_fee {
11912 if msg.fee_satoshis < our_max_fee {
11913 propose_fee!(msg.fee_satoshis);
11914 } else if last_fee < our_max_fee {
11915 propose_fee!(our_max_fee);
11916 } else {
11917 return Err(ChannelError::close(format!("Unable to come to consensus about closing feerate, remote wants something ({} sat) higher than our max fee ({} sat)", msg.fee_satoshis, our_max_fee)));
11918 }
11919 } else {
11920 if msg.fee_satoshis > our_min_fee {
11921 propose_fee!(msg.fee_satoshis);
11922 } else if last_fee > our_min_fee {
11923 propose_fee!(our_min_fee);
11924 } else {
11925 return Err(ChannelError::close(format!("Unable to come to consensus about closing feerate, remote wants something ({} sat) lower than our min fee ({} sat)", msg.fee_satoshis, our_min_fee)));
11926 }
11927 }
11928 } else {
11929 if msg.fee_satoshis < our_min_fee {
11930 propose_fee!(our_min_fee);
11931 } else if msg.fee_satoshis > our_max_fee {
11932 propose_fee!(our_max_fee);
11933 } else {
11934 propose_fee!(msg.fee_satoshis);
11935 }
11936 }
11937 }
11938 }
11939
11940 #[rustfmt::skip]
11941 fn internal_htlc_satisfies_config(
11942 &self, htlc: &msgs::UpdateAddHTLC, amt_to_forward: u64, outgoing_cltv_value: u32, config: &ChannelConfig,
11943 ) -> Result<(), LocalHTLCFailureReason> {
11944 let fee = amt_to_forward.checked_mul(config.forwarding_fee_proportional_millionths as u64)
11945 .and_then(|prop_fee| (prop_fee / 1000000).checked_add(config.forwarding_fee_base_msat as u64));
11946 if fee.is_none() || htlc.amount_msat < fee.unwrap() ||
11947 (htlc.amount_msat - fee.unwrap()) < amt_to_forward {
11948 return Err(LocalHTLCFailureReason::FeeInsufficient);
11949 }
11950 if (htlc.cltv_expiry as u64) < outgoing_cltv_value as u64 + config.cltv_expiry_delta as u64 {
11951 return Err(LocalHTLCFailureReason::IncorrectCLTVExpiry);
11952 }
11953 Ok(())
11954 }
11955
11956 pub fn htlc_satisfies_config(
11960 &self, htlc: &msgs::UpdateAddHTLC, amt_to_forward: u64, outgoing_cltv_value: u32,
11961 ) -> Result<(), LocalHTLCFailureReason> {
11962 self.internal_htlc_satisfies_config(
11963 &htlc,
11964 amt_to_forward,
11965 outgoing_cltv_value,
11966 &self.context.config(),
11967 )
11968 .or_else(|err| {
11969 if let Some(prev_config) = self.context.prev_config() {
11970 self.internal_htlc_satisfies_config(
11971 htlc,
11972 amt_to_forward,
11973 outgoing_cltv_value,
11974 &prev_config,
11975 )
11976 } else {
11977 Err(err)
11978 }
11979 })
11980 }
11981
11982 #[rustfmt::skip]
11985 pub fn can_accept_incoming_htlc<F: FeeEstimator, L: Logger>(
11986 &self, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: L
11987 ) -> Result<(), LocalHTLCFailureReason> {
11988 if self.context.channel_state.is_local_shutdown_sent() {
11989 return Err(LocalHTLCFailureReason::ChannelClosed)
11990 }
11991
11992 let dust_exposure_limiting_feerate = self.context.get_dust_exposure_limiting_feerate(
11993 &fee_estimator, self.funding.get_channel_type(),
11994 );
11995
11996 core::iter::once(&self.funding)
11997 .chain(self.pending_funding())
11998 .try_for_each(|funding| self.context.can_accept_incoming_htlc(funding, dust_exposure_limiting_feerate, &logger))
11999 }
12000
12001 pub fn get_cur_holder_commitment_transaction_number(&self) -> u64 {
12002 self.holder_commitment_point.current_transaction_number()
12003 }
12004
12005 pub fn get_cur_counterparty_commitment_transaction_number(&self) -> u64 {
12006 self.context.counterparty_next_commitment_transaction_number + 1
12007 - if self.context.channel_state.is_awaiting_remote_revoke() { 1 } else { 0 }
12008 }
12009
12010 pub fn get_revoked_counterparty_commitment_transaction_number(&self) -> u64 {
12011 let ret = self.context.counterparty_next_commitment_transaction_number + 2;
12012 debug_assert_eq!(self.context.commitment_secrets.get_min_seen_secret(), ret);
12013 ret
12014 }
12015
12016 #[cfg(any(test, feature = "_externalize_tests"))]
12017 pub fn get_signer(&self) -> &SP::EcdsaSigner {
12018 &self.context.holder_signer
12019 }
12020
12021 #[cfg(any(test, feature = "_externalize_tests"))]
12022 #[rustfmt::skip]
12023 pub fn get_value_stat(&self) -> ChannelValueStat {
12024 ChannelValueStat {
12025 value_to_self_msat: self.funding.value_to_self_msat,
12026 channel_value_msat: self.funding.get_value_satoshis() * 1000,
12027 channel_reserve_msat: self.funding.counterparty_selected_channel_reserve_satoshis.unwrap() * 1000,
12028 pending_outbound_htlcs_amount_msat: self.context.pending_outbound_htlcs.iter().map(|ref h| h.amount_msat).sum::<u64>(),
12029 pending_inbound_htlcs_amount_msat: self.context.pending_inbound_htlcs.iter().map(|ref h| h.amount_msat).sum::<u64>(),
12030 holding_cell_outbound_amount_msat: {
12031 let mut res = 0;
12032 for h in self.context.holding_cell_htlc_updates.iter() {
12033 match h {
12034 &HTLCUpdateAwaitingACK::AddHTLC{amount_msat, .. } => {
12035 res += amount_msat;
12036 }
12037 _ => {}
12038 }
12039 }
12040 res
12041 },
12042 counterparty_max_htlc_value_in_flight_msat: self.context.counterparty_max_htlc_value_in_flight_msat,
12043 counterparty_dust_limit_msat: self.context.counterparty_dust_limit_satoshis * 1000,
12044 }
12045 }
12046
12047 pub fn is_awaiting_monitor_update(&self) -> bool {
12050 self.context.channel_state.is_monitor_update_in_progress()
12051 }
12052
12053 pub fn get_latest_unblocked_monitor_update_id(&self) -> u64 {
12055 self.context.get_latest_unblocked_monitor_update_id()
12056 }
12057
12058 pub fn unblock_next_blocked_monitor_update(&mut self) -> Option<(ChannelMonitorUpdate, bool)> {
12061 if self.context.blocked_monitor_updates.is_empty() {
12062 return None;
12063 }
12064 Some((
12065 self.context.blocked_monitor_updates.remove(0).update,
12066 !self.context.blocked_monitor_updates.is_empty(),
12067 ))
12068 }
12069
12070 #[rustfmt::skip]
12073 fn push_ret_blockable_mon_update(&mut self, update: ChannelMonitorUpdate)
12074 -> Option<ChannelMonitorUpdate> {
12075 let release_monitor = self.context.blocked_monitor_updates.is_empty();
12076 if !release_monitor {
12077 self.context.blocked_monitor_updates.push(PendingChannelMonitorUpdate {
12078 update,
12079 });
12080 None
12081 } else {
12082 Some(update)
12083 }
12084 }
12085
12086 pub fn on_startup_drop_completed_blocked_mon_updates_through<L: Logger>(
12090 &mut self, logger: &L, loaded_mon_update_id: u64,
12091 ) {
12092 self.context.blocked_monitor_updates.retain(|update| {
12093 if update.update.update_id <= loaded_mon_update_id {
12094 log_info!(
12095 logger,
12096 "Dropping completed ChannelMonitorUpdate id {} due to a stale ChannelManager",
12097 update.update.update_id,
12098 );
12099 false
12100 } else {
12101 true
12102 }
12103 });
12104 }
12105
12106 pub fn blocked_monitor_updates_pending(&self) -> usize {
12107 self.context.blocked_monitor_updates.len()
12108 }
12109
12110 #[rustfmt::skip]
12115 pub fn is_awaiting_initial_mon_persist(&self) -> bool {
12116 if !self.is_awaiting_monitor_update() { return false; }
12117 if matches!(
12118 self.context.channel_state, ChannelState::AwaitingChannelReady(flags)
12119 if flags.clone().clear(AwaitingChannelReadyFlags::THEIR_CHANNEL_READY | FundedStateFlags::PEER_DISCONNECTED | FundedStateFlags::MONITOR_UPDATE_IN_PROGRESS | AwaitingChannelReadyFlags::WAITING_FOR_BATCH).is_empty()
12120 ) {
12121 debug_assert!(self.context.minimum_depth.unwrap_or(1) > 0);
12124 return true;
12125 }
12126 if self.holder_commitment_point.next_transaction_number() == INITIAL_COMMITMENT_NUMBER - 1 &&
12127 self.context.counterparty_next_commitment_transaction_number == INITIAL_COMMITMENT_NUMBER - 1 {
12128 if self.funding.is_outbound() { assert!(self.funding.funding_transaction.is_some()); }
12141 assert!(self.context.monitor_pending_channel_ready);
12142 assert_eq!(self.context.latest_monitor_update_id, 0);
12143 return true;
12144 }
12145 false
12146 }
12147
12148 pub fn get_inbound_scid(&self) -> Option<u64> {
12151 self.context.latest_inbound_scid_alias.or(self.funding.get_short_channel_id())
12152 }
12153
12154 pub fn is_our_channel_ready(&self) -> bool {
12156 matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(flags) if flags.is_set(AwaitingChannelReadyFlags::OUR_CHANNEL_READY))
12157 || matches!(self.context.channel_state, ChannelState::ChannelReady(_))
12158 }
12159
12160 pub fn received_shutdown(&self) -> bool {
12162 self.context.channel_state.is_remote_shutdown_sent()
12163 }
12164
12165 pub fn sent_shutdown(&self) -> bool {
12167 self.context.channel_state.is_local_shutdown_sent()
12168 }
12169
12170 pub fn initiated_shutdown(&self) -> bool {
12172 self.context.local_initiated_shutdown.is_some()
12173 }
12174
12175 pub fn is_shutdown(&self) -> bool {
12179 matches!(self.context.channel_state, ChannelState::ShutdownComplete)
12180 }
12181
12182 pub fn is_shutdown_pending_signature(&self) -> bool {
12183 matches!(self.context.channel_state, ChannelState::ChannelReady(_))
12184 && self.context.signer_pending_closing
12185 && self.context.last_received_closing_sig.is_some()
12186 }
12187
12188 pub fn channel_update_status(&self) -> ChannelUpdateStatus {
12189 self.context.channel_update_status
12190 }
12191
12192 pub fn set_channel_update_status(&mut self, status: ChannelUpdateStatus) {
12193 self.context.update_time_counter += 1;
12194 self.context.channel_update_status = status;
12195 }
12196
12197 #[rustfmt::skip]
12198 fn check_get_channel_ready<L: Logger>(&mut self, height: u32, logger: &L) -> Option<msgs::ChannelReady> {
12199 if !self.check_funding_meets_minimum_depth(&self.funding, height) {
12203 return None;
12204 }
12205
12206 let need_commitment_update = if matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(f) if f.clone().clear(FundedStateFlags::ALL.into()).is_empty()) {
12209 self.context.channel_state.set_our_channel_ready();
12210 true
12211 } else if matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(f) if f.clone().clear(FundedStateFlags::ALL.into()) == AwaitingChannelReadyFlags::THEIR_CHANNEL_READY) {
12212 self.context.channel_state = ChannelState::ChannelReady(self.context.channel_state.with_funded_state_flags_mask().into());
12213 self.context.update_time_counter += 1;
12214 true
12215 } else if matches!(self.context.channel_state, ChannelState::AwaitingChannelReady(f) if f.clone().clear(FundedStateFlags::ALL.into()) == AwaitingChannelReadyFlags::OUR_CHANNEL_READY) {
12216 false
12218 } else {
12219 if self.funding.funding_tx_confirmation_height != 0 &&
12220 self.context.channel_state < ChannelState::ChannelReady(ChannelReadyFlags::new())
12221 {
12222 #[cfg(not(fuzzing))]
12227 panic!("Started confirming a channel in a state pre-AwaitingChannelReady: {}.\n\
12228 Do NOT broadcast a funding transaction manually - let LDK do it for you!",
12229 self.context.channel_state.to_u32());
12230 }
12231 false
12233 };
12234
12235 if !need_commitment_update {
12236 log_debug!(logger, "Not producing channel_ready: we do not need a commitment update");
12237 return None;
12238 }
12239
12240 if self.context.channel_state.is_monitor_update_in_progress() {
12241 log_debug!(logger, "Not producing channel_ready: a monitor update is in progress. Setting monitor_pending_channel_ready.");
12242 self.context.monitor_pending_channel_ready = true;
12243 return None;
12244 }
12245
12246 if self.context.channel_state.is_peer_disconnected() {
12247 log_debug!(logger, "Not producing channel_ready: the peer is disconnected.");
12248 return None;
12249 }
12250
12251 self.get_channel_ready(logger)
12252 }
12253
12254 #[rustfmt::skip]
12255 fn get_channel_ready<L: Logger>(
12256 &mut self, logger: &L
12257 ) -> Option<msgs::ChannelReady> {
12258 if self.holder_commitment_point.can_advance() {
12259 self.context.signer_pending_channel_ready = false;
12260 Some(msgs::ChannelReady {
12261 channel_id: self.context.channel_id(),
12262 next_per_commitment_point: self.holder_commitment_point.next_point(),
12263 short_channel_id_alias: Some(self.context.outbound_scid_alias),
12264 })
12265 } else {
12266 log_debug!(logger, "Not producing channel_ready: the holder commitment point is not available.");
12267 self.context.signer_pending_channel_ready = true;
12268 None
12269 }
12270 }
12271
12272 fn check_funding_meets_minimum_depth(&self, funding: &FundingScope, height: u32) -> bool {
12273 self.context.check_funding_meets_minimum_depth(funding, height)
12274 }
12275
12276 fn maybe_promote_splice_funding<NS: NodeSigner, L: Logger>(
12278 &mut self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig,
12279 block_height: u32, logger: &L,
12280 ) -> Option<SpliceFundingPromotion> {
12281 let pending_splice = self.pending_splice.as_mut()?;
12282 let splice_txid = pending_splice.sent_funding_txid?;
12283 if let Some(received_funding_txid) = pending_splice.received_funding_txid {
12284 if splice_txid != received_funding_txid {
12285 log_warn!(
12286 logger,
12287 "Mismatched splice_locked txid for channel {}; sent txid {}; received txid {}",
12288 &self.context.channel_id,
12289 splice_txid,
12290 received_funding_txid,
12291 );
12292 return None;
12293 }
12294 } else {
12295 log_info!(logger, "Waiting on splice_locked txid {}", splice_txid);
12296 return None;
12297 }
12298
12299 log_info!(logger, "Promoting splice funding txid {}", splice_txid);
12300
12301 let (queued_splice_failed, earlier_contributions, later_contributions) = {
12302 let promoted_candidate_idx = pending_splice
12303 .negotiated_candidates
12304 .iter()
12305 .position(|candidate| candidate.funding.get_funding_txid() == Some(splice_txid))
12306 .unwrap();
12307
12308 let promoted_tx = pending_splice.negotiated_candidates[promoted_candidate_idx]
12309 .funding
12310 .funding_transaction
12311 .as_ref()
12312 .expect("Promoted splice funding should have a funding transaction");
12313
12314 let is_queued_contribution_conflicting = match self.quiescent_action.as_ref() {
12315 Some(QuiescentAction::Splice { contribution, .. }) => {
12316 contribution.contributed_inputs().any(|input| {
12317 promoted_tx.input.iter().any(|promoted| input == promoted.previous_output)
12318 }) || contribution.contributed_outputs().any(|output| {
12319 promoted_tx
12320 .output
12321 .iter()
12322 .any(|promoted| output == promoted.script_pubkey.as_script())
12323 })
12324 },
12325 _ => false,
12326 };
12327 let queued_splice_failed = if is_queued_contribution_conflicting {
12328 #[allow(irrefutable_let_patterns)]
12329 let QuiescentAction::Splice { contribution, .. } = self
12330 .quiescent_action
12331 .take()
12332 .expect("We just checked a conflicting queued contribution exists above")
12333 else {
12334 unreachable!()
12335 };
12336 Some(SpliceFundingFailed::from_contribution(contribution))
12341 } else {
12342 if let Some(QuiescentAction::Splice { contribution, .. }) =
12346 self.quiescent_action.as_mut()
12347 {
12348 contribution.clear_pending_components();
12349 }
12350 None
12351 };
12352
12353 if let Some(scid) = self.funding.short_channel_id {
12354 self.context.historical_scids.push(scid);
12355 }
12356 let mut candidates =
12360 core::mem::take(&mut pending_splice.negotiated_candidates).into_iter();
12361 let earlier_contributions: Vec<FundingContribution> = candidates
12362 .by_ref()
12363 .take(promoted_candidate_idx)
12364 .filter_map(|candidate| candidate.contribution)
12365 .collect();
12366 let mut promoted_candidate =
12367 candidates.next().expect("promoted_candidate_idx indexes the candidates");
12368 let later_contributions: Vec<FundingContribution> =
12369 candidates.filter_map(|candidate| candidate.contribution).collect();
12370 core::mem::swap(&mut self.funding, &mut promoted_candidate.funding);
12371
12372 (queued_splice_failed, earlier_contributions, later_contributions)
12373 };
12374
12375 let discarded_funding = {
12376 let promoted_tx = self
12377 .funding
12378 .funding_transaction
12379 .as_ref()
12380 .expect("Promoted splice funding should have a funding transaction");
12381 let queued_contribution = match self.quiescent_action.as_ref() {
12382 Some(QuiescentAction::Splice { contribution, .. }) => Some(contribution),
12383 _ => None,
12384 };
12385 let queued_inputs = || {
12386 queued_contribution
12387 .into_iter()
12388 .flat_map(|contribution| contribution.contributed_inputs())
12389 };
12390 let queued_output_scripts = || {
12391 queued_contribution
12392 .into_iter()
12393 .flat_map(|contribution| contribution.contributed_outputs())
12394 };
12395
12396 let earlier_released = earlier_contributions.into_iter().filter_map(|contribution| {
12407 contribution.into_unique_contributions(
12408 promoted_tx.input.iter().map(|i| i.previous_output).chain(queued_inputs()),
12409 promoted_tx
12410 .output
12411 .iter()
12412 .map(|o| o.script_pubkey.as_script())
12413 .chain(queued_output_scripts()),
12414 )
12415 });
12416 let pending_negotiation_contribution = pending_splice.negotiation_contribution.take();
12417 let later_released = later_contributions
12418 .into_iter()
12419 .chain(pending_negotiation_contribution)
12420 .filter_map(|contribution| {
12421 contribution.into_unique_contributions(queued_inputs(), queued_output_scripts())
12422 });
12423 earlier_released
12424 .chain(later_released)
12425 .map(|(inputs, outputs)| FundingInfo::Contribution {
12426 inputs,
12427 outputs: outputs.into_iter().map(|output| output.script_pubkey).collect(),
12428 })
12429 .collect::<Vec<_>>()
12430 };
12431
12432 self.context.interactive_tx_signing_session = None;
12433 self.pending_splice = None;
12434 self.context.announcement_sigs = None;
12435 self.context.announcement_sigs_state = AnnouncementSigsState::NotSent;
12436
12437 let funding_txo = self
12438 .funding
12439 .get_funding_txo()
12440 .expect("Splice FundingScope should always have a funding_txo");
12441
12442 self.context.latest_monitor_update_id += 1;
12443 let monitor_update = ChannelMonitorUpdate {
12444 update_id: self.context.latest_monitor_update_id,
12445 updates: vec![ChannelMonitorUpdateStep::RenegotiatedFundingLocked {
12446 funding_txid: funding_txo.txid,
12447 }],
12448 channel_id: Some(self.context.channel_id()),
12449 };
12450 self.monitor_updating_paused(
12451 false,
12452 false,
12453 false,
12454 Vec::new(),
12455 Vec::new(),
12456 Vec::new(),
12457 logger,
12458 );
12459 let monitor_update = self.push_ret_blockable_mon_update(monitor_update);
12460
12461 let announcement_sigs =
12462 self.get_announcement_sigs(node_signer, chain_hash, user_config, block_height, logger);
12463
12464 Some(SpliceFundingPromotion {
12465 funding_txo,
12466 monitor_update,
12467 announcement_sigs,
12468 discarded_funding,
12469 splice_funding_failed: queued_splice_failed,
12470 })
12471 }
12472
12473 pub fn timer_check_splice_locked<NS: NodeSigner, L: Logger>(
12476 &mut self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig,
12477 best_block_height: u32, logger: &L,
12478 ) -> Option<(msgs::SpliceLocked, Option<SpliceFundingPromotion>)> {
12479 if self.context.channel_state.is_quiescent() {
12482 return None;
12483 }
12484
12485 let candidate_idx = {
12486 let pending_splice = self.pending_splice.as_ref()?;
12487 pending_splice.negotiated_candidates.iter().rposition(|candidate| {
12488 self.context
12489 .check_funding_meets_minimum_depth(&candidate.funding, best_block_height)
12490 })?
12491 };
12492
12493 let splice_locked = self.pending_splice.as_mut()?.check_get_splice_locked(
12494 &self.context,
12495 candidate_idx,
12496 best_block_height,
12497 )?;
12498 log_info!(
12499 logger,
12500 "Sending splice_locked txid {} after completing funding negotiation",
12501 splice_locked.splice_txid,
12502 );
12503
12504 let splice_promotion = self.maybe_promote_splice_funding(
12505 node_signer,
12506 chain_hash,
12507 user_config,
12508 best_block_height,
12509 logger,
12510 );
12511 Some((splice_locked, splice_promotion))
12512 }
12513
12514 #[rustfmt::skip]
12518 pub fn transactions_confirmed<NS: NodeSigner, L: Logger>(
12519 &mut self, block_hash: &BlockHash, tx_confirmation_height: u32, best_block_height: u32,
12520 txdata: &TransactionData,
12521 chain_hash: ChainHash, node_signer: &NS, user_config: &UserConfig, logger: &L
12522 ) -> Result<(Option<FundingConfirmedMessage>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>, Option<SpliceRbfAbort>), ClosureReason> {
12523 let timed_out_htlcs = self.remove_timed_out_holding_cell_htlcs(cmp::max(
12526 tx_confirmation_height,
12527 best_block_height,
12528 ));
12529 let mut splice_rbf_abort = None;
12530 for &(index_in_block, tx) in txdata.iter() {
12531 let mut confirmed_tx = ConfirmedTransaction::from(tx);
12532
12533 let is_funding_tx_confirmed = self.context.check_for_funding_tx_confirmed(
12537 &mut self.funding, block_hash, tx_confirmation_height, index_in_block, &mut confirmed_tx, logger,
12538 )?;
12539
12540 if is_funding_tx_confirmed {
12541 if tx.is_coinbase() &&
12544 self.context.minimum_depth.unwrap_or(0) > 0 &&
12545 self.context.minimum_depth.unwrap_or(0) < COINBASE_MATURITY {
12546 self.funding.minimum_depth_override = Some(COINBASE_MATURITY);
12547 }
12548
12549 if let Some(channel_ready) = self.check_get_channel_ready(tx_confirmation_height, logger) {
12550 log_info!(logger, "Sending a channel_ready to our peer");
12551 let announcement_sigs = self.get_announcement_sigs(node_signer, chain_hash, user_config, tx_confirmation_height, logger);
12552 return Ok((Some(FundingConfirmedMessage::Establishment(channel_ready)), timed_out_htlcs, announcement_sigs, splice_rbf_abort));
12553 }
12554 }
12555
12556 let confirmed_funding_index = if let Some(pending_splice) = &mut self.pending_splice {
12557 let mut confirmed_funding_index = None;
12558 let mut funding_already_confirmed = false;
12559
12560 let candidates =
12561 pending_splice.negotiated_candidates.iter_mut().map(|candidate| &mut candidate.funding);
12562 for (index, funding) in candidates.enumerate() {
12563 if self.context.check_for_funding_tx_confirmed(
12564 funding, block_hash, tx_confirmation_height, index_in_block, &mut confirmed_tx, logger,
12565 )? {
12566 if funding_already_confirmed || confirmed_funding_index.is_some() {
12567 let err_reason = "splice tx of another pending funding already confirmed";
12568 return Err(ClosureReason::ProcessingError { err: err_reason.to_owned() });
12569 }
12570
12571 confirmed_funding_index = Some(index);
12572 } else if funding.funding_tx_confirmation_height != 0 {
12573 funding_already_confirmed = true;
12574 }
12575 }
12576
12577 confirmed_funding_index
12578 } else {
12579 None
12580 };
12581
12582 if let Some(confirmed_funding_index) = confirmed_funding_index {
12583 splice_rbf_abort = self.abort_ongoing_rbf_after_splice_confirmation(logger);
12584 if let Some(pending_splice) = &mut self.pending_splice {
12585 if let Some(splice_locked) = pending_splice.check_get_splice_locked(
12586 &self.context,
12587 confirmed_funding_index,
12588 tx_confirmation_height,
12589 ) {
12590
12591 log_info!(
12592 logger,
12593 "Sending splice_locked txid {} to our peer for channel {}",
12594 splice_locked.splice_txid,
12595 &self.context.channel_id,
12596 );
12597
12598 let (
12599 funding_txo,
12600 monitor_update,
12601 announcement_sigs,
12602 discarded_funding,
12603 splice_funding_failed,
12604 ) =
12605 self.maybe_promote_splice_funding(
12606 node_signer, chain_hash, user_config, tx_confirmation_height, logger,
12607 ).map(|splice_promotion| (
12608 Some(splice_promotion.funding_txo),
12609 splice_promotion.monitor_update,
12610 splice_promotion.announcement_sigs,
12611 splice_promotion.discarded_funding,
12612 splice_promotion.splice_funding_failed,
12613 )).unwrap_or((None, None, None, Vec::new(), None));
12614
12615 return Ok((Some(FundingConfirmedMessage::Splice(
12616 splice_locked,
12617 funding_txo,
12618 monitor_update,
12619 discarded_funding,
12620 splice_funding_failed,
12621 )), timed_out_htlcs, announcement_sigs, splice_rbf_abort));
12622 }
12623 }
12624 }
12625
12626 }
12627
12628 Ok((None, timed_out_htlcs, None, splice_rbf_abort))
12629 }
12630
12631 pub fn best_block_updated<NS: NodeSigner, L: Logger>(
12643 &mut self, height: u32, highest_header_time: Option<u32>, chain_hash: ChainHash,
12644 node_signer: &NS, user_config: &UserConfig, logger: &L,
12645 ) -> Result<BestBlockUpdatedRes, ClosureReason> {
12646 self.do_best_block_updated(
12647 height,
12648 highest_header_time,
12649 Some((chain_hash, node_signer, user_config)),
12650 logger,
12651 )
12652 }
12653
12654 fn remove_timed_out_holding_cell_htlcs(
12656 &mut self, height: u32,
12657 ) -> Vec<(HTLCSource, PaymentHash)> {
12658 let mut timed_out_htlcs = Vec::new();
12659 let unforwarded_htlc_cltv_limit = height + LATENCY_GRACE_PERIOD_BLOCKS;
12662 self.context.holding_cell_htlc_updates.retain(|htlc_update| match htlc_update {
12663 &HTLCUpdateAwaitingACK::AddHTLC {
12664 ref payment_hash,
12665 ref source,
12666 ref cltv_expiry,
12667 ..
12668 } => {
12669 if *cltv_expiry <= unforwarded_htlc_cltv_limit {
12670 timed_out_htlcs.push((source.clone(), payment_hash.clone()));
12671 false
12672 } else {
12673 true
12674 }
12675 },
12676 _ => true,
12677 });
12678 timed_out_htlcs
12679 }
12680
12681 #[rustfmt::skip]
12682 fn do_best_block_updated<NS: NodeSigner, L: Logger>(
12683 &mut self, height: u32, highest_header_time: Option<u32>,
12684 chain_node_signer: Option<(ChainHash, &NS, &UserConfig)>, logger: &L
12685 ) -> Result<BestBlockUpdatedRes, ClosureReason> {
12686 let timed_out_htlcs = self.remove_timed_out_holding_cell_htlcs(height);
12687
12688 if let Some(time) = highest_header_time {
12689 self.context.update_time_counter = cmp::max(self.context.update_time_counter, time);
12690 }
12691
12692 let original_scid = self.funding.short_channel_id;
12694 let was_confirmed = self.funding.funding_tx_confirmed_in.is_some();
12695 let funding_tx_confirmations = self.funding.get_funding_tx_confirmations(height);
12696 if funding_tx_confirmations == 0 {
12697 self.funding.funding_tx_confirmation_height = 0;
12698 self.funding.short_channel_id = None;
12699 self.funding.funding_tx_confirmed_in = None;
12700 }
12701
12702 if let Some(channel_ready) = self.check_get_channel_ready(height, logger) {
12703 let announcement_sigs = if let Some((chain_hash, node_signer, user_config)) = chain_node_signer {
12704 self.get_announcement_sigs(node_signer, chain_hash, user_config, height, logger)
12705 } else { None };
12706 log_info!(logger, "Sending a channel_ready to our peer");
12707 return Ok((Some(FundingConfirmedMessage::Establishment(channel_ready)), timed_out_htlcs, announcement_sigs, None));
12708 }
12709
12710 if matches!(self.context.channel_state, ChannelState::ChannelReady(_)) ||
12711 self.context.channel_state.is_our_channel_ready() {
12712
12713 if funding_tx_confirmations == 0 && was_confirmed {
12728 if let Some(scid) = original_scid {
12729 self.context.historical_scids.push(scid);
12730 } else {
12731 debug_assert!(false);
12732 }
12733 if self.context.minimum_depth(&self.funding).expect("set for a ready channel") > 0 {
12734 self.funding.short_channel_id = original_scid;
12737 let err_reason = format!("Funding transaction was un-confirmed, originally locked at {} confs.",
12738 self.context.minimum_depth.unwrap());
12739 return Err(ClosureReason::ProcessingError { err: err_reason });
12740 }
12741 }
12742 } else if !self.funding.is_outbound() && self.funding.funding_tx_confirmed_in.is_none() &&
12743 height >= self.context.channel_creation_height + FUNDING_CONF_DEADLINE_BLOCKS {
12744 log_info!(logger, "Closing channel due to funding timeout");
12745 assert!(self.context.channel_state <= ChannelState::ChannelReady(ChannelReadyFlags::new()));
12747 assert!(!self.context.channel_state.is_our_channel_ready());
12748 return Err(ClosureReason::FundingTimedOut);
12749 }
12750
12751 if let Some(pending_splice) = &mut self.pending_splice {
12752 let mut confirmed_funding_index = None;
12753
12754 let candidates = pending_splice.negotiated_candidates.iter().map(|candidate| &candidate.funding);
12755 for (index, funding) in candidates.enumerate() {
12756 if funding.funding_tx_confirmation_height != 0 {
12757 if confirmed_funding_index.is_some() {
12758 let err_reason = "splice tx of another pending funding already confirmed";
12759 return Err(ClosureReason::ProcessingError { err: err_reason.to_owned() });
12760 }
12761
12762 confirmed_funding_index = Some(index);
12763 }
12764 }
12765
12766 if let Some(confirmed_funding_index) = confirmed_funding_index {
12767 let funding =
12768 &mut pending_splice.negotiated_candidates[confirmed_funding_index].funding;
12769
12770 if funding.get_funding_tx_confirmations(height) == 0 {
12772 funding.funding_tx_confirmation_height = 0;
12773 if let Some(sent_funding_txid) = pending_splice.sent_funding_txid {
12774 if Some(sent_funding_txid) == funding.get_funding_txid() {
12775 log_warn!(
12776 logger,
12777 "Unconfirming sent splice_locked txid {} for channel {}",
12778 sent_funding_txid,
12779 &self.context.channel_id,
12780 );
12781 pending_splice.sent_funding_txid = None;
12782 }
12783 }
12784 }
12785
12786 if let Some(splice_locked) = pending_splice.check_get_splice_locked(
12787 &self.context,
12788 confirmed_funding_index,
12789 height,
12790 ) {
12791 log_info!(
12792 logger, "Sending splice_locked txid {} to our peer",
12793 splice_locked.splice_txid,
12794
12795 );
12796
12797 let (
12798 funding_txo,
12799 monitor_update,
12800 announcement_sigs,
12801 discarded_funding,
12802 splice_funding_failed,
12803 ) = chain_node_signer
12804 .and_then(|(chain_hash, node_signer, user_config)| {
12805 self.maybe_promote_splice_funding(node_signer, chain_hash, user_config, height, logger)
12808 })
12809 .map(|splice_promotion| (
12810 Some(splice_promotion.funding_txo),
12811 splice_promotion.monitor_update,
12812 splice_promotion.announcement_sigs,
12813 splice_promotion.discarded_funding,
12814 splice_promotion.splice_funding_failed,
12815 ))
12816 .unwrap_or((None, None, None, Vec::new(), None));
12817
12818 return Ok((Some(FundingConfirmedMessage::Splice(
12819 splice_locked,
12820 funding_txo,
12821 monitor_update,
12822 discarded_funding,
12823 splice_funding_failed,
12824 )), timed_out_htlcs, announcement_sigs, None));
12825 }
12826 }
12827 }
12828
12829 let announcement_sigs = if let Some((chain_hash, node_signer, user_config)) = chain_node_signer {
12830 self.get_announcement_sigs(node_signer, chain_hash, user_config, height, logger)
12831 } else { None };
12832 Ok((None, timed_out_htlcs, announcement_sigs, None))
12833 }
12834
12835 pub fn get_relevant_txids(&self) -> impl Iterator<Item = (Txid, u32, Option<BlockHash>)> + '_ {
12836 core::iter::once(&self.funding)
12837 .chain(self.pending_funding())
12838 .map(|funding| {
12839 (
12840 funding.get_funding_txid(),
12841 funding.get_funding_tx_confirmation_height(),
12842 funding.funding_tx_confirmed_in,
12843 )
12844 })
12845 .filter_map(|(txid_opt, height_opt, hash_opt)| {
12846 if let (Some(funding_txid), Some(conf_height), Some(block_hash)) =
12847 (txid_opt, height_opt, hash_opt)
12848 {
12849 Some((funding_txid, conf_height, Some(block_hash)))
12850 } else {
12851 None
12852 }
12853 })
12854 }
12855
12856 #[rustfmt::skip]
12861 pub fn transaction_unconfirmed<L: Logger>(
12862 &mut self, txid: &Txid, logger: &L,
12863 ) -> Result<(), ClosureReason> {
12864 let unconfirmed_funding = self
12865 .funding_and_pending_funding_iter_mut()
12866 .find(|funding| funding.get_funding_txid() == Some(*txid));
12867
12868 if let Some(funding) = unconfirmed_funding {
12869 if funding.funding_tx_confirmation_height != 0 {
12870 let reorg_height = funding.funding_tx_confirmation_height - 1;
12873
12874 let signer_config = None::<(ChainHash, &&dyn NodeSigner, &UserConfig)>;
12875 match self.do_best_block_updated(reorg_height, None, signer_config, logger) {
12876 Ok((channel_ready, timed_out_htlcs, announcement_sigs, splice_rbf_abort)) => {
12877 assert!(channel_ready.is_none(), "We can't generate a funding with 0 confirmations?");
12878 assert!(timed_out_htlcs.is_empty(), "We can't have accepted HTLCs with a timeout before our funding confirmation?");
12879 assert!(announcement_sigs.is_none(), "We can't generate an announcement_sigs with 0 confirmations?");
12880 assert!(splice_rbf_abort.is_none(), "We can't abort an RBF while unconfirming funding?");
12881 Ok(())
12882 },
12883 Err(e) => Err(e),
12884 }
12885 } else {
12886 Ok(())
12888 }
12889 } else {
12890 Ok(())
12891 }
12892 }
12893
12894 #[rustfmt::skip]
12909 fn get_channel_announcement<NS: NodeSigner>(
12910 &self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig,
12911 ) -> Result<msgs::UnsignedChannelAnnouncement, ChannelError> {
12912 if !self.context.config.announce_for_forwarding {
12913 return Err(ChannelError::Ignore("Channel is not available for public announcements".to_owned()));
12914 }
12915 if !self.context.is_usable() {
12916 return Err(ChannelError::Ignore("Cannot get a ChannelAnnouncement if the channel is not currently usable".to_owned()));
12917 }
12918
12919 let short_channel_id = self.funding.get_short_channel_id()
12920 .ok_or(ChannelError::Ignore("Cannot get a ChannelAnnouncement if the channel has not been confirmed yet".to_owned()))?;
12921 let node_id = NodeId::from_pubkey(&node_signer.get_node_id(Recipient::Node)
12922 .map_err(|_| ChannelError::Ignore("Failed to retrieve own public key".to_owned()))?);
12923 let counterparty_node_id = NodeId::from_pubkey(&self.context.get_counterparty_node_id());
12924 let were_node_one = node_id.as_slice() < counterparty_node_id.as_slice();
12925
12926 let msg = msgs::UnsignedChannelAnnouncement {
12927 features: channelmanager::provided_channel_features(&user_config),
12928 chain_hash,
12929 short_channel_id,
12930 node_id_1: if were_node_one { node_id } else { counterparty_node_id },
12931 node_id_2: if were_node_one { counterparty_node_id } else { node_id },
12932 bitcoin_key_1: NodeId::from_pubkey(if were_node_one { &self.funding.get_holder_pubkeys().funding_pubkey } else { self.funding.counterparty_funding_pubkey() }),
12933 bitcoin_key_2: NodeId::from_pubkey(if were_node_one { self.funding.counterparty_funding_pubkey() } else { &self.funding.get_holder_pubkeys().funding_pubkey }),
12934 excess_data: Vec::new(),
12935 };
12936
12937 Ok(msg)
12938 }
12939
12940 #[rustfmt::skip]
12941 fn get_announcement_sigs<NS: NodeSigner, L: Logger>(
12942 &mut self, node_signer: &NS, chain_hash: ChainHash, user_config: &UserConfig,
12943 best_block_height: u32, logger: &L
12944 ) -> Option<msgs::AnnouncementSignatures> {
12945 if self.funding.funding_tx_confirmation_height == 0 || self.funding.funding_tx_confirmation_height + 5 > best_block_height {
12946 return None;
12947 }
12948
12949 if !self.context.is_usable() {
12950 return None;
12951 }
12952
12953 if self.context.channel_state.is_peer_disconnected() {
12954 log_trace!(logger, "Cannot create an announcement_signatures as our peer is disconnected");
12955 return None;
12956 }
12957
12958 if self.context.announcement_sigs_state != AnnouncementSigsState::NotSent {
12959 return None;
12960 }
12961
12962 log_trace!(logger, "Creating an announcement_signatures message");
12963 let announcement = match self.get_channel_announcement(node_signer, chain_hash, user_config) {
12964 Ok(a) => a,
12965 Err(e) => {
12966 log_trace!(logger, "{:?}", e);
12967 return None;
12968 }
12969 };
12970 let our_node_sig = match node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelAnnouncement(&announcement)) {
12971 Err(_) => {
12972 log_error!(logger, "Failed to generate node signature for channel_announcement. Channel will not be announced!");
12973 return None;
12974 },
12975 Ok(v) => v
12976 };
12977 let our_bitcoin_sig = match self.context.holder_signer.sign_channel_announcement_with_funding_key(
12978 &self.funding.channel_transaction_parameters,
12979 &announcement,
12980 &self.context.secp_ctx,
12981 ) {
12982 Err(_) => {
12983 log_error!(logger, "Signer rejected channel_announcement signing. Channel will not be announced!");
12984 return None;
12985 },
12986 Ok(v) => v
12987 };
12988 let short_channel_id = match self.funding.get_short_channel_id() {
12989 Some(scid) => scid,
12990 None => return None,
12991 };
12992
12993 self.context.announcement_sigs_state = AnnouncementSigsState::MessageSent;
12994
12995 Some(msgs::AnnouncementSignatures {
12996 channel_id: self.context.channel_id(),
12997 short_channel_id,
12998 node_signature: our_node_sig,
12999 bitcoin_signature: our_bitcoin_sig,
13000 })
13001 }
13002
13003 #[rustfmt::skip]
13006 fn sign_channel_announcement<NS: NodeSigner>(
13007 &self, node_signer: &NS, announcement: msgs::UnsignedChannelAnnouncement
13008 ) -> Result<msgs::ChannelAnnouncement, ChannelError> {
13009 if let Some((their_node_sig, their_bitcoin_sig)) = self.context.announcement_sigs {
13010 let our_node_key = NodeId::from_pubkey(&node_signer.get_node_id(Recipient::Node)
13011 .map_err(|_| ChannelError::Ignore("Signer failed to retrieve own public key".to_owned()))?);
13012 let were_node_one = announcement.node_id_1 == our_node_key;
13013
13014 let our_node_sig = node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelAnnouncement(&announcement))
13015 .map_err(|_| ChannelError::Ignore("Failed to generate node signature for channel_announcement".to_owned()))?;
13016 let our_bitcoin_sig = self.context.holder_signer
13017 .sign_channel_announcement_with_funding_key(
13018 &self.funding.channel_transaction_parameters,
13019 &announcement,
13020 &self.context.secp_ctx,
13021 )
13022 .map_err(|_| ChannelError::Ignore("Signer rejected channel_announcement".to_owned()))?;
13023 Ok(msgs::ChannelAnnouncement {
13024 node_signature_1: if were_node_one { our_node_sig } else { their_node_sig },
13025 node_signature_2: if were_node_one { their_node_sig } else { our_node_sig },
13026 bitcoin_signature_1: if were_node_one { our_bitcoin_sig } else { their_bitcoin_sig },
13027 bitcoin_signature_2: if were_node_one { their_bitcoin_sig } else { our_bitcoin_sig },
13028 contents: announcement,
13029 })
13030 } else {
13031 Err(ChannelError::Ignore("Attempted to sign channel announcement before we'd received announcement_signatures".to_string()))
13032 }
13033 }
13034
13035 #[rustfmt::skip]
13039 pub fn announcement_signatures<NS: NodeSigner>(
13040 &mut self, node_signer: &NS, chain_hash: ChainHash, best_block_height: u32,
13041 msg: &msgs::AnnouncementSignatures, user_config: &UserConfig
13042 ) -> Result<msgs::ChannelAnnouncement, ChannelError> {
13043 if Some(msg.short_channel_id) != self.funding.get_short_channel_id() {
13048 return Err(ChannelError::Ignore(format!(
13049 "Ignoring announcement_signatures for short_channel_id {} which does not match our current short_channel_id {:?}",
13050 msg.short_channel_id, self.funding.get_short_channel_id(),
13051 )));
13052 }
13053
13054 let announcement = self.get_channel_announcement(node_signer, chain_hash, user_config)?;
13055
13056 let msghash = hash_to_message!(&Sha256d::hash(&announcement.encode()[..])[..]);
13057
13058 if self.context.secp_ctx.verify_ecdsa(&msghash, &msg.node_signature, &self.context.get_counterparty_node_id()).is_err() {
13059 return Err(ChannelError::close(format!(
13060 "Bad announcement_signatures. Failed to verify node_signature. UnsignedChannelAnnouncement used for verification is {:?}. their_node_key is {:?}",
13061 &announcement, self.context.get_counterparty_node_id())));
13062 }
13063 if self.context.secp_ctx.verify_ecdsa(&msghash, &msg.bitcoin_signature, self.funding.counterparty_funding_pubkey()).is_err() {
13064 return Err(ChannelError::close(format!(
13065 "Bad announcement_signatures. Failed to verify bitcoin_signature. UnsignedChannelAnnouncement used for verification is {:?}. their_bitcoin_key is ({:?})",
13066 &announcement, self.funding.counterparty_funding_pubkey())));
13067 }
13068
13069 self.context.announcement_sigs = Some((msg.node_signature, msg.bitcoin_signature));
13070 if self.funding.funding_tx_confirmation_height == 0 || self.funding.funding_tx_confirmation_height + 5 > best_block_height {
13071 return Err(ChannelError::Ignore(
13072 "Got announcement_signatures prior to the required six confirmations - we may not have received a block yet that our peer has".to_owned()));
13073 }
13074
13075 self.sign_channel_announcement(node_signer, announcement)
13076 }
13077
13078 #[rustfmt::skip]
13081 pub fn get_signed_channel_announcement<NS: NodeSigner>(
13082 &self, node_signer: &NS, chain_hash: ChainHash, best_block_height: u32, user_config: &UserConfig
13083 ) -> Option<msgs::ChannelAnnouncement> {
13084 if self.funding.funding_tx_confirmation_height == 0 || self.funding.funding_tx_confirmation_height + 5 > best_block_height {
13085 return None;
13086 }
13087 let announcement = match self.get_channel_announcement(node_signer, chain_hash, user_config) {
13088 Ok(res) => res,
13089 Err(_) => return None,
13090 };
13091 self.sign_channel_announcement(node_signer, announcement).ok()
13092 }
13093
13094 fn maybe_get_next_funding(&self) -> Option<msgs::NextFunding> {
13095 self.context
13099 .interactive_tx_signing_session
13100 .as_ref()
13101 .filter(|session| !session.has_received_tx_signatures())
13102 .map(|signing_session| {
13103 let mut next_funding = msgs::NextFunding {
13106 txid: signing_session.unsigned_tx().compute_txid(),
13107 retransmit_flags: 0,
13108 };
13109
13110 if !signing_session.has_received_commitment_signed() {
13113 next_funding.retransmit(msgs::NextFundingFlag::CommitmentSigned);
13114 }
13115
13116 next_funding
13117 })
13118 }
13121
13122 fn maybe_get_my_current_funding_locked(&self) -> Option<msgs::FundingLocked> {
13123 self.pending_splice
13124 .as_ref()
13125 .and_then(|pending| pending.sent_funding_txid)
13126 .or_else(|| {
13127 self.is_our_channel_ready().then(|| self.funding.get_funding_txid()).flatten()
13128 })
13129 .map(|txid| {
13130 let mut funding_locked = msgs::FundingLocked { txid, retransmit_flags: 0 };
13131
13132 if self.context.config.announce_for_forwarding {
13139 if self.funding.get_funding_txid() != Some(txid)
13140 || self.context.announcement_sigs.is_none()
13141 {
13142 funding_locked.retransmit(msgs::FundingLockedFlags::AnnouncementSignatures);
13143 }
13144 }
13145
13146 funding_locked
13147 })
13148 }
13149
13150 #[rustfmt::skip]
13153 fn get_channel_reestablish<L: Logger>(&mut self, logger: &L) -> msgs::ChannelReestablish {
13154 assert!(self.context.channel_state.is_peer_disconnected());
13155 assert_ne!(self.context.counterparty_next_commitment_transaction_number, INITIAL_COMMITMENT_NUMBER);
13156 self.holder_commitment_point.try_resolve_pending(
13160 &self.context.holder_signer, &self.context.secp_ctx, logger,
13161 );
13162 let mut pk = [2; 33]; pk[1] = 0xff;
13169 let dummy_pubkey = PublicKey::from_slice(&pk).unwrap();
13170 let remote_last_secret = if self.context.counterparty_next_commitment_transaction_number + 1 < INITIAL_COMMITMENT_NUMBER {
13171 let remote_last_secret = self.context.commitment_secrets.get_secret(self.context.counterparty_next_commitment_transaction_number + 2).unwrap();
13172 log_trace!(logger, "Enough info to generate a Data Loss Protect with per_commitment_secret {}", log_bytes!(remote_last_secret));
13173 remote_last_secret
13174 } else {
13175 log_info!(logger, "Sending a data_loss_protect with no previous remote per_commitment_secret for channel {}", &self.context.channel_id());
13176 [0;32]
13177 };
13178 let my_current_funding_locked = self.maybe_get_my_current_funding_locked();
13179 self.context.funding_locked_txid_sent_in_reestablish =
13180 my_current_funding_locked.as_ref().map(|funding_locked| funding_locked.txid);
13181 msgs::ChannelReestablish {
13182 channel_id: self.context.channel_id(),
13183 next_local_commitment_number: INITIAL_COMMITMENT_NUMBER - self.holder_commitment_point.next_transaction_number(),
13193 next_remote_commitment_number: INITIAL_COMMITMENT_NUMBER - self.context.counterparty_next_commitment_transaction_number - 1,
13201 your_last_per_commitment_secret: remote_last_secret,
13202 my_current_per_commitment_point: dummy_pubkey,
13203 next_funding: self.maybe_get_next_funding(),
13204 my_current_funding_locked,
13205 }
13206 }
13207
13208 pub fn splice_channel(&self) -> Result<FundingTemplate, APIError> {
13210 if self.holder_commitment_point.current_point().is_none() {
13211 return Err(APIError::APIMisuseError {
13212 err: format!(
13213 "Channel {} cannot be spliced until a payment is routed",
13214 self.context.channel_id(),
13215 ),
13216 });
13217 }
13218
13219 if self.quiescent_action.is_some() {
13220 return Err(APIError::APIMisuseError {
13221 err: format!(
13222 "Channel {} cannot be spliced as one is waiting to be negotiated",
13223 self.context.channel_id(),
13224 ),
13225 });
13226 }
13227
13228 if let Some(pending_splice) = &self.pending_splice {
13229 if let Some(funding_negotiation) = &pending_splice.funding_negotiation {
13230 debug_assert!(self.context.channel_state.is_quiescent());
13231 if funding_negotiation.is_initiator() {
13232 return Err(APIError::APIMisuseError {
13233 err: format!(
13234 "Channel {} cannot be spliced as one is currently being negotiated",
13235 self.context.channel_id(),
13236 ),
13237 });
13238 }
13239 }
13240 }
13241
13242 if !self.context.is_usable() {
13243 return Err(APIError::APIMisuseError {
13244 err: format!(
13245 "Channel {} cannot be spliced as it is either pending open/close",
13246 self.context.channel_id()
13247 ),
13248 });
13249 }
13250
13251 let spliceable_balance = self.get_next_splice_out_maximum(&self.funding).map_err(|e| {
13252 APIError::ChannelUnavailable {
13253 err: format!(
13254 "Channel {} cannot be spliced at this time: {}",
13255 self.context.channel_id(),
13256 e
13257 ),
13258 }
13259 })?;
13260
13261 let (min_rbf_feerate, prior_contribution) = if self.is_rbf_compatible().is_err() {
13262 (None, None)
13264 } else if self.pending_splice.as_ref().is_some_and(|pending_splice| {
13265 pending_splice.has_confirmed_candidate()
13266 || pending_splice.received_funding_txid.is_some()
13267 }) {
13268 (None, None)
13273 } else if let Some(pending_splice) = self.pending_splice.as_ref() {
13274 let min_rbf_feerate = pending_splice.min_rbf_feerate();
13287 let prior = if pending_splice.last_funding_feerate_sat_per_1000_weight.is_some() {
13288 pending_splice.latest_contribution().cloned()
13289 } else {
13290 None
13291 };
13292 (min_rbf_feerate, prior)
13293 } else {
13294 (None, None)
13296 };
13297
13298 let funding_txo = self.funding.get_funding_txo().expect("funding_txo should be set");
13299 let previous_utxo =
13300 self.funding.get_funding_output().expect("funding_output should be set");
13301 let shared_input = Input {
13302 outpoint: funding_txo.into_bitcoin_outpoint(),
13303 previous_utxo,
13304 satisfaction_weight: EMPTY_SCRIPT_SIG_WEIGHT + FUNDING_TRANSACTION_WITNESS_WEIGHT,
13305 };
13306
13307 Ok(FundingTemplate::new(
13308 Some(shared_input),
13309 min_rbf_feerate,
13310 prior_contribution,
13311 spliceable_balance,
13312 ))
13313 }
13314
13315 fn is_rbf_compatible(&self) -> Result<(), String> {
13317 if self.context.minimum_depth(&self.funding) == Some(0) {
13318 return Err(format!(
13319 "Channel {} has option_zeroconf, cannot RBF",
13320 self.context.channel_id(),
13321 ));
13322 }
13323 Ok(())
13324 }
13325
13326 fn queued_contribution_can_rbf(&self, contribution: &FundingContribution) -> bool {
13330 let pending_splice = match &self.pending_splice {
13331 Some(pending_splice) => pending_splice,
13332 None => return false,
13333 };
13334 if self.is_rbf_compatible().is_err() {
13337 return false;
13338 }
13339 if pending_splice.has_confirmed_candidate()
13340 || pending_splice.received_funding_txid.is_some()
13341 {
13342 return false;
13343 }
13344 let prev_feerate = match pending_splice.funding_negotiation.as_ref() {
13349 Some(funding_negotiation) => funding_negotiation.funding_feerate_sat_per_1000_weight(),
13350 None => match pending_splice.last_funding_feerate_sat_per_1000_weight {
13351 Some(prev_feerate) => prev_feerate,
13352 None => return false,
13353 },
13354 };
13355 contribution.feerate() >= PendingFunding::min_rbf_feerate_above(prev_feerate)
13356 }
13357
13358 fn can_initiate_rbf(&self) -> Result<FeeRate, String> {
13359 self.is_rbf_compatible()?;
13360
13361 let pending_splice = match &self.pending_splice {
13362 Some(pending_splice) => pending_splice,
13363 None => {
13364 return Err(format!(
13365 "Channel {} has no pending splice to RBF",
13366 self.context.channel_id(),
13367 ));
13368 },
13369 };
13370
13371 if pending_splice.funding_negotiation.is_some() {
13372 return Err(format!(
13373 "Channel {} cannot RBF as a funding negotiation is already in progress",
13374 self.context.channel_id(),
13375 ));
13376 }
13377
13378 if pending_splice.has_confirmed_candidate() {
13379 return Err(
13380 "A negotiated splice transaction has already confirmed, cannot RBF".to_owned()
13381 );
13382 }
13383
13384 if pending_splice.received_funding_txid.is_some() {
13385 return Err(format!(
13386 "Channel {} counterparty already sent splice_locked, cannot RBF",
13387 self.context.channel_id(),
13388 ));
13389 }
13390
13391 if pending_splice.negotiated_candidates.is_empty() {
13392 return Err(format!(
13393 "Channel {} has no negotiated splice candidates to RBF",
13394 self.context.channel_id(),
13395 ));
13396 }
13397
13398 match pending_splice.last_funding_feerate_sat_per_1000_weight {
13399 Some(prev_feerate) => Ok(PendingFunding::min_rbf_feerate_above(prev_feerate)),
13400 None => Err(format!(
13401 "Channel {} has no prior feerate to compute RBF minimum",
13402 self.context.channel_id(),
13403 )),
13404 }
13405 }
13406
13407 fn maybe_adjust_for_rbf<L: Logger>(
13411 &self, contribution: FundingContribution, min_rbf_feerate: FeeRate, logger: &L,
13412 ) -> FundingContribution {
13413 if contribution.feerate() >= min_rbf_feerate {
13414 return contribution;
13415 }
13416
13417 let spliceable_balance = match self.get_next_splice_out_maximum(&self.funding) {
13418 Ok(balance) => balance,
13419 Err(_) => return contribution,
13420 };
13421
13422 if let Err(e) =
13423 contribution.net_value_for_initiator_at_feerate(min_rbf_feerate, spliceable_balance)
13424 {
13425 log_info!(logger, "Cannot adjust to minimum RBF feerate {}: {}", min_rbf_feerate, e,);
13426 return contribution;
13427 }
13428
13429 log_info!(
13430 logger,
13431 "Adjusting contribution feerate from {} to minimum RBF feerate {}",
13432 contribution.feerate(),
13433 min_rbf_feerate,
13434 );
13435 contribution
13436 .for_initiator_at_feerate(min_rbf_feerate, spliceable_balance)
13437 .expect("feerate compatibility already checked")
13438 }
13439
13440 pub fn funding_contributed<F: FeeEstimator, L: Logger>(
13441 &mut self, contribution: FundingContribution, locktime: LockTime,
13442 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
13443 ) -> Result<Option<msgs::Stfu>, QuiescentError> {
13444 debug_assert!(contribution.is_splice());
13445
13446 let already_contributing = match self.quiescent_action.as_ref() {
13449 Some(QuiescentAction::Splice { .. }) => true,
13450 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
13451 Some(QuiescentAction::DoNothing) => unreachable!(),
13452 None => self
13453 .pending_splice
13454 .as_ref()
13455 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
13456 .is_some_and(|funding_negotiation| funding_negotiation.is_initiator()),
13457 };
13458 if already_contributing {
13459 return Err(match contribution.unique_contributions() {
13460 None => QuiescentError::DoNothing,
13461 Some((inputs, outputs)) => QuiescentError::DiscardFunding {
13462 inputs,
13463 outputs: outputs
13464 .into_iter()
13465 .map(|output| output.script_pubkey.clone())
13466 .collect(),
13467 },
13468 });
13469 }
13470
13471 let (committed_inputs, committed_output_scripts) = self
13476 .pending_splice
13477 .as_ref()
13478 .map(|pending_splice| pending_splice.committed_funding_parts())
13479 .unwrap_or_default();
13480 if contribution.is_stale(&committed_inputs, &committed_output_scripts) {
13481 log_error!(
13482 logger,
13483 "Channel {} rejecting stale funding contribution: its inherited inputs and outputs no longer match the pending splice state; build a new contribution from a fresh FundingTemplate",
13484 self.context.channel_id(),
13485 );
13486 return Err(QuiescentError::FailSplice(
13487 SpliceFundingFailed::from_contribution(contribution),
13488 NegotiationFailureReason::ContributionInvalid,
13489 ));
13490 }
13491
13492 let our_funding_contribution = contribution.net_value();
13493 let unsigned_contribution = our_funding_contribution.unsigned_abs();
13494 if let Err(e) = self.get_next_splice_out_maximum(&self.funding)
13495 .and_then(|splice_max| splice_max
13496 .to_sat()
13497 .checked_add_signed(our_funding_contribution.to_sat())
13498 .ok_or(format!("Our splice-out value of {unsigned_contribution} is greater than the maximum {splice_max}"))
13499 )
13500 {
13501 log_error!(logger, "Channel {} cannot be funded: {}", self.context.channel_id(), e);
13502 return Err(QuiescentError::FailSplice(
13503 SpliceFundingFailed::from_contribution(contribution),
13504 NegotiationFailureReason::ContributionInvalid,
13505 ));
13506 }
13507
13508 if let Some(pending_splice) = self.pending_splice.as_ref() {
13509 if !pending_splice.is_rbf_feerate_sufficient(
13510 contribution.feerate().to_sat_per_kwu() as u32,
13511 fee_estimator,
13512 ) {
13513 log_error!(
13514 logger,
13515 "Channel {} RBF feerate {} below fee estimator minimum",
13516 self.context.channel_id(),
13517 contribution.feerate(),
13518 );
13519 return Err(QuiescentError::FailSplice(
13520 SpliceFundingFailed::from_contribution(contribution),
13521 NegotiationFailureReason::FeeRateTooLow,
13522 ));
13523 }
13524 }
13525
13526 let (contribution, rbf_failure_reason) = if self.pending_splice.is_some() {
13531 match self.can_initiate_rbf() {
13532 Ok(min_rbf_feerate) => {
13533 let contribution =
13534 self.maybe_adjust_for_rbf(contribution, min_rbf_feerate, logger);
13535 let failure_reason = if contribution.feerate() < min_rbf_feerate {
13536 Some(NegotiationFailureReason::FeeRateTooLow)
13537 } else {
13538 None
13539 };
13540 (contribution, failure_reason)
13541 },
13542 Err(e) => {
13543 log_info!(
13544 logger,
13545 "Cannot initiate splice RBF for channel {}: {}",
13546 self.context.channel_id(),
13547 e,
13548 );
13549 (contribution, Some(NegotiationFailureReason::CannotInitiateRbf))
13550 },
13551 }
13552 } else {
13553 (contribution, None)
13554 };
13555
13556 if let Some(reason) = rbf_failure_reason {
13557 let can_queue_for_fresh_splice =
13558 self.pending_splice.as_ref().map_or(true, |pending_splice| {
13559 pending_splice.can_queue_contribution_for_fresh_splice(&contribution)
13560 });
13561 if !can_queue_for_fresh_splice {
13562 return Err(QuiescentError::FailSplice(
13563 SpliceFundingFailed::from_contribution(contribution),
13564 reason,
13565 ));
13566 }
13567 }
13568
13569 debug_assert!(
13574 self.pending_splice
13575 .as_ref()
13576 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
13577 .map_or(true, |funding_negotiation| !funding_negotiation.is_initiator()),
13578 "A queued splice must not coexist with a funding negotiation we initiated",
13579 );
13580
13581 self.propose_quiescence(logger, QuiescentAction::Splice { contribution, locktime })
13582 }
13583
13584 fn queued_funding_contribution(&self) -> Option<&FundingContribution> {
13587 match &self.quiescent_action {
13588 Some(QuiescentAction::Splice { contribution, .. }) => Some(contribution),
13589 _ => None,
13590 }
13591 }
13592
13593 fn take_queued_funding_contribution(&mut self) -> Option<FundingContribution> {
13595 match &self.quiescent_action {
13596 Some(QuiescentAction::Splice { .. }) => match self.quiescent_action.take() {
13597 Some(QuiescentAction::Splice { contribution, .. }) => Some(contribution),
13598 _ => unreachable!(),
13599 },
13600 _ => None,
13601 }
13602 }
13603
13604 fn send_splice_init(
13605 &mut self, context: FundingNegotiationContext, contribution: FundingContribution,
13606 ) -> msgs::SpliceInit {
13607 debug_assert!(self.pending_splice.is_none());
13608 let prev_funding_txid = self.funding.get_funding_txid();
13610 let funding_pubkey = match prev_funding_txid {
13611 None => {
13612 debug_assert!(false);
13613 self.funding.get_holder_pubkeys().funding_pubkey
13614 },
13615 Some(prev_funding_txid) => self
13616 .context
13617 .holder_signer
13618 .new_funding_pubkey(prev_funding_txid, &self.context.secp_ctx),
13619 };
13620
13621 let funding_feerate_per_kw = context.funding_feerate_sat_per_1000_weight;
13622 let funding_contribution_satoshis = context.our_funding_contribution.to_sat();
13623 let locktime = context.funding_tx_locktime.to_consensus_u32();
13624
13625 let funding_negotiation =
13626 FundingNegotiation::AwaitingAck { context, new_holder_funding_key: funding_pubkey };
13627 self.pending_splice = Some(PendingFunding {
13628 funding_negotiation: Some(funding_negotiation),
13629 negotiation_contribution: Some(contribution),
13630 negotiated_candidates: vec![],
13631 sent_funding_txid: None,
13632 received_funding_txid: None,
13633 last_funding_feerate_sat_per_1000_weight: None,
13634 });
13635
13636 msgs::SpliceInit {
13637 channel_id: self.context.channel_id,
13638 funding_contribution_satoshis,
13639 funding_feerate_per_kw,
13640 locktime,
13641 funding_pubkey,
13642 require_confirmed_inputs: None,
13643 }
13644 }
13645
13646 fn send_tx_init_rbf(
13647 &mut self, context: FundingNegotiationContext, contribution: FundingContribution,
13648 ) -> msgs::TxInitRbf {
13649 let pending_splice =
13650 self.pending_splice.as_mut().expect("pending_splice should exist for RBF");
13651 debug_assert!(!pending_splice.negotiated_candidates.is_empty());
13652 debug_assert!(
13653 pending_splice.funding_negotiation.is_none(),
13654 "A new RBF cannot begin while another funding negotiation is in progress",
13655 );
13656
13657 let new_holder_funding_key = pending_splice
13658 .negotiated_candidates
13659 .first()
13660 .unwrap()
13661 .funding
13662 .get_holder_pubkeys()
13663 .funding_pubkey;
13664
13665 let funding_feerate_per_kw = context.funding_feerate_sat_per_1000_weight;
13666 let funding_contribution_satoshis = context.our_funding_contribution.to_sat();
13667 let locktime = context.funding_tx_locktime.to_consensus_u32();
13668
13669 pending_splice.funding_negotiation =
13670 Some(FundingNegotiation::AwaitingAck { context, new_holder_funding_key });
13671 pending_splice.negotiation_contribution = Some(contribution);
13672
13673 msgs::TxInitRbf {
13674 channel_id: self.context.channel_id,
13675 locktime,
13676 feerate_sat_per_1000_weight: funding_feerate_per_kw,
13677 funding_output_contribution: Some(funding_contribution_satoshis),
13678 }
13679 }
13680
13681 pub fn cancel_funding_contributed(&mut self) -> Result<InteractiveTxMsgError, APIError> {
13682 if matches!(self.quiescent_action, Some(QuiescentAction::Splice { .. })) {
13683 let splice_funding_failed = self.abandon_quiescent_action();
13684 debug_assert!(splice_funding_failed.is_some());
13685 let str = "Manually canceled funding contribution";
13686 let err = if self.context.channel_state.is_local_stfu_sent()
13687 && !self.context.channel_state.is_remote_stfu_sent()
13688 {
13689 ChannelError::WarnAndDisconnect(str.into())
13692 } else {
13693 ChannelError::Ignore(str.into())
13696 };
13697 return Ok(InteractiveTxMsgError::new(err, splice_funding_failed)
13698 .with_negotiation_failure_reason(NegotiationFailureReason::LocallyCanceled));
13699 }
13700
13701 let funding_negotiation = self
13702 .pending_splice
13703 .as_ref()
13704 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref());
13705 let Some(funding_negotiation) = funding_negotiation else {
13706 return Err(APIError::APIMisuseError {
13707 err: format!(
13708 "Channel {} does not have a pending splice negotiation",
13709 self.context.channel_id()
13710 ),
13711 });
13712 };
13713
13714 let made_contribution = match funding_negotiation {
13715 FundingNegotiation::AwaitingAck { context, .. } => {
13716 context.contributed_inputs().next().is_some()
13717 || context.contributed_outputs().next().is_some()
13718 },
13719 FundingNegotiation::ConstructingTransaction { interactive_tx_constructor, .. } => {
13720 interactive_tx_constructor.contributed_inputs().next().is_some()
13721 || interactive_tx_constructor.contributed_outputs().next().is_some()
13722 },
13723 FundingNegotiation::AwaitingSignatures { .. } => self
13724 .context
13725 .interactive_tx_signing_session
13726 .as_ref()
13727 .expect("We have a pending splice awaiting signatures")
13728 .has_local_contribution(),
13729 };
13730 if !made_contribution {
13731 return Err(APIError::APIMisuseError {
13732 err: format!(
13733 "Channel {} has a pending splice negotiation with no contribution made",
13734 self.context.channel_id()
13735 ),
13736 });
13737 }
13738
13739 if matches!(funding_negotiation, FundingNegotiation::AwaitingSignatures { .. }) {
13746 let already_signed = self
13747 .context
13748 .interactive_tx_signing_session
13749 .as_ref()
13750 .expect("We have a pending splice awaiting signatures")
13751 .has_holder_witnesses();
13752 if already_signed {
13753 return Err(APIError::APIMisuseError {
13754 err: format!(
13755 "Channel {} has pending splice negotiation that was already signed",
13756 self.context.channel_id(),
13757 ),
13758 });
13759 }
13760 }
13761
13762 debug_assert!(self.context.channel_state.is_quiescent());
13763 let (splice_funding_failed, splice_funding_negotiated) = self.reset_pending_splice_state();
13764 debug_assert!(splice_funding_negotiated.is_none());
13765 debug_assert!(splice_funding_failed.is_some());
13766 Ok(InteractiveTxMsgError::new(
13767 ChannelError::Abort(AbortReason::ManualIntervention),
13768 splice_funding_failed,
13769 )
13770 .with_negotiation_failure_reason(NegotiationFailureReason::LocallyCanceled))
13771 }
13772
13773 pub fn validate_splice_init(&self, msg: &msgs::SpliceInit) -> Result<(), ChannelError> {
13775 if !self.context.is_live() {
13779 return Err(ChannelError::WarnAndDisconnect(
13780 "Splicing requested on a channel that is not live".to_owned(),
13781 ));
13782 }
13783
13784 if !self.context.channel_state.is_quiescent() {
13785 return Err(ChannelError::WarnAndDisconnect("Quiescence needed to splice".to_owned()));
13786 }
13787
13788 if self.pending_splice.is_some() {
13790 return Err(ChannelError::WarnAndDisconnect(format!(
13791 "Channel {} already has a splice pending",
13792 self.context.channel_id(),
13793 )));
13794 }
13795
13796 let their_funding_contribution = SignedAmount::from_sat(msg.funding_contribution_satoshis);
13797 if their_funding_contribution == SignedAmount::ZERO {
13798 return Err(ChannelError::WarnAndDisconnect(format!(
13799 "Channel {} cannot be spliced; they are the initiator, and their contribution is zero",
13800 self.context.channel_id(),
13801 )));
13802 }
13803
13804 if self.holder_commitment_point.current_point().is_none() {
13805 return Err(ChannelError::Abort(AbortReason::InternalError(
13806 "Commitment point needs to be advanced once before spliced".into(),
13807 )));
13808 }
13809
13810 Ok(())
13811 }
13812
13813 fn validate_splice_contributions(
13814 &self, our_funding_contribution: SignedAmount, their_funding_contribution: SignedAmount,
13815 counterparty_funding_pubkey: PublicKey, our_new_holder_keys: ChannelPublicKeys,
13816 min_funding_satoshis: u64,
13817 ) -> Result<FundingScope, String> {
13818 let candidate_scope = FundingScope::for_splice(
13819 &self.funding,
13820 self.context(),
13821 our_funding_contribution,
13822 their_funding_contribution,
13823 counterparty_funding_pubkey,
13824 our_new_holder_keys,
13825 min_funding_satoshis,
13826 )?;
13827
13828 let (post_splice_holder_balance, post_splice_counterparty_balance) =
13829 self.get_holder_counterparty_balances_floor_incl_fee(&candidate_scope)?;
13830
13831 let holder_selected_channel_reserve =
13832 Amount::from_sat(candidate_scope.holder_selected_channel_reserve_satoshis);
13833 let counterparty_selected_channel_reserve = Amount::from_sat(
13834 candidate_scope.counterparty_selected_channel_reserve_satoshis.expect("Reserve is set"),
13835 );
13836
13837 if our_funding_contribution != SignedAmount::ZERO {
13839 post_splice_holder_balance.checked_sub(counterparty_selected_channel_reserve).ok_or(
13840 format!(
13841 "Our post-splice channel balance {} is smaller than their selected v2 reserve {}",
13842 post_splice_holder_balance,
13843 counterparty_selected_channel_reserve,
13844 ),
13845 )?;
13846 }
13847
13848 if their_funding_contribution != SignedAmount::ZERO {
13849 post_splice_counterparty_balance.checked_sub(holder_selected_channel_reserve).ok_or(
13850 format!(
13851 "Their post-splice channel balance {} is smaller than our selected v2 reserve {}",
13852 post_splice_counterparty_balance,
13853 holder_selected_channel_reserve,
13854 ),
13855 )?;
13856 }
13857
13858 #[cfg(debug_assertions)]
13859 {
13860 let (old_holder_balance_msat, old_counterparty_balance_msat) =
13861 *self.funding.holder_prev_commitment_tx_balance.lock().unwrap();
13862 let (new_holder_balance_msat, new_counterparty_balance_msat) =
13863 *candidate_scope.holder_prev_commitment_tx_balance.lock().unwrap();
13864 if new_holder_balance_msat < counterparty_selected_channel_reserve.to_sat() * 1000 {
13865 debug_assert_eq!(new_holder_balance_msat, old_holder_balance_msat);
13866 }
13867 if new_counterparty_balance_msat < holder_selected_channel_reserve.to_sat() * 1000 {
13868 debug_assert_eq!(new_counterparty_balance_msat, old_counterparty_balance_msat);
13869 }
13870 }
13871 #[cfg(debug_assertions)]
13872 {
13873 let (old_holder_balance_msat, old_counterparty_balance_msat) =
13874 *self.funding.counterparty_prev_commitment_tx_balance.lock().unwrap();
13875 let (new_holder_balance_msat, new_counterparty_balance_msat) =
13876 *candidate_scope.counterparty_prev_commitment_tx_balance.lock().unwrap();
13877 if new_holder_balance_msat < counterparty_selected_channel_reserve.to_sat() * 1000 {
13878 debug_assert_eq!(new_holder_balance_msat, old_holder_balance_msat);
13879 }
13880 if new_counterparty_balance_msat < holder_selected_channel_reserve.to_sat() * 1000 {
13881 debug_assert_eq!(new_counterparty_balance_msat, old_counterparty_balance_msat);
13882 }
13883 }
13884
13885 Ok(candidate_scope)
13886 }
13887
13888 fn resolve_queued_contribution<L: Logger>(
13889 &self, feerate: FeeRate, logger: &L,
13890 ) -> Result<(Option<SignedAmount>, Option<Amount>), ChannelError> {
13891 let spliceable_balance = self
13892 .get_next_splice_out_maximum(&self.funding)
13893 .map_err(|e| {
13894 log_info!(
13895 logger,
13896 "Cannot compute holder balance for channel {}: {}; \
13897 proceeding without contribution",
13898 self.context.channel_id(),
13899 e,
13900 );
13901 })
13902 .ok();
13903
13904 let net_value = match spliceable_balance.and_then(|_| self.queued_funding_contribution()) {
13905 Some(c) => {
13906 match c.net_value_for_acceptor_at_feerate(feerate, spliceable_balance.unwrap()) {
13907 Ok(net_value) => Some(net_value),
13908 Err(FeeRateAdjustmentError::FeeRateTooHigh { .. }) => {
13909 return Err(ChannelError::Abort(AbortReason::FeeRateTooHigh));
13910 },
13911 Err(e) => {
13912 log_info!(
13913 logger,
13914 "Cannot accommodate initiator's feerate ({}) for channel {}: {}",
13915 feerate,
13916 self.context.channel_id(),
13917 e,
13918 );
13919 None
13920 },
13921 }
13922 },
13923 None => None,
13924 };
13925
13926 Ok((net_value, spliceable_balance))
13927 }
13928
13929 pub(crate) fn splice_init<ES: EntropySource, L: Logger>(
13930 &mut self, msg: &msgs::SpliceInit, entropy_source: &ES, holder_node_id: &PublicKey,
13931 min_funding_satoshis: u64, logger: &L,
13932 ) -> Result<msgs::SpliceAck, InteractiveTxMsgError> {
13933 self.validate_splice_init(msg).map_err(|e| self.quiescent_negotiation_err(e))?;
13934
13935 let feerate = FeeRate::from_sat_per_kwu(msg.funding_feerate_per_kw as u64);
13936 let (queued_net_value, holder_balance) = self
13937 .resolve_queued_contribution(feerate, logger)
13938 .map_err(|e| self.quiescent_negotiation_err(e))?;
13939
13940 let our_funding_contribution = queued_net_value.unwrap_or(SignedAmount::ZERO);
13941 let their_funding_contribution = SignedAmount::from_sat(msg.funding_contribution_satoshis);
13942
13943 let prev_funding_txid = self.funding.get_funding_txid();
13945 let funding_pubkey = match prev_funding_txid {
13946 None => {
13947 debug_assert!(false);
13948 self.funding.get_holder_pubkeys().funding_pubkey
13949 },
13950 Some(prev_funding_txid) => self
13951 .context
13952 .holder_signer
13953 .new_funding_pubkey(prev_funding_txid, &self.context.secp_ctx),
13954 };
13955 let mut holder_pubkeys = self.funding.get_holder_pubkeys().clone();
13956 holder_pubkeys.funding_pubkey = funding_pubkey;
13957
13958 let splice_funding = self
13959 .validate_splice_contributions(
13960 our_funding_contribution,
13961 their_funding_contribution,
13962 msg.funding_pubkey,
13963 holder_pubkeys,
13964 min_funding_satoshis,
13965 )
13966 .map_err(|e| {
13967 self.quiescent_negotiation_err(ChannelError::Abort(
13968 AbortReason::InvalidContribution(e),
13969 ))
13970 })?;
13971
13972 let (adjusted_contribution, our_funding_inputs, our_funding_outputs) =
13974 if queued_net_value.is_some() {
13975 let adjusted_contribution = self
13976 .take_queued_funding_contribution()
13977 .expect("queued_funding_contribution was Some")
13978 .for_acceptor_at_feerate(feerate, holder_balance.unwrap())
13979 .expect("feerate compatibility already checked");
13980 let (inputs, outputs) = adjusted_contribution.clone().into_tx_parts();
13981 (Some(adjusted_contribution), inputs, outputs)
13982 } else {
13983 (None, Default::default(), Default::default())
13984 };
13985
13986 log_info!(
13987 logger,
13988 "Starting splice funding negotiation for channel {} after receiving splice_init; new channel value: {} sats (old: {} sats)",
13989 self.context.channel_id,
13990 splice_funding.get_value_satoshis(),
13991 self.funding.get_value_satoshis(),
13992 );
13993
13994 let new_funding_pubkey = splice_funding.get_holder_pubkeys().funding_pubkey;
13995 let prev_funding_input = self.funding.to_splice_funding_input();
13996 let funding_negotiation = FundingNegotiation::for_acceptor(
13997 splice_funding,
13998 &self.context,
13999 entropy_source,
14000 holder_node_id,
14001 our_funding_contribution,
14002 prev_funding_input,
14003 msg.locktime,
14004 msg.funding_feerate_per_kw,
14005 our_funding_inputs,
14006 our_funding_outputs,
14007 );
14008 self.pending_splice = Some(PendingFunding {
14009 funding_negotiation: Some(funding_negotiation),
14010 negotiation_contribution: adjusted_contribution,
14011 negotiated_candidates: Vec::new(),
14012 received_funding_txid: None,
14013 sent_funding_txid: None,
14014 last_funding_feerate_sat_per_1000_weight: None,
14015 });
14016
14017 Ok(msgs::SpliceAck {
14018 channel_id: self.context.channel_id,
14019 funding_contribution_satoshis: our_funding_contribution.to_sat(),
14020 funding_pubkey: new_funding_pubkey,
14021 require_confirmed_inputs: None,
14022 })
14023 }
14024
14025 fn validate_tx_init_rbf<F: FeeEstimator>(
14027 &self, msg: &msgs::TxInitRbf, fee_estimator: &LowerBoundedFeeEstimator<F>,
14028 ) -> Result<(ChannelPublicKeys, PublicKey), ChannelError> {
14029 if !self.context.is_live() {
14030 return Err(ChannelError::WarnAndDisconnect(
14031 "RBF requested on a channel that is not live".to_owned(),
14032 ));
14033 }
14034 if !self.context.channel_state.is_quiescent() {
14035 return Err(ChannelError::WarnAndDisconnect("Quiescence needed for RBF".to_owned()));
14036 }
14037
14038 if self.holder_commitment_point.current_point().is_none() {
14039 return Err(ChannelError::Abort(AbortReason::InternalError(
14040 "Commitment point needs to be advanced once before RBF".into(),
14041 )));
14042 }
14043
14044 self.is_rbf_compatible()
14045 .map_err(|msg| ChannelError::Abort(AbortReason::RbfUnavailable(msg)))?;
14046
14047 let (pending_splice, last_candidate) = self
14048 .pending_splice
14049 .as_ref()
14050 .filter(|pending_splice| !pending_splice.negotiated_candidates.is_empty())
14051 .map(|pending_splice| {
14052 (
14053 pending_splice,
14054 pending_splice.negotiated_candidates.last().expect("checked above"),
14055 )
14056 })
14057 .ok_or_else(|| {
14058 ChannelError::Abort(AbortReason::RbfUnavailable(
14059 "No pending splice available to RBF".into(),
14060 ))
14061 })?;
14062
14063 if pending_splice.funding_negotiation.is_some() {
14064 return Err(ChannelError::WarnAndDisconnect(
14065 "Received tx_init_rbf while a funding negotiation is already in progress"
14066 .to_owned(),
14067 ));
14068 }
14069
14070 if pending_splice.received_funding_txid.is_some() {
14071 return Err(ChannelError::Abort(AbortReason::RbfUnavailable(
14072 "Already received splice_locked".into(),
14073 )));
14074 }
14075
14076 if pending_splice.has_confirmed_candidate() {
14077 return Err(ChannelError::Abort(AbortReason::RbfUnavailable(
14078 "A negotiated splice transaction has already confirmed".into(),
14079 )));
14080 }
14081
14082 let prev_feerate =
14083 pending_splice.last_funding_feerate_sat_per_1000_weight.unwrap_or_else(|| {
14084 fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::UrgentOnChainSweep)
14085 });
14086 let new_feerate = FeeRate::from_sat_per_kwu(msg.feerate_sat_per_1000_weight as u64);
14087 if new_feerate < PendingFunding::min_rbf_feerate_above(prev_feerate) {
14088 return Err(ChannelError::Abort(AbortReason::InsufficientRbfFeerate));
14089 }
14090
14091 if !pending_splice.is_rbf_feerate_sufficient(msg.feerate_sat_per_1000_weight, fee_estimator)
14092 {
14093 return Err(ChannelError::Abort(AbortReason::InsufficientRbfFeerate));
14094 }
14095
14096 Ok((
14099 last_candidate.funding.get_holder_pubkeys().clone(),
14100 *last_candidate.funding.counterparty_funding_pubkey(),
14101 ))
14102 }
14103
14104 pub(crate) fn tx_init_rbf<ES: EntropySource, F: FeeEstimator, L: Logger>(
14105 &mut self, msg: &msgs::TxInitRbf, entropy_source: &ES, holder_node_id: &PublicKey,
14106 fee_estimator: &LowerBoundedFeeEstimator<F>, min_funding_satoshis: u64, logger: &L,
14107 ) -> Result<msgs::TxAckRbf, InteractiveTxMsgError> {
14108 let (holder_pubkeys, counterparty_funding_pubkey) = self
14109 .validate_tx_init_rbf(msg, fee_estimator)
14110 .map_err(|e| self.quiescent_negotiation_err(e))?;
14111
14112 let feerate = FeeRate::from_sat_per_kwu(msg.feerate_sat_per_1000_weight as u64);
14113 let (queued_net_value, holder_balance) = self
14114 .resolve_queued_contribution(feerate, logger)
14115 .map_err(|e| self.quiescent_negotiation_err(e))?;
14116
14117 let prior_net_value = if queued_net_value.is_some() {
14120 None
14121 } else if let Some(prior) = self
14122 .pending_splice
14123 .as_ref()
14124 .and_then(|pending_splice| pending_splice.latest_contribution())
14125 {
14126 let net_value = holder_balance
14127 .ok_or_else(|| ChannelError::Abort(AbortReason::InsufficientRbfFeerate))
14128 .and_then(|holder_balance| {
14129 prior
14130 .net_value_for_acceptor_at_feerate(feerate, holder_balance)
14131 .map_err(|_| ChannelError::Abort(AbortReason::InsufficientRbfFeerate))
14132 })
14133 .map_err(|e| self.quiescent_negotiation_err(e))?;
14134 Some(net_value)
14135 } else {
14136 None
14137 };
14138
14139 let our_funding_contribution = queued_net_value.or(prior_net_value);
14140 let our_funding_contribution = our_funding_contribution.unwrap_or(SignedAmount::ZERO);
14141
14142 let their_funding_contribution = match msg.funding_output_contribution {
14143 Some(value) => SignedAmount::from_sat(value),
14144 None => SignedAmount::ZERO,
14145 };
14146
14147 let rbf_funding = self
14148 .validate_splice_contributions(
14149 our_funding_contribution,
14150 their_funding_contribution,
14151 counterparty_funding_pubkey,
14152 holder_pubkeys,
14153 min_funding_satoshis,
14154 )
14155 .map_err(|e| {
14156 self.quiescent_negotiation_err(ChannelError::Abort(
14157 AbortReason::InvalidContribution(e),
14158 ))
14159 })?;
14160
14161 let (our_funding_inputs, our_funding_outputs) = if queued_net_value.is_some() {
14163 let adjusted_contribution = self
14164 .take_queued_funding_contribution()
14165 .expect("queued_funding_contribution was Some")
14166 .for_acceptor_at_feerate(feerate, holder_balance.unwrap())
14167 .expect("feerate compatibility already checked");
14168 self.pending_splice
14169 .as_mut()
14170 .expect("pending_splice is Some")
14171 .negotiation_contribution = Some(adjusted_contribution.clone());
14172 adjusted_contribution.into_tx_parts()
14173 } else if prior_net_value.is_some() {
14174 let prior_contribution = self
14175 .pending_splice
14176 .as_ref()
14177 .expect("pending_splice is Some")
14178 .latest_contribution()
14179 .expect("prior_net_value was Some")
14180 .clone();
14181 let pending_components =
14185 PendingFundingComponents::from_contribution(&prior_contribution);
14186 let adjusted_contribution = prior_contribution
14187 .for_acceptor_at_feerate(feerate, holder_balance.unwrap())
14188 .expect("feerate compatibility already checked")
14189 .with_pending_components(pending_components);
14190 self.pending_splice
14191 .as_mut()
14192 .expect("pending_splice is Some")
14193 .negotiation_contribution = Some(adjusted_contribution.clone());
14194 adjusted_contribution.into_tx_parts()
14195 } else {
14196 Default::default()
14197 };
14198
14199 log_info!(
14200 logger,
14201 "Starting RBF funding negotiation for channel {} after receiving tx_init_rbf; channel value: {} sats",
14202 self.context.channel_id,
14203 rbf_funding.get_value_satoshis(),
14204 );
14205
14206 let prev_funding_input = self.funding.to_splice_funding_input();
14207 let funding_negotiation = FundingNegotiation::for_acceptor(
14208 rbf_funding,
14209 &self.context,
14210 entropy_source,
14211 holder_node_id,
14212 our_funding_contribution,
14213 prev_funding_input,
14214 msg.locktime,
14215 msg.feerate_sat_per_1000_weight,
14216 our_funding_inputs,
14217 our_funding_outputs,
14218 );
14219 let pending_splice = self.pending_splice.as_mut().expect("pending_splice should exist");
14220 pending_splice.funding_negotiation = Some(funding_negotiation);
14221
14222 Ok(msgs::TxAckRbf {
14223 channel_id: self.context.channel_id,
14224 funding_output_contribution: if our_funding_contribution != SignedAmount::ZERO {
14225 Some(our_funding_contribution.to_sat())
14226 } else {
14227 None
14228 },
14229 })
14230 }
14231
14232 fn validate_tx_ack_rbf(
14233 &self, msg: &msgs::TxAckRbf, min_funding_satoshis: u64,
14234 ) -> Result<FundingScope, ChannelError> {
14235 let pending_splice = self
14236 .pending_splice
14237 .as_ref()
14238 .ok_or_else(|| ChannelError::Ignore("Channel is not in pending splice".to_owned()))?;
14239
14240 let (funding_negotiation_context, _) = pending_splice.awaiting_ack_context("tx_ack_rbf")?;
14241
14242 let our_funding_contribution = funding_negotiation_context.our_funding_contribution;
14243 let their_funding_contribution = match msg.funding_output_contribution {
14244 Some(value) => SignedAmount::from_sat(value),
14245 None => SignedAmount::ZERO,
14246 };
14247
14248 let last_candidate = pending_splice.negotiated_candidates.last().ok_or_else(|| {
14249 ChannelError::Abort(AbortReason::RbfUnavailable(
14250 "No pending splice available to RBF".into(),
14251 ))
14252 })?;
14253 let holder_pubkeys = last_candidate.funding.get_holder_pubkeys().clone();
14254 let counterparty_funding_pubkey = *last_candidate.funding.counterparty_funding_pubkey();
14255
14256 let new_funding = self
14257 .validate_splice_contributions(
14258 our_funding_contribution,
14259 their_funding_contribution,
14260 counterparty_funding_pubkey,
14261 holder_pubkeys,
14262 min_funding_satoshis,
14263 )
14264 .map_err(|e| ChannelError::Abort(AbortReason::InvalidContribution(e)))?;
14265
14266 Ok(new_funding)
14267 }
14268
14269 pub(crate) fn tx_ack_rbf<ES: EntropySource, L: Logger>(
14270 &mut self, msg: &msgs::TxAckRbf, entropy_source: &ES, holder_node_id: &PublicKey,
14271 min_funding_satoshis: u64, logger: &L,
14272 ) -> Result<Option<InteractiveTxMessageSend>, ChannelError> {
14273 let rbf_funding = self.validate_tx_ack_rbf(msg, min_funding_satoshis)?;
14274
14275 log_info!(
14276 logger,
14277 "Starting RBF funding negotiation for channel {} after receiving tx_ack_rbf; channel value: {} sats",
14278 self.context.channel_id,
14279 rbf_funding.get_value_satoshis(),
14280 );
14281
14282 let pending_splice = self
14283 .pending_splice
14284 .as_mut()
14285 .expect("pending_splice existence validated in validate_tx_ack_rbf");
14286 let funding_negotiation_context = pending_splice
14287 .take_awaiting_ack_context("tx_ack_rbf")
14288 .expect("awaiting ack state validated in validate_tx_ack_rbf");
14289
14290 let (funding_negotiation, tx_msg_opt) = FundingNegotiation::for_initiator(
14291 rbf_funding,
14292 &self.context,
14293 funding_negotiation_context,
14294 entropy_source,
14295 holder_node_id,
14296 );
14297 pending_splice.funding_negotiation = Some(funding_negotiation);
14298
14299 Ok(tx_msg_opt)
14300 }
14301
14302 pub(crate) fn splice_ack<ES: EntropySource, L: Logger>(
14303 &mut self, msg: &msgs::SpliceAck, entropy_source: &ES, holder_node_id: &PublicKey,
14304 min_funding_satoshis: u64, logger: &L,
14305 ) -> Result<Option<InteractiveTxMessageSend>, ChannelError> {
14306 let splice_funding = self.validate_splice_ack(msg, min_funding_satoshis)?;
14307
14308 log_info!(
14309 logger,
14310 "Starting splice funding negotiation for channel {} after receiving splice_ack; new channel value: {} sats (old: {} sats)",
14311 self.context.channel_id,
14312 splice_funding.get_value_satoshis(),
14313 self.funding.get_value_satoshis(),
14314 );
14315
14316 debug_assert!(self.context.interactive_tx_signing_session.is_none());
14317
14318 let pending_splice = self
14319 .pending_splice
14320 .as_mut()
14321 .expect("pending_splice existence validated in validate_splice_ack");
14322 let funding_negotiation_context = pending_splice
14323 .take_awaiting_ack_context("splice_ack")
14324 .expect("awaiting ack state validated in validate_splice_ack");
14325
14326 let (funding_negotiation, tx_msg_opt) = FundingNegotiation::for_initiator(
14327 splice_funding,
14328 &self.context,
14329 funding_negotiation_context,
14330 entropy_source,
14331 holder_node_id,
14332 );
14333 pending_splice.funding_negotiation = Some(funding_negotiation);
14334
14335 Ok(tx_msg_opt)
14336 }
14337
14338 fn validate_splice_ack(
14339 &self, msg: &msgs::SpliceAck, min_funding_satoshis: u64,
14340 ) -> Result<FundingScope, ChannelError> {
14341 let pending_splice = self
14342 .pending_splice
14343 .as_ref()
14344 .ok_or_else(|| ChannelError::Ignore("Channel is not in pending splice".to_owned()))?;
14345
14346 let (funding_negotiation_context, new_holder_funding_key) =
14347 pending_splice.awaiting_ack_context("splice_ack")?;
14348
14349 let our_funding_contribution = funding_negotiation_context.our_funding_contribution;
14350 let their_funding_contribution = SignedAmount::from_sat(msg.funding_contribution_satoshis);
14351
14352 let mut new_keys = self.funding.get_holder_pubkeys().clone();
14353 new_keys.funding_pubkey = *new_holder_funding_key;
14354
14355 let new_funding = self
14356 .validate_splice_contributions(
14357 our_funding_contribution,
14358 their_funding_contribution,
14359 msg.funding_pubkey,
14360 new_keys,
14361 min_funding_satoshis,
14362 )
14363 .map_err(|e| ChannelError::Abort(AbortReason::InvalidContribution(e)))?;
14364
14365 Ok(new_funding)
14366 }
14367
14368 fn get_holder_counterparty_balances_floor_incl_fee(
14382 &self, funding: &FundingScope,
14383 ) -> Result<(Amount, Amount), String> {
14384 let addl_nondust_htlc_count = 1;
14387 let dust_exposure_limiting_feerate = None;
14389
14390 let (local_stats, _local_htlcs) = self
14401 .context
14402 .get_next_local_commitment_stats(
14403 funding,
14404 None, NextCommitmentView::ValidatingOwnUpdate,
14406 addl_nondust_htlc_count,
14407 self.context.feerate_per_kw,
14408 true,
14409 dust_exposure_limiting_feerate,
14410 )
14411 .map_err(|()| "Balance exhausted on local commitment")?;
14412
14413 let (remote_stats, _remote_htlcs) = self
14414 .context
14415 .get_next_remote_commitment_stats(
14416 funding,
14417 None, NextCommitmentView::ValidatingOwnUpdate,
14419 addl_nondust_htlc_count,
14420 self.context.feerate_per_kw,
14421 true,
14422 dust_exposure_limiting_feerate,
14423 )
14424 .map_err(|()| "Balance exhausted on remote commitment")?;
14425
14426 let holder_balance_floor = Amount::from_sat(
14427 cmp::min(
14428 local_stats.commitment_stats.holder_balance_msat,
14429 remote_stats.commitment_stats.holder_balance_msat,
14430 ) / 1000,
14431 );
14432 let counterparty_balance_floor = Amount::from_sat(
14433 cmp::min(
14434 local_stats.commitment_stats.counterparty_balance_msat,
14435 remote_stats.commitment_stats.counterparty_balance_msat,
14436 ) / 1000,
14437 );
14438
14439 Ok((holder_balance_floor, counterparty_balance_floor))
14440 }
14441
14442 fn get_next_splice_out_maximum(&self, funding: &FundingScope) -> Result<Amount, String> {
14447 let dust_exposure_limiting_feerate = None;
14449
14450 let (remote_stats, _remote_htlcs) = self
14453 .context
14454 .get_next_remote_commitment_stats(
14455 funding,
14456 None, NextCommitmentView::ValidatingOwnUpdate,
14458 0,
14459 self.context.feerate_per_kw,
14460 false,
14461 dust_exposure_limiting_feerate,
14462 )
14463 .map_err(|()| "Balance exhausted on remote commitment")?;
14464
14465 let next_splice_out_maximum_sat =
14466 remote_stats.available_balances.next_splice_out_maximum_sat;
14467
14468 #[cfg(debug_assertions)]
14469 if !self.context.is_waiting_on_peer_pending_channel_update()
14470 && !self.context.is_monitor_or_signer_pending_channel_update()
14471 {
14472 self.validate_splice_contributions(
14474 SignedAmount::from_sat(-(next_splice_out_maximum_sat as i64)),
14475 SignedAmount::ZERO,
14476 funding.counterparty_funding_pubkey().clone(),
14477 funding.get_holder_pubkeys().clone(),
14478 0,
14481 )
14482 .unwrap();
14483 self.validate_splice_contributions(
14485 SignedAmount::from_sat(-((next_splice_out_maximum_sat + 1) as i64)),
14486 SignedAmount::ZERO,
14487 funding.counterparty_funding_pubkey().clone(),
14488 funding.get_holder_pubkeys().clone(),
14489 0,
14492 )
14493 .unwrap_err();
14494 }
14495
14496 Ok(Amount::from_sat(next_splice_out_maximum_sat))
14497 }
14498
14499 pub fn splice_locked<NS: NodeSigner, L: Logger>(
14500 &mut self, msg: &msgs::SpliceLocked, node_signer: &NS, chain_hash: ChainHash,
14501 user_config: &UserConfig, block_height: u32, logger: &L,
14502 ) -> Result<Option<SpliceFundingPromotion>, ChannelError> {
14503 log_info!(logger, "Received splice_locked txid {} from our peer", msg.splice_txid,);
14504
14505 let pending_splice = match self.pending_splice.as_mut() {
14506 Some(pending_splice) => pending_splice,
14507 None => {
14508 return Err(ChannelError::Ignore("Channel is not in pending splice".to_owned()));
14509 },
14510 };
14511
14512 if !pending_splice
14513 .negotiated_candidates
14514 .iter()
14515 .any(|candidate| candidate.funding.get_funding_txid() == Some(msg.splice_txid))
14516 {
14517 let err = "unknown splice funding txid";
14518 return Err(ChannelError::close(err.to_string()));
14519 }
14520 pending_splice.received_funding_txid = Some(msg.splice_txid);
14521
14522 if pending_splice.sent_funding_txid.is_none() {
14523 log_info!(
14524 logger,
14525 "Waiting for enough confirmations to send splice_locked txid {}",
14526 msg.splice_txid,
14527 );
14528 return Ok(None);
14529 }
14530
14531 Ok(self.maybe_promote_splice_funding(
14532 node_signer,
14533 chain_hash,
14534 user_config,
14535 block_height,
14536 logger,
14537 ))
14538 }
14539
14540 pub fn queue_add_htlc<F: FeeEstimator, L: Logger>(
14544 &mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32,
14545 source: HTLCSource, onion_routing_packet: msgs::OnionPacket, skimmed_fee_msat: Option<u64>,
14546 blinding_point: Option<PublicKey>, accountable: bool,
14547 fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
14548 ) -> Result<(), (LocalHTLCFailureReason, String)> {
14549 self.send_htlc(
14550 amount_msat,
14551 payment_hash,
14552 cltv_expiry,
14553 source,
14554 onion_routing_packet,
14555 true,
14556 skimmed_fee_msat,
14557 blinding_point,
14558 false,
14560 accountable,
14561 fee_estimator,
14562 logger,
14563 )
14564 .map(|can_add_htlc| assert!(!can_add_htlc, "We forced holding cell?"))
14565 .map_err(|err| {
14566 debug_assert!(err.0.is_temporary(), "Queuing HTLC should return temporary error");
14567 err
14568 })
14569 }
14570
14571 fn send_htlc<F: FeeEstimator, L: Logger>(
14589 &mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32,
14590 source: HTLCSource, onion_routing_packet: msgs::OnionPacket, mut force_holding_cell: bool,
14591 skimmed_fee_msat: Option<u64>, blinding_point: Option<PublicKey>, hold_htlc: bool,
14592 accountable: bool, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
14593 ) -> Result<bool, (LocalHTLCFailureReason, String)> {
14594 if !matches!(self.context.channel_state, ChannelState::ChannelReady(_))
14595 || self.context.channel_state.is_local_shutdown_sent()
14596 || self.context.channel_state.is_remote_shutdown_sent()
14597 {
14598 return Err((LocalHTLCFailureReason::ChannelNotReady,
14599 "Cannot send HTLC until channel is fully established and we haven't started shutting down".to_owned()));
14600 }
14601
14602 if amount_msat == 0 {
14603 return Err((LocalHTLCFailureReason::ZeroAmount, "Cannot send 0-msat HTLC".to_owned()));
14604 }
14605
14606 let available_balances = self.get_available_balances(fee_estimator).map_err(|()| {
14607 (
14608 LocalHTLCFailureReason::ChannelBalanceOverdrawn,
14609 "Channel balance overdrawn".to_owned(),
14610 )
14611 })?;
14612 if amount_msat < available_balances.next_outbound_htlc_minimum_msat {
14613 return Err((
14614 LocalHTLCFailureReason::HTLCMinimum,
14615 format!(
14616 "Cannot send less than our next-HTLC minimum - {} msat",
14617 available_balances.next_outbound_htlc_minimum_msat
14618 ),
14619 ));
14620 }
14621
14622 if amount_msat > available_balances.next_outbound_htlc_limit_msat {
14623 return Err((
14624 LocalHTLCFailureReason::HTLCMaximum,
14625 format!(
14626 "Cannot send more than our next-HTLC maximum - {} msat",
14627 available_balances.next_outbound_htlc_limit_msat
14628 ),
14629 ));
14630 }
14631
14632 if self.context.channel_state.is_peer_disconnected() {
14633 return Err((
14640 LocalHTLCFailureReason::PeerOffline,
14641 "Cannot send an HTLC while disconnected from channel counterparty".to_owned(),
14642 ));
14643 }
14644
14645 let need_holding_cell = !self.context.channel_state.can_generate_new_commitment();
14646 log_debug!(
14647 logger,
14648 "Pushing new outbound HTLC with hash {} for {} msat {}",
14649 payment_hash,
14650 amount_msat,
14651 if force_holding_cell {
14652 "into holding cell"
14653 } else if need_holding_cell {
14654 "into holding cell as we're awaiting an RAA or monitor"
14655 } else {
14656 "to peer"
14657 }
14658 );
14659
14660 if need_holding_cell {
14661 force_holding_cell = true;
14662 }
14663
14664 if force_holding_cell {
14666 self.context.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::AddHTLC {
14667 amount_msat,
14668 payment_hash,
14669 cltv_expiry,
14670 source,
14671 onion_routing_packet,
14672 skimmed_fee_msat,
14673 blinding_point,
14674 hold_htlc: hold_htlc.then(|| ()),
14675 accountable,
14676 });
14677 return Ok(false);
14678 }
14679
14680 let send_timestamp = duration_since_epoch();
14687 self.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
14688 htlc_id: self.context.next_holder_htlc_id,
14689 amount_msat,
14690 payment_hash,
14691 cltv_expiry,
14692 state: OutboundHTLCState::LocalAnnounced(Box::new(onion_routing_packet)),
14693 source,
14694 blinding_point,
14695 skimmed_fee_msat,
14696 send_timestamp,
14697 hold_htlc: hold_htlc.then(|| ()),
14698 accountable,
14699 });
14700 self.context.next_holder_htlc_id += 1;
14701
14702 Ok(true)
14703 }
14704
14705 pub(super) fn get_available_balances<F: FeeEstimator>(
14710 &self, fee_estimator: &LowerBoundedFeeEstimator<F>,
14711 ) -> Result<AvailableBalances, ()> {
14712 let init = self.context.get_available_balances_for_scope(&self.funding, fee_estimator)?;
14713 self.pending_funding().try_fold(init, |acc, funding| {
14714 let e = self.context.get_available_balances_for_scope(funding, fee_estimator)?;
14715 Ok(AvailableBalances {
14716 inbound_capacity_msat: acc.inbound_capacity_msat.min(e.inbound_capacity_msat),
14717 outbound_capacity_msat: acc.outbound_capacity_msat.min(e.outbound_capacity_msat),
14718 next_outbound_htlc_limit_msat: acc
14719 .next_outbound_htlc_limit_msat
14720 .min(e.next_outbound_htlc_limit_msat),
14721 next_outbound_htlc_minimum_msat: acc
14722 .next_outbound_htlc_minimum_msat
14723 .max(e.next_outbound_htlc_minimum_msat),
14724 dust_exposure_msat: acc.dust_exposure_msat.max(e.dust_exposure_msat),
14725 next_splice_out_maximum_sat: acc
14726 .next_splice_out_maximum_sat
14727 .min(e.next_splice_out_maximum_sat),
14728 })
14729 })
14730 }
14731
14732 fn build_commitment_no_status_check<L: Logger>(&mut self, logger: &L) -> ChannelMonitorUpdate {
14733 log_trace!(logger, "Updating HTLC state for a newly-sent commitment_signed...");
14734 for htlc in self.context.pending_inbound_htlcs.iter_mut() {
14738 let new_state =
14739 if let &InboundHTLCState::AwaitingRemoteRevokeToAnnounce(ref forward_info) =
14740 &htlc.state
14741 {
14742 Some(InboundHTLCState::AwaitingAnnouncedRemoteRevoke(forward_info.clone()))
14743 } else {
14744 None
14745 };
14746 if let Some(state) = new_state {
14747 log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to AwaitingAnnouncedRemoteRevoke", &htlc.payment_hash);
14748 htlc.state = state;
14749 }
14750 }
14751 for htlc in self.context.pending_outbound_htlcs.iter_mut() {
14752 if let &mut OutboundHTLCState::AwaitingRemoteRevokeToRemove(ref mut outcome) =
14753 &mut htlc.state
14754 {
14755 log_trace!(logger, " ...promoting outbound AwaitingRemoteRevokeToRemove {} to AwaitingRemovedRemoteRevoke", &htlc.payment_hash);
14756 let mut reason = OutboundHTLCOutcome::Success {
14758 preimage: PaymentPreimage([0u8; 32]),
14759 attribution_data: None,
14760 };
14761 mem::swap(outcome, &mut reason);
14762 htlc.state = OutboundHTLCState::AwaitingRemovedRemoteRevoke(reason);
14763 }
14764 }
14765 if let Some((feerate, update_state)) = self.context.pending_update_fee {
14766 if update_state == FeeUpdateState::AwaitingRemoteRevokeToAnnounce {
14767 debug_assert!(!self.funding.is_outbound());
14768 log_trace!(logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce fee update {} to Committed", feerate);
14769 self.context.feerate_per_kw = feerate;
14770 self.context.pending_update_fee = None;
14771 }
14772 }
14773 self.context.resend_order = RAACommitmentOrder::RevokeAndACKFirst;
14774
14775 let update = if self.negotiated_candidates().is_empty() {
14776 let (htlcs_ref, counterparty_commitment_tx) =
14777 self.build_commitment_no_state_update(&self.funding, logger);
14778 let htlc_outputs = htlcs_ref
14779 .into_iter()
14780 .map(|(htlc, htlc_source)| {
14781 (htlc, htlc_source.map(|source_ref| Box::new(source_ref.clone())))
14782 })
14783 .collect();
14784
14785 ChannelMonitorUpdateStep::LatestCounterpartyCommitmentTXInfo {
14788 commitment_txid: counterparty_commitment_tx.trust().txid(),
14789 htlc_outputs,
14790 commitment_number: self.context.counterparty_next_commitment_transaction_number,
14791 their_per_commitment_point: self
14792 .context
14793 .counterparty_next_commitment_point
14794 .unwrap(),
14795 feerate_per_kw: Some(counterparty_commitment_tx.negotiated_feerate_per_kw()),
14796 to_broadcaster_value_sat: Some(
14797 counterparty_commitment_tx.to_broadcaster_value_sat(),
14798 ),
14799 to_countersignatory_value_sat: Some(
14800 counterparty_commitment_tx.to_countersignatory_value_sat(),
14801 ),
14802 }
14803 } else {
14804 let mut htlc_data = None;
14805 let commitment_txs = core::iter::once(&self.funding)
14806 .chain(self.pending_funding())
14807 .map(|funding| {
14808 let (htlcs_ref, counterparty_commitment_tx) =
14809 self.build_commitment_no_state_update(funding, logger);
14810 if htlc_data.is_none() {
14811 let nondust_htlc_sources = htlcs_ref
14812 .iter()
14813 .filter(|(htlc, _)| {
14815 !htlc.offered && htlc.transaction_output_index.is_some()
14816 })
14817 .map(|(_, source)| {
14818 source.expect("Outbound HTLC must have a source").clone()
14819 })
14820 .collect();
14821 let dust_htlcs = htlcs_ref
14822 .into_iter()
14823 .filter(|(htlc, _)| htlc.transaction_output_index.is_none())
14824 .map(|(htlc, source)| (htlc, source.cloned()))
14825 .collect();
14826 htlc_data = Some(CommitmentHTLCData { nondust_htlc_sources, dust_htlcs });
14827 }
14828 counterparty_commitment_tx
14829 })
14830 .collect();
14831 let htlc_data = htlc_data.unwrap();
14832 ChannelMonitorUpdateStep::LatestCounterpartyCommitment { commitment_txs, htlc_data }
14833 };
14834
14835 if self.context.announcement_sigs_state == AnnouncementSigsState::MessageSent {
14836 self.context.announcement_sigs_state = AnnouncementSigsState::Committed;
14837 }
14838
14839 self.context.latest_monitor_update_id += 1;
14840 let monitor_update = ChannelMonitorUpdate {
14841 update_id: self.context.latest_monitor_update_id,
14842 updates: vec![update],
14843 channel_id: Some(self.context.channel_id()),
14844 };
14845 self.context.channel_state.set_awaiting_remote_revoke();
14846 monitor_update
14847 }
14848
14849 #[rustfmt::skip]
14850 pub(super) fn build_commitment_no_state_update<L: Logger>(
14851 &self, funding: &FundingScope, logger: &L,
14852 ) -> (Vec<(HTLCOutputInCommitment, Option<&HTLCSource>)>, CommitmentTransaction) {
14853 let commitment_data = self.context.build_commitment_transaction(
14854 funding, self.context.counterparty_next_commitment_transaction_number,
14855 &self.context.counterparty_next_commitment_point.unwrap(), false, true, logger,
14856 );
14857 let counterparty_commitment_tx = commitment_data.tx;
14858
14859 (commitment_data.htlcs_included, counterparty_commitment_tx)
14860 }
14861
14862 fn send_commitment_no_state_update<L: Logger>(
14865 &self, logger: &L,
14866 ) -> Result<Vec<msgs::CommitmentSigned>, ChannelError> {
14867 core::iter::once(&self.funding)
14868 .chain(self.pending_funding())
14869 .map(|funding| self.send_commitment_no_state_update_for_funding(funding, logger))
14870 .collect::<Result<Vec<_>, ChannelError>>()
14871 }
14872
14873 #[rustfmt::skip]
14874 fn send_commitment_no_state_update_for_funding<L: Logger>(
14875 &self, funding: &FundingScope, logger: &L,
14876 ) -> Result<msgs::CommitmentSigned, ChannelError> {
14877 #[cfg(any(test, fuzzing))]
14879 self.build_commitment_no_state_update(funding, logger);
14880
14881 let commitment_data = self.context.build_commitment_transaction(
14882 funding, self.context.counterparty_next_commitment_transaction_number,
14883 &self.context.counterparty_next_commitment_point.unwrap(), false, true, logger,
14884 );
14885 let counterparty_commitment_tx = commitment_data.tx;
14886
14887 let (signature, htlc_signatures);
14888
14889 {
14890 let res = self.context.holder_signer
14891 .sign_counterparty_commitment(
14892 &funding.channel_transaction_parameters,
14893 &counterparty_commitment_tx,
14894 commitment_data.inbound_htlc_preimages,
14895 commitment_data.outbound_htlc_preimages,
14896 &self.context.secp_ctx,
14897 )
14898 .map_err(|_| ChannelError::Ignore("Failed to get signatures for new commitment_signed".to_owned()))?;
14899 signature = res.0;
14900 htlc_signatures = res.1;
14901
14902 let trusted_tx = counterparty_commitment_tx.trust();
14903 log_trace!(logger, "Signed remote commitment tx {} (txid {}) with redeemscript {} -> {}",
14904 encode::serialize_hex(&trusted_tx.built_transaction().transaction),
14905 &trusted_tx.txid(), encode::serialize_hex(&funding.get_funding_redeemscript()),
14906 log_bytes!(signature.serialize_compact()[..]));
14907
14908 let counterparty_keys = trusted_tx.keys();
14909 debug_assert_eq!(htlc_signatures.len(), trusted_tx.nondust_htlcs().len());
14910 for (ref htlc_sig, ref htlc) in htlc_signatures.iter().zip(trusted_tx.nondust_htlcs()) {
14911 log_trace!(logger, "Signed remote HTLC tx {} with redeemscript {} with pubkey {} -> {}",
14912 encode::serialize_hex(&chan_utils::build_htlc_transaction(&trusted_tx.txid(), trusted_tx.negotiated_feerate_per_kw(), funding.get_holder_selected_contest_delay(), htlc, funding.get_channel_type(), &counterparty_keys.broadcaster_delayed_payment_key, &counterparty_keys.revocation_key)),
14913 encode::serialize_hex(&chan_utils::get_htlc_redeemscript(&htlc, funding.get_channel_type(), &counterparty_keys)),
14914 log_bytes!(counterparty_keys.broadcaster_htlc_key.to_public_key().serialize()),
14915 log_bytes!(htlc_sig.serialize_compact()[..]));
14916 }
14917 }
14918
14919 Ok(msgs::CommitmentSigned {
14920 channel_id: self.context.channel_id,
14921 signature,
14922 htlc_signatures,
14923 funding_txid: funding.get_funding_txo().map(|funding_txo| funding_txo.txid),
14924 })
14925 }
14926
14927 pub fn send_htlc_and_commit<F: FeeEstimator, L: Logger>(
14933 &mut self, amount_msat: u64, payment_hash: PaymentHash, cltv_expiry: u32,
14934 source: HTLCSource, onion_routing_packet: msgs::OnionPacket, skimmed_fee_msat: Option<u64>,
14935 hold_htlc: bool, accountable: bool, fee_estimator: &LowerBoundedFeeEstimator<F>,
14936 logger: &L,
14937 ) -> Result<Option<ChannelMonitorUpdate>, ChannelError> {
14938 let send_res = self.send_htlc(
14939 amount_msat,
14940 payment_hash,
14941 cltv_expiry,
14942 source,
14943 onion_routing_packet,
14944 false,
14945 skimmed_fee_msat,
14946 None,
14947 hold_htlc,
14948 accountable,
14949 fee_estimator,
14950 logger,
14951 );
14952 let can_add_htlc = send_res.map_err(|(_, msg)| ChannelError::Ignore(msg))?;
14954 if can_add_htlc {
14955 let monitor_update = self.build_commitment_no_status_check(logger);
14956 self.monitor_updating_paused(
14957 false,
14958 true,
14959 false,
14960 Vec::new(),
14961 Vec::new(),
14962 Vec::new(),
14963 logger,
14964 );
14965 Ok(self.push_ret_blockable_mon_update(monitor_update))
14966 } else {
14967 Ok(None)
14968 }
14969 }
14970
14971 #[rustfmt::skip]
14974 pub fn channel_update(&mut self, msg: &msgs::ChannelUpdate) -> Result<bool, ChannelError> {
14975 let new_forwarding_info = Some(CounterpartyForwardingInfo {
14976 fee_base_msat: msg.contents.fee_base_msat,
14977 fee_proportional_millionths: msg.contents.fee_proportional_millionths,
14978 cltv_expiry_delta: msg.contents.cltv_expiry_delta
14979 });
14980 let did_change = self.context.counterparty_forwarding_info != new_forwarding_info;
14981 if did_change {
14982 self.context.counterparty_forwarding_info = new_forwarding_info;
14983 }
14984
14985 Ok(did_change)
14986 }
14987
14988 pub fn get_shutdown<L: Logger>(
14991 &mut self, signer_provider: &SP, their_features: &InitFeatures,
14992 target_feerate_sats_per_kw: Option<u32>, override_shutdown_script: Option<ShutdownScript>,
14993 logger: &L,
14994 ) -> Result<
14995 (
14996 msgs::Shutdown,
14997 Option<ChannelMonitorUpdate>,
14998 Vec<(HTLCSource, PaymentHash)>,
14999 Option<SpliceFundingFailed>,
15000 ),
15001 APIError,
15002 > {
15003 let logger = WithChannelContext::from(logger, &self.context, None);
15004
15005 if self.context.channel_state.is_local_stfu_sent()
15006 || self.context.channel_state.is_remote_stfu_sent()
15007 || self.context.channel_state.is_quiescent()
15008 {
15009 return Err(APIError::APIMisuseError {
15010 err: "Cannot begin shutdown while quiescent".to_owned(),
15011 });
15012 }
15013 for htlc in self.context.pending_outbound_htlcs.iter() {
15014 if let OutboundHTLCState::LocalAnnounced(_) = htlc.state {
15015 return Err(APIError::APIMisuseError {
15016 err: "Cannot begin shutdown with pending HTLCs. Process pending events first"
15017 .to_owned(),
15018 });
15019 }
15020 }
15021 if self.context.channel_state.is_local_shutdown_sent() {
15022 return Err(APIError::APIMisuseError {
15023 err: "Shutdown already in progress".to_owned(),
15024 });
15025 } else if self.context.channel_state.is_remote_shutdown_sent() {
15026 return Err(APIError::ChannelUnavailable {
15027 err: "Shutdown already in progress by remote".to_owned(),
15028 });
15029 }
15030 if self.context.shutdown_scriptpubkey.is_some() && override_shutdown_script.is_some() {
15031 return Err(APIError::APIMisuseError {
15032 err: "Cannot override shutdown script for a channel with one already set"
15033 .to_owned(),
15034 });
15035 }
15036 assert!(!matches!(self.context.channel_state, ChannelState::ShutdownComplete));
15037 if self.context.channel_state.is_peer_disconnected()
15038 || self.context.channel_state.is_monitor_update_in_progress()
15039 {
15040 return Err(APIError::ChannelUnavailable{err: "Cannot begin shutdown while peer is disconnected or we're waiting on a monitor update, maybe force-close instead?".to_owned()});
15041 }
15042
15043 let update_shutdown_script = match self.context.shutdown_scriptpubkey {
15044 Some(_) => false,
15045 None => {
15046 let shutdown_scriptpubkey = match override_shutdown_script {
15048 Some(script) => script,
15049 None => {
15050 match signer_provider.get_shutdown_scriptpubkey() {
15052 Ok(scriptpubkey) => scriptpubkey,
15053 Err(_) => {
15054 return Err(APIError::ChannelUnavailable {
15055 err: "Failed to get shutdown scriptpubkey".to_owned(),
15056 })
15057 },
15058 }
15059 },
15060 };
15061 if !shutdown_scriptpubkey.is_compatible(their_features) {
15062 return Err(APIError::IncompatibleShutdownScript {
15063 script: shutdown_scriptpubkey.clone(),
15064 });
15065 }
15066 self.context.shutdown_scriptpubkey = Some(shutdown_scriptpubkey);
15067 true
15068 },
15069 };
15070
15071 self.context.target_closing_feerate_sats_per_kw = target_feerate_sats_per_kw;
15073 self.context.channel_state.set_local_shutdown_sent();
15074 self.context.local_initiated_shutdown = Some(());
15075 self.context.update_time_counter += 1;
15076
15077 let monitor_update = if update_shutdown_script {
15078 self.context.latest_monitor_update_id += 1;
15079 let monitor_update = ChannelMonitorUpdate {
15080 update_id: self.context.latest_monitor_update_id,
15081 updates: vec![ChannelMonitorUpdateStep::ShutdownScript {
15082 scriptpubkey: self.get_closing_scriptpubkey(),
15083 }],
15084 channel_id: Some(self.context.channel_id()),
15085 };
15086 self.monitor_updating_paused(
15087 false,
15088 false,
15089 false,
15090 Vec::new(),
15091 Vec::new(),
15092 Vec::new(),
15093 &&logger,
15094 );
15095 self.push_ret_blockable_mon_update(monitor_update)
15096 } else {
15097 None
15098 };
15099 let shutdown = msgs::Shutdown {
15100 channel_id: self.context.channel_id,
15101 scriptpubkey: self.get_closing_scriptpubkey(),
15102 };
15103
15104 self.context.holding_cell_update_fee = None;
15107 let mut dropped_outbound_htlcs =
15108 Vec::with_capacity(self.context.holding_cell_htlc_updates.len());
15109 self.context.holding_cell_htlc_updates.retain(|htlc_update| match htlc_update {
15110 &HTLCUpdateAwaitingACK::AddHTLC { ref payment_hash, ref source, .. } => {
15111 dropped_outbound_htlcs.push((source.clone(), payment_hash.clone()));
15112 false
15113 },
15114 _ => true,
15115 });
15116
15117 debug_assert!(
15118 !self.is_shutdown() || monitor_update.is_none(),
15119 "we can't both complete shutdown and return a monitor update"
15120 );
15121
15122 let splice_funding_failed = self.abandon_quiescent_action();
15123
15124 Ok((shutdown, monitor_update, dropped_outbound_htlcs, splice_funding_failed))
15125 }
15126
15127 #[rustfmt::skip]
15130 pub fn inflight_htlc_sources(&self) -> impl Iterator<Item=(&HTLCSource, &PaymentHash)> {
15131 self.context.holding_cell_htlc_updates.iter()
15132 .flat_map(|htlc_update| {
15133 match htlc_update {
15134 HTLCUpdateAwaitingACK::AddHTLC { source, payment_hash, .. }
15135 => Some((source, payment_hash)),
15136 _ => None,
15137 }
15138 })
15139 .chain(self.context.pending_outbound_htlcs.iter().map(|htlc| (&htlc.source, &htlc.payment_hash)))
15140 }
15141
15142 pub fn get_announced_htlc_max_msat(&self) -> u64 {
15143 return cmp::min(
15144 self.funding.get_value_satoshis() * 1000 * 9 / 10,
15148 self.context.counterparty_max_htlc_value_in_flight_msat,
15149 );
15150 }
15151
15152 #[rustfmt::skip]
15153 pub fn propose_quiescence<L: Logger>(
15154 &mut self, logger: &L, action: QuiescentAction,
15155 ) -> Result<Option<msgs::Stfu>, QuiescentError> {
15156 log_debug!(logger, "Attempting to initiate quiescence");
15157
15158 if !self.context.is_usable() {
15159 debug_assert!(
15160 self.context.channel_state.is_local_shutdown_sent()
15161 || self.context.channel_state.is_remote_shutdown_sent(),
15162 "splice_channel should have prevented reaching propose_quiescence on a non-ready channel"
15163 );
15164 log_debug!(logger, "Channel is not in a usable state to propose quiescence");
15165 return Err(match action {
15166 QuiescentAction::Splice { contribution, .. } => QuiescentError::FailSplice(
15167 SpliceFundingFailed::from_contribution(contribution),
15168 NegotiationFailureReason::ChannelClosing,
15169 ),
15170 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
15171 QuiescentAction::DoNothing => QuiescentError::DoNothing,
15172 });
15173 }
15174
15175 if self.quiescent_action.is_some() {
15176 debug_assert!(
15177 false,
15178 "callers must not invoke propose_quiescence with {:?} while quiescent_action is set",
15179 action,
15180 );
15181 log_debug!(
15182 logger,
15183 "Channel already has a pending quiescent action and cannot start another",
15184 );
15185 return Err(match action {
15186 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
15187 QuiescentAction::DoNothing => QuiescentError::DoNothing,
15188 QuiescentAction::Splice { contribution, .. } => QuiescentError::FailSplice(
15189 SpliceFundingFailed::from_contribution(contribution),
15190 NegotiationFailureReason::Unknown,
15191 ),
15192 });
15193 }
15194
15195 self.quiescent_action = Some(action);
15196 if self.context.channel_state.is_quiescent() {
15197 log_debug!(logger, "Channel is already quiescent");
15198 return Ok(None);
15199 }
15200
15201 Ok(self.try_send_stfu(false, logger))
15202 }
15203
15204 #[rustfmt::skip]
15205 pub fn stfu<L: Logger>(
15206 &mut self, msg: &msgs::Stfu, logger: &L
15207 ) -> Result<Option<StfuResponse>, (ChannelError, QuiescentError)> {
15208 if self.context.channel_state.is_quiescent() {
15209 return Err((ChannelError::Warn("Channel is already quiescent".to_owned()), QuiescentError::DoNothing));
15210 }
15211 if self.context.channel_state.is_remote_stfu_sent() {
15212 return Err((ChannelError::Warn(
15213 "Peer sent `stfu` when they already sent it and we've yet to become quiescent".to_owned()
15214 ), QuiescentError::DoNothing));
15215 }
15216
15217 if !self.context.is_live() {
15218 return Err((ChannelError::Warn(
15219 "Peer sent `stfu` when we were not in a live state".to_owned()
15220 ), QuiescentError::DoNothing));
15221 }
15222
15223 if !self.context.channel_state.is_local_stfu_sent() {
15224 if !msg.initiator {
15225 return Err((ChannelError::WarnAndDisconnect(
15226 "Peer sent unexpected `stfu` without signaling as initiator".to_owned()
15227 ), QuiescentError::DoNothing));
15228 }
15229
15230 self.context.channel_state.set_remote_stfu_sent();
15236
15237 log_debug!(logger, "Received counterparty stfu proposing quiescence");
15238 return Ok(self.try_send_stfu(false, logger).map(|stfu| StfuResponse::Stfu(stfu)))
15239 }
15240
15241 let is_holder_quiescence_initiator = !msg.initiator || self.funding.is_outbound();
15244
15245 self.mark_response_received();
15247
15248 if self.context.is_waiting_on_peer_pending_channel_update()
15249 || self.context.signer_pending_revoke_and_ack
15250 || self.context.signer_pending_commitment_update
15251 {
15252 return Err((ChannelError::WarnAndDisconnect(
15258 "Received counterparty stfu while having pending counterparty updates".to_owned()
15259 ), QuiescentError::DoNothing));
15260 }
15261
15262 self.context.channel_state.clear_local_stfu_sent();
15263 self.context.channel_state.set_quiescent();
15264
15265 log_debug!(
15266 logger,
15267 "Received counterparty stfu, channel is now quiescent and we are{} the initiator",
15268 if !is_holder_quiescence_initiator { " not" } else { "" }
15269 );
15270
15271 if is_holder_quiescence_initiator {
15272 match self.quiescent_action.take() {
15273 None => {
15274 return Err((ChannelError::WarnAndDisconnect(
15278 "Quiescence no longer needed".to_owned()
15279 ), QuiescentError::DoNothing));
15280 },
15281 Some(QuiescentAction::Splice { contribution, locktime }) => {
15282 if self.pending_splice.is_some() {
15283 if !self.queued_contribution_can_rbf(&contribution) {
15284 let msg = "Waiting for splice to lock before potentially proceeding with queued contribution".into();
15285 self.quiescent_action = Some(QuiescentAction::Splice { contribution, locktime });
15286 return Err((
15287 ChannelError::WarnAndDisconnect(msg),
15288 QuiescentError::DoNothing,
15289 ));
15290 }
15291 }
15292
15293 let our_funding_contribution = contribution.net_value();
15299 let unsigned_contribution = our_funding_contribution.unsigned_abs();
15300 if let Err(e) = self.get_next_splice_out_maximum(&self.funding)
15301 .and_then(|splice_max| splice_max
15302 .to_sat()
15303 .checked_add_signed(our_funding_contribution.to_sat())
15304 .ok_or(format!("Our splice-out value of {unsigned_contribution} is greater than the maximum {splice_max}"))
15305 )
15306 {
15307 let failed = SpliceFundingFailed::from_contribution(contribution);
15308 return Err((
15309 ChannelError::WarnAndDisconnect(format!(
15310 "Channel {} contribution no longer valid at quiescence: {}",
15311 self.context.channel_id(),
15312 e,
15313 )),
15314 QuiescentError::FailSplice(
15315 failed,
15316 NegotiationFailureReason::ContributionInvalid,
15317 ),
15318 ));
15319 }
15320
15321 let prev_funding_input = self.funding.to_splice_funding_input();
15322 let our_funding_contribution = contribution.net_value();
15323 let funding_feerate_per_kw = contribution.feerate().to_sat_per_kwu() as u32;
15324 let (our_funding_inputs, our_funding_outputs) = contribution.clone().into_tx_parts();
15325 let context = FundingNegotiationContext {
15326 is_initiator: true,
15327 our_funding_contribution,
15328 funding_tx_locktime: locktime,
15329 funding_feerate_sat_per_1000_weight: funding_feerate_per_kw,
15330 shared_funding_input: Some(prev_funding_input),
15331 our_funding_inputs,
15332 our_funding_outputs,
15333 };
15334
15335 if self.pending_splice.is_some() {
15336 let tx_init_rbf = self.send_tx_init_rbf(context, contribution);
15337 return Ok(Some(StfuResponse::TxInitRbf(tx_init_rbf)));
15338 }
15339 let splice_init = self.send_splice_init(context, contribution);
15340 debug_assert!(self.pending_splice.is_some());
15341 return Ok(Some(StfuResponse::SpliceInit(splice_init)));
15342 },
15343 #[cfg(any(test, fuzzing, feature = "_test_utils"))]
15344 Some(QuiescentAction::DoNothing) => {
15345 },
15348 }
15349 }
15350
15351 Ok(None)
15352 }
15353
15354 pub fn try_send_stfu<L: Logger>(&mut self, is_retry: bool, logger: &L) -> Option<msgs::Stfu> {
15355 debug_assert!(
15357 !(self.context.channel_state.is_local_stfu_sent()
15358 && self.context.channel_state.is_remote_stfu_sent())
15359 );
15360
15361 if self.quiescent_action.is_none() && !self.context.channel_state.is_remote_stfu_sent() {
15364 return None;
15365 }
15366 if self.context.channel_state.is_local_stfu_sent()
15367 || self.context.channel_state.is_quiescent()
15368 {
15369 return None;
15370 }
15371
15372 if !self.context.is_live() {
15375 if !is_retry {
15376 log_debug!(logger, "Waiting for peer reconnection to send stfu");
15377 }
15378 return None;
15379 }
15380
15381 if self.context.is_waiting_on_peer_pending_channel_update()
15382 || self.context.is_monitor_or_signer_pending_channel_update()
15383 {
15384 if !is_retry {
15385 log_debug!(
15386 logger,
15387 "Waiting for state machine pending changes to complete before sending stfu"
15388 );
15389 }
15390 return None;
15391 }
15392
15393 let initiator = if self.context.channel_state.is_remote_stfu_sent() {
15394 self.context.channel_state.clear_remote_stfu_sent();
15397 self.context.channel_state.set_quiescent();
15398 false
15399 } else if let Some(action) = self.quiescent_action.as_ref() {
15400 #[allow(irrefutable_let_patterns)]
15401 if let QuiescentAction::Splice { contribution, .. } = action {
15402 if self.pending_splice.is_some() {
15403 if !self.queued_contribution_can_rbf(contribution) {
15404 if !is_retry {
15405 log_debug!(
15406 logger,
15407 "Waiting for splice to lock before potentially proceeding with queued contribution"
15408 );
15409 }
15410 return None;
15411 }
15412 }
15413 }
15414
15415 log_debug!(logger, "Sending stfu as quiescence initiator");
15416 self.context.channel_state.set_local_stfu_sent();
15417 true
15418 } else {
15419 debug_assert!(
15420 false,
15421 "Either we have a pending quiescent action or need to respond to the counterparty"
15422 );
15423 false
15424 };
15425
15426 Some(msgs::Stfu { channel_id: self.context.channel_id, initiator })
15427 }
15428
15429 pub fn exit_quiescence(&mut self) -> bool {
15430 debug_assert!(!self.context.channel_state.is_local_stfu_sent());
15433 debug_assert!(!self.context.channel_state.is_remote_stfu_sent());
15434
15435 self.mark_response_received();
15436 let was_quiescent = self.context.channel_state.is_quiescent();
15437 self.context.channel_state.clear_quiescent();
15438 was_quiescent
15439 }
15440
15441 fn quiescent_negotiation_err(&mut self, err: ChannelError) -> InteractiveTxMsgError {
15442 if matches!(err, ChannelError::Abort(_)) {
15443 debug_assert!(self.context.channel_state.is_quiescent());
15444 self.exit_quiescence();
15445 }
15446 InteractiveTxMsgError::new(err, None)
15447 }
15448
15449 pub fn remove_legacy_scids_before_block(&mut self, height: u32) -> alloc::vec::Drain<'_, u64> {
15450 let end = self
15451 .funding
15452 .get_short_channel_id()
15453 .map(|current_scid| {
15454 let historical_scids = &self.context.historical_scids;
15455 historical_scids
15456 .iter()
15457 .zip(historical_scids.iter().skip(1).chain(core::iter::once(¤t_scid)))
15458 .filter(|(_, next_scid)| {
15459 let funding_height = block_from_scid(**next_scid);
15460 let drop_scid =
15461 funding_height + CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY - 1 <= height;
15462 drop_scid
15463 })
15464 .count()
15465 })
15466 .unwrap_or(0);
15467
15468 self.context.historical_scids.drain(0..end)
15471 }
15472}
15473
15474pub(super) struct OutboundV1Channel<SP: SignerProvider> {
15476 pub funding: FundingScope,
15477 pub context: ChannelContext<SP>,
15478 pub unfunded_context: UnfundedChannelContext,
15479 pub signer_pending_open_channel: bool,
15483}
15484
15485impl<SP: SignerProvider> OutboundV1Channel<SP> {
15486 pub fn abandon_unfunded_chan(&mut self, closure_reason: ClosureReason) -> ShutdownResult {
15487 self.context.force_shutdown(&self.funding, closure_reason)
15488 }
15489
15490 #[allow(dead_code)] pub fn new<ES: EntropySource, F: FeeEstimator, L: Logger>(
15492 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
15493 counterparty_node_id: PublicKey, their_features: &InitFeatures,
15494 channel_value_satoshis: u64, push_msat: u64, user_id: u128, config: &UserConfig,
15495 current_chain_height: u32, outbound_scid_alias: u64,
15496 temporary_channel_id: Option<ChannelId>, logger: L,
15497 trusted_channel_features: Option<TrustedChannelFeatures>,
15498 ) -> Result<OutboundV1Channel<SP>, APIError> {
15499 let their_dust_limit_satoshis = 0;
15503 let is_0reserve = trusted_channel_features.is_some_and(|f| f.is_0reserve());
15504 let holder_selected_channel_reserve_satoshis =
15505 get_holder_selected_channel_reserve_satoshis(
15506 channel_value_satoshis,
15507 their_dust_limit_satoshis,
15508 config,
15509 is_0reserve,
15510 )
15511 .map_err(|()| APIError::APIMisuseError {
15512 err: format!(
15513 "The channel value {channel_value_satoshis} is smaller than \
15514 {MIN_THEIR_CHAN_RESERVE_SATOSHIS}"
15515 ),
15516 })?;
15517 if holder_selected_channel_reserve_satoshis < MIN_CHAN_DUST_LIMIT_SATOSHIS && !is_0reserve {
15518 return Err(APIError::APIMisuseError {
15521 err: format!(
15522 "Holder selected channel reserve below implementation limit dust_limit_satoshis {holder_selected_channel_reserve_satoshis}"
15523 ),
15524 });
15525 }
15526
15527 let channel_keys_id = signer_provider.generate_channel_keys_id(false, user_id);
15528 let holder_signer = signer_provider.derive_channel_signer(channel_keys_id);
15529
15530 let temporary_channel_id_fn =
15531 temporary_channel_id.map(|id| move |_: &ChannelPublicKeys| id);
15532
15533 let (funding, context) = ChannelContext::new_for_outbound_channel(
15534 fee_estimator,
15535 entropy_source,
15536 signer_provider,
15537 counterparty_node_id,
15538 their_features,
15539 channel_value_satoshis,
15540 push_msat,
15541 user_id,
15542 config,
15543 current_chain_height,
15544 outbound_scid_alias,
15545 temporary_channel_id_fn,
15546 holder_selected_channel_reserve_satoshis,
15547 channel_keys_id,
15548 holder_signer,
15549 logger,
15550 )?;
15551 let unfunded_context = UnfundedChannelContext {
15552 unfunded_channel_age_ticks: 0,
15553 holder_commitment_point: HolderCommitmentPoint::new(
15554 &context.holder_signer,
15555 &context.secp_ctx,
15556 ),
15557 };
15558
15559 let chan = Self { funding, context, unfunded_context, signer_pending_open_channel: false };
15562 Ok(chan)
15563 }
15564
15565 #[rustfmt::skip]
15567 fn get_funding_created_msg<L: Logger>(&mut self, logger: &L) -> Option<msgs::FundingCreated> {
15568 let commitment_data = self.context.build_commitment_transaction(&self.funding,
15569 self.context.counterparty_next_commitment_transaction_number,
15570 &self.context.counterparty_next_commitment_point.unwrap(), false, false, logger);
15571 let counterparty_initial_commitment_tx = commitment_data.tx;
15572 let signature = {
15573 let channel_parameters = &self.funding.channel_transaction_parameters;
15574 self.context
15575 .holder_signer
15576 .sign_counterparty_commitment(
15577 channel_parameters,
15578 &counterparty_initial_commitment_tx,
15579 Vec::new(),
15580 Vec::new(),
15581 &self.context.secp_ctx,
15582 )
15583 .map(|(sig, _)| sig)
15584 .ok()
15585 };
15586
15587 if signature.is_some() && self.context.signer_pending_funding {
15588 log_trace!(logger, "Counterparty commitment signature ready for funding_created message: clearing signer_pending_funding");
15589 self.context.signer_pending_funding = false;
15590 } else if signature.is_none() {
15591 log_trace!(logger, "funding_created awaiting signer; setting signer_pending_funding");
15592 self.context.signer_pending_funding = true;
15593 };
15594
15595 signature.map(|signature| msgs::FundingCreated {
15596 temporary_channel_id: self.context.temporary_channel_id.unwrap(),
15597 funding_txid: self.funding.channel_transaction_parameters.funding_outpoint.as_ref().unwrap().txid,
15598 funding_output_index: self.funding.channel_transaction_parameters.funding_outpoint.as_ref().unwrap().index,
15599 signature,
15600 })
15601 }
15602
15603 #[rustfmt::skip]
15611 pub fn get_funding_created<L: Logger>(&mut self, funding_transaction: Transaction, funding_txo: OutPoint, is_batch_funding: bool, logger: &L)
15612 -> Result<Option<msgs::FundingCreated>, (Self, ChannelError)> {
15613 if !self.funding.is_outbound() {
15614 panic!("Tried to create outbound funding_created message on an inbound channel!");
15615 }
15616 if !matches!(
15617 self.context.channel_state, ChannelState::NegotiatingFunding(flags)
15618 if flags == (NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT)
15619 ) {
15620 panic!("Tried to get a funding_created messsage at a time other than immediately after initial handshake completion (or tried to get funding_created twice)");
15621 }
15622 self.context.assert_no_commitment_advancement(self.unfunded_context.transaction_number(), "funding_created");
15623
15624 self.funding.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
15625
15626 self.context.channel_state = ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
15629 self.context.channel_id = ChannelId::v1_from_funding_outpoint(funding_txo);
15630
15631 if funding_transaction.is_coinbase() &&
15634 self.context.minimum_depth.unwrap_or(0) > 0 &&
15635 self.context.minimum_depth.unwrap_or(0) < COINBASE_MATURITY {
15636 self.funding.minimum_depth_override = Some(COINBASE_MATURITY);
15637 }
15638
15639 debug_assert!(self.funding.funding_transaction.is_none());
15640 self.funding.funding_transaction = Some(funding_transaction);
15641 self.context.is_batch_funding = Some(()).filter(|_| is_batch_funding);
15642
15643 let funding_created = self.get_funding_created_msg(logger);
15644 Ok(funding_created)
15645 }
15646
15647 #[rustfmt::skip]
15651 pub(crate) fn maybe_handle_error_without_close<F: FeeEstimator, L: Logger>(
15652 &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator<F>, logger: &L,
15653 user_config: &UserConfig, their_features: &InitFeatures,
15654 ) -> Result<msgs::OpenChannel, ()> {
15655 self.context.maybe_downgrade_channel_features(
15656 &mut self.funding, fee_estimator, user_config, their_features,
15657 )?;
15658 self.get_open_channel(chain_hash, logger).ok_or(())
15659 }
15660
15661 pub fn is_resumable(&self) -> bool {
15663 !self.context.have_received_message()
15664 && self.unfunded_context.transaction_number() == INITIAL_COMMITMENT_NUMBER
15665 }
15666
15667 #[rustfmt::skip]
15668 pub fn get_open_channel<L: Logger>(
15669 &mut self, chain_hash: ChainHash, _logger: &L
15670 ) -> Option<msgs::OpenChannel> {
15671 if !self.funding.is_outbound() {
15672 panic!("Tried to open a channel for an inbound channel?");
15673 }
15674 if self.context.have_received_message() {
15675 panic!("Cannot generate an open_channel after we've moved forward");
15676 }
15677
15678 if self.unfunded_context.transaction_number() != INITIAL_COMMITMENT_NUMBER {
15679 panic!("Tried to send an open_channel for a channel that has already advanced");
15680 }
15681
15682 let first_per_commitment_point = match self.unfunded_context.holder_commitment_point {
15683 Some(holder_commitment_point) if holder_commitment_point.can_advance() => {
15684 self.signer_pending_open_channel = false;
15685 holder_commitment_point.next_point()
15686 },
15687 _ => {
15688 log_trace!(_logger, "Unable to generate open_channel message, waiting for commitment point");
15689 self.signer_pending_open_channel = true;
15690 return None;
15691 }
15692 };
15693 let keys = self.funding.get_holder_pubkeys();
15694
15695 Some(msgs::OpenChannel {
15696 common_fields: msgs::CommonOpenChannelFields {
15697 chain_hash,
15698 temporary_channel_id: self.context.channel_id,
15699 funding_satoshis: self.funding.get_value_satoshis(),
15700 dust_limit_satoshis: self.context.holder_dust_limit_satoshis,
15701 max_htlc_value_in_flight_msat: self.context.holder_max_htlc_value_in_flight_msat,
15702 htlc_minimum_msat: self.context.holder_htlc_minimum_msat,
15703 commitment_feerate_sat_per_1000_weight: self.context.feerate_per_kw as u32,
15704 to_self_delay: self.funding.get_holder_selected_contest_delay(),
15705 max_accepted_htlcs: self.context.holder_max_accepted_htlcs,
15706 funding_pubkey: keys.funding_pubkey,
15707 revocation_basepoint: keys.revocation_basepoint.to_public_key(),
15708 payment_basepoint: keys.payment_point,
15709 delayed_payment_basepoint: keys.delayed_payment_basepoint.to_public_key(),
15710 htlc_basepoint: keys.htlc_basepoint.to_public_key(),
15711 first_per_commitment_point,
15712 channel_flags: if self.context.config.announce_for_forwarding {1} else {0},
15713 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
15714 Some(script) => script.clone().into_inner(),
15715 None => Builder::new().into_script(),
15716 }),
15717 channel_type: Some(self.funding.get_channel_type().clone()),
15718 },
15719 push_msat: self.funding.get_value_satoshis() * 1000 - self.funding.value_to_self_msat,
15720 channel_reserve_satoshis: self.funding.holder_selected_channel_reserve_satoshis,
15721 })
15722 }
15723
15724 pub fn accept_channel(
15726 &mut self, msg: &msgs::AcceptChannel, default_limits: &ChannelHandshakeLimits,
15727 their_features: &InitFeatures,
15728 ) -> Result<(), ChannelError> {
15729 self.context.do_accept_channel_checks(
15730 &mut self.funding,
15731 default_limits,
15732 their_features,
15733 &msg.common_fields,
15734 msg.channel_reserve_satoshis,
15735 )
15736 }
15737
15738 pub fn funding_signed<L: Logger>(
15741 mut self, msg: &msgs::FundingSigned, best_block: BlockLocator, signer_provider: &SP,
15742 logger: &L,
15743 ) -> Result<
15744 (FundedChannel<SP>, ChannelMonitor<SP::EcdsaSigner>),
15745 (OutboundV1Channel<SP>, ChannelError),
15746 > {
15747 if !self.funding.is_outbound() {
15748 let err = "Received funding_signed for an inbound channel?";
15749 return Err((self, ChannelError::close(err.to_owned())));
15750 }
15751 if !matches!(self.context.channel_state, ChannelState::FundingNegotiated(_)) {
15752 let err = "Received funding_signed in strange state!";
15753 return Err((self, ChannelError::close(err.to_owned())));
15754 }
15755 let mut holder_commitment_point = match self.unfunded_context.holder_commitment_point {
15756 Some(point) => point,
15757 None => {
15758 let err = "Received funding_signed before our first commitment point was available";
15759 return Err((self, ChannelError::close(err.to_owned())));
15760 },
15761 };
15762 self.context.assert_no_commitment_advancement(
15763 holder_commitment_point.next_transaction_number(),
15764 "funding_signed",
15765 );
15766
15767 let (channel_monitor, _) = match self.initial_commitment_signed(
15768 self.context.channel_id(),
15769 msg.signature,
15770 &mut holder_commitment_point,
15771 best_block,
15772 signer_provider,
15773 logger,
15774 ) {
15775 Ok(channel_monitor) => channel_monitor,
15776 Err(err) => return Err((self, err)),
15777 };
15778
15779 log_info!(
15780 logger,
15781 "Received funding_signed from peer for channel {}",
15782 &self.context.channel_id()
15783 );
15784
15785 let mut channel = FundedChannel {
15786 funding: self.funding,
15787 context: self.context,
15788 holder_commitment_point,
15789 pending_splice: None,
15790 quiescent_action: None,
15791 };
15792
15793 let need_channel_ready = channel.check_get_channel_ready(0, logger).is_some()
15794 || channel.context.signer_pending_channel_ready;
15795 channel.monitor_updating_paused(
15796 false,
15797 false,
15798 need_channel_ready,
15799 Vec::new(),
15800 Vec::new(),
15801 Vec::new(),
15802 logger,
15803 );
15804 Ok((channel, channel_monitor))
15805 }
15806
15807 #[rustfmt::skip]
15810 pub fn signer_maybe_unblocked<L: Logger>(
15811 &mut self, chain_hash: ChainHash, logger: &L
15812 ) -> (Option<msgs::OpenChannel>, Option<msgs::FundingCreated>) {
15813 if self.unfunded_context.holder_commitment_point.is_none() {
15816 self.unfunded_context.holder_commitment_point = HolderCommitmentPoint::new(&self.context.holder_signer, &self.context.secp_ctx);
15817 }
15818 if let Some(ref mut point) = self.unfunded_context.holder_commitment_point {
15819 if !point.can_advance() {
15820 point.try_resolve_pending(&self.context.holder_signer, &self.context.secp_ctx, logger);
15821 }
15822 }
15823 let open_channel = if self.signer_pending_open_channel {
15824 log_trace!(logger, "Attempting to generate open_channel...");
15825 self.get_open_channel(chain_hash, logger)
15826 } else { None };
15827 let funding_created = if self.context.signer_pending_funding && self.funding.is_outbound() {
15828 log_trace!(logger, "Attempting to generate pending funding created...");
15829 self.get_funding_created_msg(logger)
15830 } else { None };
15831 (open_channel, funding_created)
15832 }
15833
15834 pub fn unset_funding_info(&mut self) {
15839 debug_assert!(matches!(
15840 self.context.channel_state,
15841 ChannelState::FundingNegotiated(_) if self.context.interactive_tx_signing_session.is_none()
15842 ));
15843 self.context.unset_funding_info(&mut self.funding);
15844 }
15845}
15846
15847pub(super) struct InboundV1Channel<SP: SignerProvider> {
15849 pub funding: FundingScope,
15850 pub context: ChannelContext<SP>,
15851 pub unfunded_context: UnfundedChannelContext,
15852 pub signer_pending_accept_channel: bool,
15853}
15854
15855pub(super) fn channel_type_from_open_channel(
15858 common_fields: &msgs::CommonOpenChannelFields, our_supported_features: &ChannelTypeFeatures,
15859) -> Result<ChannelTypeFeatures, ChannelError> {
15860 let channel_type = common_fields.channel_type.as_ref().ok_or_else(|| {
15861 ChannelError::close("option_channel_type assumed to be supported".to_owned())
15862 })?;
15863
15864 if channel_type.supports_any_optional_bits() {
15865 return Err(ChannelError::close(
15866 "Channel Type field contained optional bits - this is not allowed".to_owned(),
15867 ));
15868 }
15869
15870 if !channel_type.requires_static_remote_key()
15875 && !channel_type.requires_anchor_zero_fee_commitments()
15876 {
15877 return Err(ChannelError::close(
15878 "Channel Type was not understood - we require static remote key".to_owned(),
15879 ));
15880 }
15881 if channel_type.requires_anchors_zero_fee_htlc_tx()
15882 && channel_type.requires_anchor_zero_fee_commitments()
15883 {
15884 return Err(ChannelError::close(
15885 "Channel Type cannot require both anchor types".to_owned(),
15886 ));
15887 }
15888 if channel_type.requires_unknown_bits_from(&our_supported_features) {
15890 return Err(ChannelError::close("Channel Type contains unsupported features".to_owned()));
15891 }
15892 let announce_for_forwarding = if (common_fields.channel_flags & 1) == 1 { true } else { false };
15893 if channel_type.requires_scid_privacy() && announce_for_forwarding {
15894 return Err(ChannelError::close(
15895 "SCID Alias/Privacy Channel Type cannot be set on a public channel".to_owned(),
15896 ));
15897 }
15898 Ok(channel_type.clone())
15899}
15900
15901impl<SP: SignerProvider> InboundV1Channel<SP> {
15902 pub fn new<ES: EntropySource, F: FeeEstimator, L: Logger>(
15905 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
15906 counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
15907 their_features: &InitFeatures, msg: &msgs::OpenChannel, user_id: u128, config: &UserConfig,
15908 current_chain_height: u32, logger: &L,
15909 trusted_channel_features: Option<TrustedChannelFeatures>,
15910 ) -> Result<InboundV1Channel<SP>, ChannelError> {
15911 let logger = WithContext::from(
15912 logger,
15913 Some(counterparty_node_id),
15914 Some(msg.common_fields.temporary_channel_id),
15915 None,
15916 );
15917
15918 let channel_type =
15921 channel_type_from_open_channel(&msg.common_fields, our_supported_features)?;
15922
15923 let holder_selected_channel_reserve_satoshis =
15924 get_holder_selected_channel_reserve_satoshis(
15925 msg.common_fields.funding_satoshis,
15926 msg.common_fields.dust_limit_satoshis,
15927 config,
15928 trusted_channel_features.is_some_and(|f| f.is_0reserve()),
15929 )
15930 .map_err(|()| {
15931 ChannelError::close(format!(
15932 "The channel value {} is smaller than either their dust \
15933 limit {}, or {MIN_THEIR_CHAN_RESERVE_SATOSHIS}",
15934 msg.common_fields.funding_satoshis, msg.common_fields.dust_limit_satoshis,
15935 ))
15936 })?;
15937 let counterparty_pubkeys = ChannelPublicKeys {
15938 funding_pubkey: msg.common_fields.funding_pubkey,
15939 revocation_basepoint: RevocationBasepoint::from(msg.common_fields.revocation_basepoint),
15940 payment_point: msg.common_fields.payment_basepoint,
15941 delayed_payment_basepoint: DelayedPaymentBasepoint::from(
15942 msg.common_fields.delayed_payment_basepoint,
15943 ),
15944 htlc_basepoint: HtlcBasepoint::from(msg.common_fields.htlc_basepoint),
15945 };
15946
15947 let (funding, context) = ChannelContext::new_for_inbound_channel(
15948 fee_estimator,
15949 entropy_source,
15950 signer_provider,
15951 counterparty_node_id,
15952 their_features,
15953 user_id,
15954 config,
15955 current_chain_height,
15956 &&logger,
15957 trusted_channel_features,
15958 0,
15959 counterparty_pubkeys,
15960 channel_type,
15961 holder_selected_channel_reserve_satoshis,
15962 msg.channel_reserve_satoshis,
15963 msg.push_msat,
15964 msg.common_fields.clone(),
15965 )?;
15966 let unfunded_context = UnfundedChannelContext {
15967 unfunded_channel_age_ticks: 0,
15968 holder_commitment_point: HolderCommitmentPoint::new(
15969 &context.holder_signer,
15970 &context.secp_ctx,
15971 ),
15972 };
15973 let chan =
15974 Self { funding, context, unfunded_context, signer_pending_accept_channel: false };
15975 Ok(chan)
15976 }
15977
15978 pub fn accept_inbound_channel<L: Logger>(&mut self, logger: &L) -> Option<msgs::AcceptChannel> {
15983 if self.funding.is_outbound() {
15984 panic!("Tried to send accept_channel for an outbound channel?");
15985 }
15986 if !matches!(
15987 self.context.channel_state, ChannelState::NegotiatingFunding(flags)
15988 if flags == (NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT)
15989 ) {
15990 panic!("Tried to send accept_channel after channel had moved forward");
15991 }
15992 if self.unfunded_context.transaction_number() != INITIAL_COMMITMENT_NUMBER {
15993 panic!("Tried to send an accept_channel for a channel that has already advanced");
15994 }
15995
15996 self.generate_accept_channel_message(logger)
15997 }
15998
15999 #[rustfmt::skip]
16005 fn generate_accept_channel_message<L: Logger>(
16006 &mut self, _logger: &L
16007 ) -> Option<msgs::AcceptChannel> {
16008 let first_per_commitment_point = match self.unfunded_context.holder_commitment_point {
16009 Some(holder_commitment_point) if holder_commitment_point.can_advance() => {
16010 self.signer_pending_accept_channel = false;
16011 holder_commitment_point.next_point()
16012 },
16013 _ => {
16014 log_trace!(_logger, "Unable to generate accept_channel message, waiting for commitment point");
16015 self.signer_pending_accept_channel = true;
16016 return None;
16017 }
16018 };
16019 let keys = self.funding.get_holder_pubkeys();
16020
16021 Some(msgs::AcceptChannel {
16022 common_fields: msgs::CommonAcceptChannelFields {
16023 temporary_channel_id: self.context.channel_id,
16024 dust_limit_satoshis: self.context.holder_dust_limit_satoshis,
16025 max_htlc_value_in_flight_msat: self.context.holder_max_htlc_value_in_flight_msat,
16026 htlc_minimum_msat: self.context.holder_htlc_minimum_msat,
16027 minimum_depth: self.context.minimum_depth.unwrap(),
16028 to_self_delay: self.funding.get_holder_selected_contest_delay(),
16029 max_accepted_htlcs: self.context.holder_max_accepted_htlcs,
16030 funding_pubkey: keys.funding_pubkey,
16031 revocation_basepoint: keys.revocation_basepoint.to_public_key(),
16032 payment_basepoint: keys.payment_point,
16033 delayed_payment_basepoint: keys.delayed_payment_basepoint.to_public_key(),
16034 htlc_basepoint: keys.htlc_basepoint.to_public_key(),
16035 first_per_commitment_point,
16036 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
16037 Some(script) => script.clone().into_inner(),
16038 None => Builder::new().into_script(),
16039 }),
16040 channel_type: Some(self.funding.get_channel_type().clone()),
16041 },
16042 channel_reserve_satoshis: self.funding.holder_selected_channel_reserve_satoshis,
16043 })
16044 }
16045
16046 #[cfg(test)]
16051 pub fn get_accept_channel_message<L: Logger>(
16052 &mut self, logger: &L,
16053 ) -> Option<msgs::AcceptChannel> {
16054 self.generate_accept_channel_message(logger)
16055 }
16056
16057 pub fn funding_created<L: Logger>(
16058 mut self, msg: &msgs::FundingCreated, best_block: BlockLocator, signer_provider: &SP,
16059 logger: &L,
16060 ) -> Result<
16061 (FundedChannel<SP>, Option<msgs::FundingSigned>, ChannelMonitor<SP::EcdsaSigner>),
16062 (Self, ChannelError),
16063 > {
16064 if self.funding.is_outbound() {
16065 let err = "Received funding_created for an outbound channel?";
16066 return Err((self, ChannelError::close(err.to_owned())));
16067 }
16068 if !matches!(
16069 self.context.channel_state, ChannelState::NegotiatingFunding(flags)
16070 if flags == (NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT)
16071 ) {
16072 let err = "Received funding_created after we got the channel!";
16076 return Err((self, ChannelError::close(err.to_owned())));
16077 }
16078 let mut holder_commitment_point = match self.unfunded_context.holder_commitment_point {
16079 Some(point) => point,
16080 None => {
16081 let err =
16082 "Received funding_created before our first commitment point was available";
16083 return Err((self, ChannelError::close(err.to_owned())));
16084 },
16085 };
16086 self.context.assert_no_commitment_advancement(
16087 holder_commitment_point.next_transaction_number(),
16088 "funding_created",
16089 );
16090
16091 let funding_txo = OutPoint { txid: msg.funding_txid, index: msg.funding_output_index };
16092 self.funding.channel_transaction_parameters.funding_outpoint = Some(funding_txo);
16093
16094 let (channel_monitor, counterparty_initial_commitment_tx) = match self
16095 .initial_commitment_signed(
16096 ChannelId::v1_from_funding_outpoint(funding_txo),
16097 msg.signature,
16098 &mut holder_commitment_point,
16099 best_block,
16100 signer_provider,
16101 logger,
16102 ) {
16103 Ok(channel_monitor) => channel_monitor,
16104 Err(err) => return Err((self, err)),
16105 };
16106
16107 let funding_signed = self.context.get_funding_signed_msg(
16108 &self.funding.channel_transaction_parameters,
16109 logger,
16110 counterparty_initial_commitment_tx,
16111 );
16112
16113 log_info!(
16114 logger,
16115 "{} funding_signed for peer for channel {}",
16116 if funding_signed.is_some() { "Generated" } else { "Waiting for signature on" },
16117 &self.context.channel_id()
16118 );
16119
16120 let mut channel = FundedChannel {
16123 funding: self.funding,
16124 context: self.context,
16125 holder_commitment_point,
16126 pending_splice: None,
16127 quiescent_action: None,
16128 };
16129 let need_channel_ready = channel.check_get_channel_ready(0, logger).is_some()
16130 || channel.context.signer_pending_channel_ready;
16131 channel.monitor_updating_paused(
16132 false,
16133 false,
16134 need_channel_ready,
16135 Vec::new(),
16136 Vec::new(),
16137 Vec::new(),
16138 logger,
16139 );
16140
16141 Ok((channel, funding_signed, channel_monitor))
16142 }
16143
16144 #[rustfmt::skip]
16147 pub fn signer_maybe_unblocked<L: Logger>(
16148 &mut self, logger: &L
16149 ) -> Option<msgs::AcceptChannel> {
16150 if self.unfunded_context.holder_commitment_point.is_none() {
16151 self.unfunded_context.holder_commitment_point = HolderCommitmentPoint::new(&self.context.holder_signer, &self.context.secp_ctx);
16152 }
16153 if let Some(ref mut point) = self.unfunded_context.holder_commitment_point {
16154 if !point.can_advance() {
16155 point.try_resolve_pending(&self.context.holder_signer, &self.context.secp_ctx, logger);
16156 }
16157 }
16158 if self.signer_pending_accept_channel {
16159 log_trace!(logger, "Attempting to generate accept_channel...");
16160 self.generate_accept_channel_message(logger)
16161 } else { None }
16162 }
16163}
16164
16165pub(super) struct PendingV2Channel<SP: SignerProvider> {
16167 pub funding: FundingScope,
16168 pub context: ChannelContext<SP>,
16169 pub unfunded_context: UnfundedChannelContext,
16170 pub funding_negotiation_context: FundingNegotiationContext,
16171 pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
16173}
16174
16175impl<SP: SignerProvider> PendingV2Channel<SP> {
16176 #[allow(dead_code)] #[rustfmt::skip]
16178 pub fn new_outbound<ES: EntropySource, F: FeeEstimator, L: Logger>(
16179 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
16180 counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64,
16181 funding_inputs: Vec<ConfirmedUtxo>, user_id: u128, config: &UserConfig,
16182 current_chain_height: u32, outbound_scid_alias: u64, funding_confirmation_target: ConfirmationTarget,
16183 logger: L, trusted_channel_features: Option<TrustedChannelFeatures>,
16184 ) -> Result<Self, APIError> {
16185 let channel_keys_id = signer_provider.generate_channel_keys_id(false, user_id);
16186 let holder_signer = signer_provider.derive_channel_signer(channel_keys_id);
16187
16188 let temporary_channel_id_fn = Some(|pubkeys: &ChannelPublicKeys| {
16189 ChannelId::temporary_v2_from_revocation_basepoint(&pubkeys.revocation_basepoint)
16190 });
16191
16192 let holder_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
16193 funding_satoshis, MIN_CHAN_DUST_LIMIT_SATOSHIS, trusted_channel_features.is_some_and(|f| f.is_0reserve())
16194 ).map_err(|()| APIError::APIMisuseError {
16195 err: format!(
16196 "The channel value {funding_satoshis} is smaller than their dust \
16197 limit {MIN_CHAN_DUST_LIMIT_SATOSHIS}"
16198 )
16199 })?;
16200 let funding_feerate_sat_per_1000_weight = fee_estimator.bounded_sat_per_1000_weight(funding_confirmation_target);
16201 let funding_tx_locktime = LockTime::from_height(current_chain_height)
16202 .map_err(|_| APIError::APIMisuseError {
16203 err: format!(
16204 "Provided current chain height of {} doesn't make sense for a height-based timelock for the funding transaction",
16205 current_chain_height) })?;
16206
16207 let (funding, context) = ChannelContext::new_for_outbound_channel(
16208 fee_estimator,
16209 entropy_source,
16210 signer_provider,
16211 counterparty_node_id,
16212 their_features,
16213 funding_satoshis,
16214 0,
16215 user_id,
16216 config,
16217 current_chain_height,
16218 outbound_scid_alias,
16219 temporary_channel_id_fn,
16220 holder_selected_channel_reserve_satoshis,
16221 channel_keys_id,
16222 holder_signer,
16223 logger,
16224 )?;
16225 let unfunded_context = UnfundedChannelContext {
16226 unfunded_channel_age_ticks: 0,
16227 holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
16228 };
16229 let funding_negotiation_context = FundingNegotiationContext {
16230 is_initiator: true,
16231 our_funding_contribution: SignedAmount::from_sat(funding_satoshis as i64),
16232 funding_tx_locktime,
16233 funding_feerate_sat_per_1000_weight,
16234 shared_funding_input: None,
16235 our_funding_inputs: funding_inputs,
16236 our_funding_outputs: Vec::new(),
16237 };
16238 let chan = Self {
16239 funding,
16240 context,
16241 unfunded_context,
16242 funding_negotiation_context,
16243 interactive_tx_constructor: None,
16244 };
16245 Ok(chan)
16246 }
16247
16248 pub(crate) fn maybe_handle_error_without_close<F: FeeEstimator>(
16252 &mut self, chain_hash: ChainHash, fee_estimator: &LowerBoundedFeeEstimator<F>,
16253 user_config: &UserConfig, their_features: &InitFeatures,
16254 ) -> Result<msgs::OpenChannelV2, ()> {
16255 self.context.maybe_downgrade_channel_features(
16256 &mut self.funding,
16257 fee_estimator,
16258 user_config,
16259 their_features,
16260 )?;
16261 Ok(self.get_open_channel_v2(chain_hash))
16262 }
16263
16264 #[rustfmt::skip]
16265 pub fn get_open_channel_v2(&self, chain_hash: ChainHash) -> msgs::OpenChannelV2 {
16266 if !self.funding.is_outbound() {
16267 debug_assert!(false, "Tried to send open_channel2 for an inbound channel?");
16268 }
16269
16270 if self.context.have_received_message() {
16271 debug_assert!(false, "Cannot generate an open_channel2 after we've moved forward");
16272 }
16273
16274 if self.unfunded_context.transaction_number() != INITIAL_COMMITMENT_NUMBER {
16275 debug_assert!(false, "Tried to send an open_channel2 for a channel that has already advanced");
16276 }
16277
16278 let first_per_commitment_point = self.context.holder_signer
16279 .get_per_commitment_point(self.unfunded_context.transaction_number(),
16280 &self.context.secp_ctx)
16281 .expect("TODO: async signing is not yet supported for commitment points in v2 channel establishment");
16282 let second_per_commitment_point = self.context.holder_signer
16283 .get_per_commitment_point(self.unfunded_context.transaction_number() - 1,
16284 &self.context.secp_ctx)
16285 .expect("TODO: async signing is not yet supported for commitment points in v2 channel establishment");
16286 let keys = self.funding.get_holder_pubkeys();
16287
16288 msgs::OpenChannelV2 {
16289 common_fields: msgs::CommonOpenChannelFields {
16290 chain_hash,
16291 temporary_channel_id: self.context.temporary_channel_id.unwrap(),
16292 funding_satoshis: self.funding.get_value_satoshis(),
16293 dust_limit_satoshis: self.context.holder_dust_limit_satoshis,
16294 max_htlc_value_in_flight_msat: self.context.holder_max_htlc_value_in_flight_msat,
16295 htlc_minimum_msat: self.context.holder_htlc_minimum_msat,
16296 commitment_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
16297 to_self_delay: self.funding.get_holder_selected_contest_delay(),
16298 max_accepted_htlcs: self.context.holder_max_accepted_htlcs,
16299 funding_pubkey: keys.funding_pubkey,
16300 revocation_basepoint: keys.revocation_basepoint.to_public_key(),
16301 payment_basepoint: keys.payment_point,
16302 delayed_payment_basepoint: keys.delayed_payment_basepoint.to_public_key(),
16303 htlc_basepoint: keys.htlc_basepoint.to_public_key(),
16304 first_per_commitment_point,
16305 channel_flags: if self.context.config.announce_for_forwarding {1} else {0},
16306 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
16307 Some(script) => script.clone().into_inner(),
16308 None => Builder::new().into_script(),
16309 }),
16310 channel_type: Some(self.funding.get_channel_type().clone()),
16311 },
16312 funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
16313 second_per_commitment_point,
16314 locktime: self.funding_negotiation_context.funding_tx_locktime.to_consensus_u32(),
16315 require_confirmed_inputs: None,
16316 disable_channel_reserve: (self.funding.holder_selected_channel_reserve_satoshis == 0).then_some(()),
16317 }
16318 }
16319
16320 #[allow(dead_code)] #[rustfmt::skip]
16325 pub fn new_inbound<ES: EntropySource, F: FeeEstimator, L: Logger>(
16326 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
16327 holder_node_id: PublicKey, counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
16328 their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
16329 user_id: u128, config: &UserConfig, current_chain_height: u32, logger: &L, trusted_channel_features: Option<TrustedChannelFeatures>,
16330 ) -> Result<Self, ChannelError> {
16331 let (our_funding_contribution, our_funding_contribution_sats) = (SignedAmount::ZERO, 0u64);
16333 let our_funding_inputs = Vec::new();
16334
16335 let channel_value_satoshis =
16336 our_funding_contribution_sats.saturating_add(msg.common_fields.funding_satoshis);
16337 let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
16338 channel_value_satoshis, MIN_CHAN_DUST_LIMIT_SATOSHIS, msg.disable_channel_reserve.is_some()
16339 ).map_err(|()| ChannelError::close(format!(
16340 "The channel value {channel_value_satoshis} is smaller than our dust limit {MIN_CHAN_DUST_LIMIT_SATOSHIS}"
16341 )))?;
16342 let their_dust_limit_satoshis = msg.common_fields.dust_limit_satoshis;
16343 let holder_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
16344 channel_value_satoshis, their_dust_limit_satoshis, trusted_channel_features.is_some_and(|f| f.is_0reserve())
16345 ).map_err(|()| ChannelError::close(format!(
16346 "The channel value {channel_value_satoshis} is smaller than their dust limit {their_dust_limit_satoshis}"
16347 )))?;
16348
16349 let channel_type = channel_type_from_open_channel(&msg.common_fields, our_supported_features)?;
16350
16351 let counterparty_pubkeys = ChannelPublicKeys {
16352 funding_pubkey: msg.common_fields.funding_pubkey,
16353 revocation_basepoint: RevocationBasepoint(msg.common_fields.revocation_basepoint),
16354 payment_point: msg.common_fields.payment_basepoint,
16355 delayed_payment_basepoint: DelayedPaymentBasepoint(msg.common_fields.delayed_payment_basepoint),
16356 htlc_basepoint: HtlcBasepoint(msg.common_fields.htlc_basepoint)
16357 };
16358
16359 let (funding, mut context) = ChannelContext::new_for_inbound_channel(
16360 fee_estimator,
16361 entropy_source,
16362 signer_provider,
16363 counterparty_node_id,
16364 their_features,
16365 user_id,
16366 config,
16367 current_chain_height,
16368 logger,
16369 trusted_channel_features,
16370 our_funding_contribution_sats,
16371 counterparty_pubkeys,
16372 channel_type,
16373 holder_selected_channel_reserve_satoshis,
16374 counterparty_selected_channel_reserve_satoshis,
16375 0 ,
16376 msg.common_fields.clone(),
16377 )?;
16378 let channel_id = ChannelId::v2_from_revocation_basepoints(
16379 &funding.get_holder_pubkeys().revocation_basepoint,
16380 &funding.get_counterparty_pubkeys().revocation_basepoint);
16381 context.channel_id = channel_id;
16382
16383 let funding_negotiation_context = FundingNegotiationContext {
16384 is_initiator: false,
16385 our_funding_contribution,
16386 funding_tx_locktime: LockTime::from_consensus(msg.locktime),
16387 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
16388 shared_funding_input: None,
16389 our_funding_inputs: our_funding_inputs.clone(),
16390 our_funding_outputs: Vec::new(),
16391 };
16392 let shared_funding_output = TxOut {
16393 value: Amount::from_sat(funding.get_value_satoshis()),
16394 script_pubkey: funding.get_funding_redeemscript().to_p2wsh(),
16395 };
16396
16397 let interactive_tx_constructor = Some(InteractiveTxConstructor::new_for_inbound(
16398 InteractiveTxConstructorArgs {
16399 entropy_source,
16400 holder_node_id,
16401 counterparty_node_id,
16402 channel_id: context.channel_id,
16403 feerate_sat_per_kw: funding_negotiation_context.funding_feerate_sat_per_1000_weight,
16404 funding_tx_locktime: funding_negotiation_context.funding_tx_locktime,
16405 inputs_to_contribute: our_funding_inputs,
16406 shared_funding_input: None,
16407 shared_funding_output: SharedOwnedOutput::new(shared_funding_output, our_funding_contribution_sats),
16408 outputs_to_contribute: funding_negotiation_context.our_funding_outputs.clone(),
16409 }
16410 ));
16411
16412 let unfunded_context = UnfundedChannelContext {
16413 unfunded_channel_age_ticks: 0,
16414 holder_commitment_point: HolderCommitmentPoint::new(&context.holder_signer, &context.secp_ctx),
16415 };
16416 Ok(Self {
16417 funding,
16418 context,
16419 funding_negotiation_context,
16420 interactive_tx_constructor,
16421 unfunded_context,
16422 })
16423 }
16424
16425 #[allow(dead_code)] #[rustfmt::skip]
16431 pub fn accept_inbound_dual_funded_channel(&self) -> msgs::AcceptChannelV2 {
16432 if self.funding.is_outbound() {
16433 debug_assert!(false, "Tried to send accept_channel for an outbound channel?");
16434 }
16435 if !matches!(
16436 self.context.channel_state, ChannelState::NegotiatingFunding(flags)
16437 if flags == (NegotiatingFundingFlags::OUR_INIT_SENT | NegotiatingFundingFlags::THEIR_INIT_SENT)
16438 ) {
16439 debug_assert!(false, "Tried to send accept_channel2 after channel had moved forward");
16440 }
16441 if self.unfunded_context.transaction_number() != INITIAL_COMMITMENT_NUMBER {
16442 debug_assert!(false, "Tried to send an accept_channel2 for a channel that has already advanced");
16443 }
16444
16445 self.generate_accept_channel_v2_message()
16446 }
16447
16448 #[allow(dead_code)] fn generate_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
16455 let first_per_commitment_point = self.context.holder_signer.get_per_commitment_point(
16456 self.unfunded_context.transaction_number(), &self.context.secp_ctx)
16457 .expect("TODO: async signing is not yet supported for commitment points in v2 channel establishment");
16458 let second_per_commitment_point = self.context.holder_signer.get_per_commitment_point(
16459 self.unfunded_context.transaction_number() - 1, &self.context.secp_ctx)
16460 .expect("TODO: async signing is not yet supported for commitment points in v2 channel establishment");
16461 let keys = self.funding.get_holder_pubkeys();
16462
16463 msgs::AcceptChannelV2 {
16464 common_fields: msgs::CommonAcceptChannelFields {
16465 temporary_channel_id: self.context.temporary_channel_id.unwrap(),
16466 dust_limit_satoshis: self.context.holder_dust_limit_satoshis,
16467 max_htlc_value_in_flight_msat: self.context.holder_max_htlc_value_in_flight_msat,
16468 htlc_minimum_msat: self.context.holder_htlc_minimum_msat,
16469 minimum_depth: self.context.minimum_depth.unwrap(),
16470 to_self_delay: self.funding.get_holder_selected_contest_delay(),
16471 max_accepted_htlcs: self.context.holder_max_accepted_htlcs,
16472 funding_pubkey: keys.funding_pubkey,
16473 revocation_basepoint: keys.revocation_basepoint.to_public_key(),
16474 payment_basepoint: keys.payment_point,
16475 delayed_payment_basepoint: keys.delayed_payment_basepoint.to_public_key(),
16476 htlc_basepoint: keys.htlc_basepoint.to_public_key(),
16477 first_per_commitment_point,
16478 shutdown_scriptpubkey: Some(match &self.context.shutdown_scriptpubkey {
16479 Some(script) => script.clone().into_inner(),
16480 None => Builder::new().into_script(),
16481 }),
16482 channel_type: Some(self.funding.get_channel_type().clone()),
16483 },
16484 funding_satoshis: self.funding_negotiation_context.our_funding_contribution.to_sat()
16485 as u64,
16486 second_per_commitment_point,
16487 require_confirmed_inputs: None,
16488 disable_channel_reserve: (self.funding.holder_selected_channel_reserve_satoshis == 0)
16489 .then_some(()),
16490 }
16491 }
16492
16493 #[cfg(test)]
16498 #[allow(dead_code)] pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
16500 self.generate_accept_channel_v2_message()
16501 }
16502}
16503
16504pub(super) fn get_initial_channel_type(
16507 config: &UserConfig, their_features: &InitFeatures,
16508) -> ChannelTypeFeatures {
16509 let mut ret = ChannelTypeFeatures::only_static_remote_key();
16514 if !config.channel_handshake_config.announce_for_forwarding
16515 && config.channel_handshake_config.negotiate_scid_privacy
16516 && their_features.supports_scid_privacy()
16517 {
16518 ret.set_scid_privacy_required();
16519 }
16520
16521 if config.channel_handshake_config.negotiate_anchor_zero_fee_commitments
16526 && their_features.supports_anchor_zero_fee_commitments()
16527 {
16528 ret.set_anchor_zero_fee_commitments_required();
16529 ret.clear_static_remote_key();
16531 } else if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx
16532 && their_features.supports_anchors_zero_fee_htlc_tx()
16533 {
16534 ret.set_anchors_zero_fee_htlc_tx_required();
16535 }
16536
16537 ret
16538}
16539
16540const SERIALIZATION_VERSION: u8 = 4;
16541const MIN_SERIALIZATION_VERSION: u8 = 4;
16542
16543impl Writeable for ChannelUpdateStatus {
16544 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
16545 match self {
16549 ChannelUpdateStatus::Enabled => 0u8.write(writer)?,
16550 ChannelUpdateStatus::DisabledStaged(_) => 0u8.write(writer)?,
16551 ChannelUpdateStatus::EnabledStaged(_) => 1u8.write(writer)?,
16552 ChannelUpdateStatus::Disabled => 1u8.write(writer)?,
16553 }
16554 Ok(())
16555 }
16556}
16557
16558impl Readable for ChannelUpdateStatus {
16559 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
16560 Ok(match <u8 as Readable>::read(reader)? {
16561 0 => ChannelUpdateStatus::Enabled,
16562 1 => ChannelUpdateStatus::Disabled,
16563 _ => return Err(DecodeError::InvalidValue),
16564 })
16565 }
16566}
16567
16568impl Writeable for AnnouncementSigsState {
16569 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
16570 match self {
16573 AnnouncementSigsState::NotSent => 0u8.write(writer),
16574 AnnouncementSigsState::MessageSent => 0u8.write(writer),
16575 AnnouncementSigsState::Committed => 0u8.write(writer),
16576 AnnouncementSigsState::PeerReceived => 1u8.write(writer),
16577 }
16578 }
16579}
16580
16581impl Readable for AnnouncementSigsState {
16582 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
16583 Ok(match <u8 as Readable>::read(reader)? {
16584 0 => AnnouncementSigsState::NotSent,
16585 1 => AnnouncementSigsState::PeerReceived,
16586 _ => return Err(DecodeError::InvalidValue),
16587 })
16588 }
16589}
16590
16591impl<SP: SignerProvider> Writeable for FundedChannel<SP> {
16592 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
16593 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
16597
16598 let user_id_low = self.context.user_id as u64;
16602 user_id_low.write(writer)?;
16603
16604 writer.write_all(&[0; 8])?;
16608
16609 self.context.channel_id.write(writer)?;
16610 {
16611 let mut channel_state = self.context.channel_state;
16612 match channel_state {
16613 ChannelState::AwaitingChannelReady(_) => {},
16614 ChannelState::ChannelReady(_) => {
16615 channel_state.clear_local_stfu_sent();
16616 channel_state.clear_remote_stfu_sent();
16617 if self.should_reset_pending_splice_state(true)
16618 || !self.has_pending_splice_awaiting_signatures()
16619 {
16620 channel_state.clear_quiescent();
16625 }
16626 },
16627 ChannelState::FundingNegotiated(_)
16628 if self.context.interactive_tx_signing_session.is_some() => {},
16629 _ => debug_assert!(false, "Pre-funded/shutdown channels should not be written"),
16630 }
16631 channel_state.set_peer_disconnected();
16632 channel_state.to_u32().write(writer)?;
16633 }
16634 self.funding.get_value_satoshis().write(writer)?;
16635
16636 self.context.latest_monitor_update_id.write(writer)?;
16637
16638 let shutdown_scriptpubkey = self.context.shutdown_scriptpubkey.as_ref();
16641 match shutdown_scriptpubkey.and_then(|script| script.as_legacy_pubkey()) {
16642 Some(shutdown_pubkey) => shutdown_pubkey.write(writer)?,
16643 None => [0u8; PUBLIC_KEY_SIZE].write(writer)?,
16644 }
16645 self.context.destination_script.write(writer)?;
16646
16647 self.holder_commitment_point.next_transaction_number().write(writer)?;
16648 self.context.counterparty_next_commitment_transaction_number.write(writer)?;
16649 self.funding.value_to_self_msat.write(writer)?;
16650
16651 let mut dropped_inbound_htlcs = 0;
16652 for htlc in self.context.pending_inbound_htlcs.iter() {
16653 if let InboundHTLCState::RemoteAnnounced(_) = htlc.state {
16654 dropped_inbound_htlcs += 1;
16655 }
16656 }
16657 let mut removed_htlc_attribution_data: Vec<&Option<AttributionData>> = Vec::new();
16658 #[cfg_attr(not(test), allow(unused_mut))]
16659 let mut inbound_committed_update_adds: Vec<&InboundUpdateAdd> = Vec::new();
16660 (self.context.pending_inbound_htlcs.len() as u64 - dropped_inbound_htlcs).write(writer)?;
16661 for htlc in self.context.pending_inbound_htlcs.iter() {
16662 if let &InboundHTLCState::RemoteAnnounced(_) = &htlc.state {
16663 continue; }
16665 htlc.htlc_id.write(writer)?;
16666 htlc.amount_msat.write(writer)?;
16667 htlc.cltv_expiry.write(writer)?;
16668 htlc.payment_hash.write(writer)?;
16669 match &htlc.state {
16670 &InboundHTLCState::RemoteAnnounced(_) => unreachable!(),
16671 &InboundHTLCState::AwaitingRemoteRevokeToAnnounce(ref htlc_resolution) => {
16672 1u8.write(writer)?;
16673 htlc_resolution.write(writer)?;
16674 },
16675 &InboundHTLCState::AwaitingAnnouncedRemoteRevoke(ref htlc_resolution) => {
16676 2u8.write(writer)?;
16677 htlc_resolution.write(writer)?;
16678 },
16679 &InboundHTLCState::Committed { update_add_htlc: ref _update_add } => {
16680 3u8.write(writer)?;
16681 #[cfg(test)]
16682 inbound_committed_update_adds.push(_update_add);
16683 },
16684 &InboundHTLCState::LocalRemoved(ref removal_reason) => {
16685 4u8.write(writer)?;
16686 match removal_reason {
16687 InboundHTLCRemovalReason::FailRelay(msgs::OnionErrorPacket {
16688 data,
16689 attribution_data,
16690 }) => {
16691 0u8.write(writer)?;
16692 data.write(writer)?;
16693 removed_htlc_attribution_data.push(&attribution_data);
16694 },
16695 InboundHTLCRemovalReason::FailMalformed {
16696 sha256_of_onion: hash,
16697 failure_code: code,
16698 } => {
16699 1u8.write(writer)?;
16700 (hash, code).write(writer)?;
16701 },
16702 InboundHTLCRemovalReason::Fulfill { preimage, attribution_data } => {
16703 2u8.write(writer)?;
16704 preimage.write(writer)?;
16705 removed_htlc_attribution_data.push(&attribution_data);
16706 },
16707 }
16708 },
16709 }
16710 }
16711
16712 let mut preimages: Vec<Option<&PaymentPreimage>> = vec![];
16715 let mut fulfill_attribution_data = vec![];
16716 let mut pending_outbound_skimmed_fees: Vec<Option<u64>> = Vec::new();
16717 let mut pending_outbound_blinding_points: Vec<Option<PublicKey>> = Vec::new();
16718 let mut pending_outbound_held_htlc_flags: Vec<Option<()>> = Vec::new();
16719 let mut pending_outbound_accountable: Vec<bool> = Vec::new();
16720
16721 (self.context.pending_outbound_htlcs.len() as u64).write(writer)?;
16722 for htlc in self.context.pending_outbound_htlcs.iter() {
16723 htlc.htlc_id.write(writer)?;
16724 htlc.amount_msat.write(writer)?;
16725 htlc.cltv_expiry.write(writer)?;
16726 htlc.payment_hash.write(writer)?;
16727 htlc.source.write(writer)?;
16728 match &htlc.state {
16729 &OutboundHTLCState::LocalAnnounced(ref onion_packet) => {
16730 0u8.write(writer)?;
16731 onion_packet.write(writer)?;
16732 },
16733 &OutboundHTLCState::Committed => {
16734 1u8.write(writer)?;
16735 },
16736 &OutboundHTLCState::RemoteRemoved(_) => {
16737 1u8.write(writer)?;
16740 },
16741 &OutboundHTLCState::AwaitingRemoteRevokeToRemove(ref outcome) => {
16742 3u8.write(writer)?;
16743 if let OutboundHTLCOutcome::Success { preimage, attribution_data } = outcome {
16744 preimages.push(Some(preimage));
16745 fulfill_attribution_data.push(attribution_data);
16746 }
16747 let reason: Option<&HTLCFailReason> = outcome.into();
16748 reason.write(writer)?;
16749 },
16750 &OutboundHTLCState::AwaitingRemovedRemoteRevoke(ref outcome) => {
16751 4u8.write(writer)?;
16752 if let OutboundHTLCOutcome::Success { preimage, attribution_data } = outcome {
16753 preimages.push(Some(preimage));
16754 fulfill_attribution_data.push(attribution_data);
16755 }
16756 let reason: Option<&HTLCFailReason> = outcome.into();
16757 reason.write(writer)?;
16758 },
16759 }
16760 pending_outbound_skimmed_fees.push(htlc.skimmed_fee_msat);
16761 pending_outbound_blinding_points.push(htlc.blinding_point);
16762 pending_outbound_held_htlc_flags.push(htlc.hold_htlc);
16763 pending_outbound_accountable.push(htlc.accountable);
16764 }
16765
16766 let holding_cell_htlc_update_count = self.context.holding_cell_htlc_updates.len();
16767 let mut holding_cell_skimmed_fees: Vec<Option<u64>> =
16768 Vec::with_capacity(holding_cell_htlc_update_count);
16769 let mut holding_cell_blinding_points: Vec<Option<PublicKey>> =
16770 Vec::with_capacity(holding_cell_htlc_update_count);
16771 let mut holding_cell_attribution_data: Vec<Option<&AttributionData>> =
16772 Vec::with_capacity(holding_cell_htlc_update_count);
16773 let mut holding_cell_held_htlc_flags: Vec<Option<()>> =
16774 Vec::with_capacity(holding_cell_htlc_update_count);
16775 let mut holding_cell_accountable_flags: Vec<bool> =
16776 Vec::with_capacity(holding_cell_htlc_update_count);
16777 let mut malformed_htlcs: Vec<(u64, u16, [u8; 32])> = Vec::new();
16779 (holding_cell_htlc_update_count as u64).write(writer)?;
16780 for update in self.context.holding_cell_htlc_updates.iter() {
16781 match update {
16782 &HTLCUpdateAwaitingACK::AddHTLC {
16783 ref amount_msat,
16784 ref cltv_expiry,
16785 ref payment_hash,
16786 ref source,
16787 ref onion_routing_packet,
16788 blinding_point,
16789 skimmed_fee_msat,
16790 hold_htlc,
16791 accountable,
16792 } => {
16793 0u8.write(writer)?;
16794 amount_msat.write(writer)?;
16795 cltv_expiry.write(writer)?;
16796 payment_hash.write(writer)?;
16797 source.write(writer)?;
16798 onion_routing_packet.write(writer)?;
16799
16800 holding_cell_skimmed_fees.push(skimmed_fee_msat);
16801 holding_cell_blinding_points.push(blinding_point);
16802 holding_cell_held_htlc_flags.push(hold_htlc);
16803 holding_cell_accountable_flags.push(accountable);
16804 },
16805 &HTLCUpdateAwaitingACK::ClaimHTLC {
16806 ref payment_preimage,
16807 ref htlc_id,
16808 ref attribution_data,
16809 } => {
16810 1u8.write(writer)?;
16811 payment_preimage.write(writer)?;
16812 htlc_id.write(writer)?;
16813
16814 holding_cell_attribution_data.push(attribution_data.as_ref());
16816 },
16817 &HTLCUpdateAwaitingACK::FailHTLC { ref htlc_id, ref err_packet } => {
16818 2u8.write(writer)?;
16819 htlc_id.write(writer)?;
16820 err_packet.data.write(writer)?;
16821
16822 holding_cell_attribution_data.push(err_packet.attribution_data.as_ref());
16824 },
16825 &HTLCUpdateAwaitingACK::FailMalformedHTLC {
16826 htlc_id,
16827 failure_code,
16828 sha256_of_onion,
16829 } => {
16830 malformed_htlcs.push((htlc_id, failure_code, sha256_of_onion));
16833
16834 2u8.write(writer)?;
16835 htlc_id.write(writer)?;
16836 Vec::<u8>::new().write(writer)?;
16837
16838 holding_cell_attribution_data.push(None);
16841 },
16842 }
16843 }
16844
16845 match self.context.resend_order {
16846 RAACommitmentOrder::CommitmentFirst => 0u8.write(writer)?,
16847 RAACommitmentOrder::RevokeAndACKFirst => 1u8.write(writer)?,
16848 }
16849
16850 self.context.monitor_pending_channel_ready.write(writer)?;
16851 self.context.monitor_pending_revoke_and_ack.write(writer)?;
16852 self.context.monitor_pending_commitment_signed.write(writer)?;
16853
16854 (self.context.monitor_pending_forwards.len() as u64).write(writer)?;
16855 for &(ref pending_forward, ref htlc_id) in self.context.monitor_pending_forwards.iter() {
16856 pending_forward.write(writer)?;
16857 htlc_id.write(writer)?;
16858 }
16859
16860 (self.context.monitor_pending_failures.len() as u64).write(writer)?;
16861 for &(ref htlc_source, ref payment_hash, ref fail_reason) in
16862 self.context.monitor_pending_failures.iter()
16863 {
16864 htlc_source.write(writer)?;
16865 payment_hash.write(writer)?;
16866 fail_reason.write(writer)?;
16867 }
16868
16869 if self.funding.is_outbound() {
16870 self.context.pending_update_fee.map(|(a, _)| a).write(writer)?;
16871 } else if let Some((feerate, FeeUpdateState::AwaitingRemoteRevokeToAnnounce)) =
16872 self.context.pending_update_fee
16873 {
16874 Some(feerate).write(writer)?;
16875 } else {
16876 None::<u32>.write(writer)?;
16879 }
16880 self.context.holding_cell_update_fee.write(writer)?;
16881
16882 self.context.next_holder_htlc_id.write(writer)?;
16883 (self.context.next_counterparty_htlc_id - dropped_inbound_htlcs).write(writer)?;
16884 self.context.update_time_counter.write(writer)?;
16885 self.context.feerate_per_kw.write(writer)?;
16886
16887 0u8.write(writer)?;
16892
16893 self.funding.funding_tx_confirmed_in.write(writer)?;
16894 self.funding.funding_tx_confirmation_height.write(writer)?;
16895 self.funding.short_channel_id.write(writer)?;
16896
16897 self.context.counterparty_dust_limit_satoshis.write(writer)?;
16898 self.context.holder_dust_limit_satoshis.write(writer)?;
16899 self.context.counterparty_max_htlc_value_in_flight_msat.write(writer)?;
16900
16901 self.funding.counterparty_selected_channel_reserve_satoshis.unwrap_or(0).write(writer)?;
16903
16904 self.context.counterparty_htlc_minimum_msat.write(writer)?;
16905 self.context.holder_htlc_minimum_msat.write(writer)?;
16906 self.context.counterparty_max_accepted_htlcs.write(writer)?;
16907
16908 self.context.minimum_depth.unwrap_or(0).write(writer)?;
16910
16911 match &self.context.counterparty_forwarding_info {
16912 Some(info) => {
16913 1u8.write(writer)?;
16914 info.fee_base_msat.write(writer)?;
16915 info.fee_proportional_millionths.write(writer)?;
16916 info.cltv_expiry_delta.write(writer)?;
16917 },
16918 None => 0u8.write(writer)?,
16919 }
16920
16921 self.funding.channel_transaction_parameters.write(writer)?;
16922 self.funding.funding_transaction.write(writer)?;
16923
16924 self.context.counterparty_next_commitment_point.write(writer)?;
16925 self.context.counterparty_current_commitment_point.write(writer)?;
16926 self.context.counterparty_node_id.write(writer)?;
16927
16928 self.context.counterparty_shutdown_scriptpubkey.write(writer)?;
16929
16930 self.context.commitment_secrets.write(writer)?;
16931
16932 self.context.channel_update_status.write(writer)?;
16933
16934 let chan_type =
16939 if self.funding.get_channel_type() != &ChannelTypeFeatures::only_static_remote_key() {
16940 Some(self.funding.get_channel_type())
16941 } else {
16942 None
16943 };
16944
16945 let legacy_reserve_satoshis = get_legacy_default_holder_selected_channel_reserve_satoshis(
16950 self.funding.get_value_satoshis(),
16951 );
16952 let serialized_holder_selected_reserve =
16953 if self.funding.holder_selected_channel_reserve_satoshis != legacy_reserve_satoshis {
16954 Some(self.funding.holder_selected_channel_reserve_satoshis)
16955 } else {
16956 None
16957 };
16958
16959 let legacy_max_in_flight_msat = get_legacy_default_holder_max_htlc_value_in_flight_msat(
16960 self.funding.get_value_satoshis(),
16961 );
16962 let serialized_holder_htlc_max_in_flight =
16963 if self.context.holder_max_htlc_value_in_flight_msat != legacy_max_in_flight_msat {
16964 Some(self.context.holder_max_htlc_value_in_flight_msat)
16965 } else {
16966 None
16967 };
16968
16969 let channel_pending_event_emitted = Some(self.context.channel_pending_event_emitted);
16970 let initial_channel_ready_event_emitted =
16971 Some(self.context.initial_channel_ready_event_emitted);
16972 let funding_tx_broadcast_safe_event_emitted =
16973 Some(self.context.funding_tx_broadcast_safe_event_emitted);
16974
16975 let user_id_high_opt = Some((self.context.user_id >> 64) as u64);
16979
16980 let holder_max_accepted_htlcs =
16981 if self.context.holder_max_accepted_htlcs == DEFAULT_MAX_HTLCS {
16982 None
16983 } else {
16984 Some(self.context.holder_max_accepted_htlcs)
16985 };
16986
16987 let mut monitor_pending_update_adds = None;
16988 if !self.context.monitor_pending_update_adds.is_empty() {
16989 monitor_pending_update_adds = Some(&self.context.monitor_pending_update_adds);
16990 }
16991 let is_manual_broadcast = Some(self.context.is_manual_broadcast);
16992
16993 let has_0reserve =
16997 (self.funding.holder_selected_channel_reserve_satoshis == 0).then_some(());
16998 let holder_commitment_point_previous_revoked =
16999 self.holder_commitment_point.previous_revoked_point();
17000 let holder_commitment_point_last_revoked =
17001 self.holder_commitment_point.last_revoked_point();
17002 let holder_commitment_point_current = self.holder_commitment_point.current_point();
17003 let holder_commitment_point_next = self.holder_commitment_point.next_point();
17004 let holder_commitment_point_pending_next = self.holder_commitment_point.pending_next_point;
17005
17006 let reset_funding_negotiation = self.should_reset_pending_splice_state(true);
17009 let should_persist_pending_splice =
17010 !reset_funding_negotiation || !self.negotiated_candidates().is_empty();
17011 let pending_splice = should_persist_pending_splice
17012 .then(|| ())
17013 .and_then(|_| self.pending_splice.as_ref())
17014 .map(|pending_funding| PendingFundingWriteable {
17015 pending_funding,
17016 reset_funding_negotiation,
17017 });
17018
17019 let monitor_pending_tx_signatures =
17020 self.context.monitor_pending_tx_signatures.then_some(());
17021
17022 write_tlv_fields!(writer, {
17023 (0, self.context.announcement_sigs, option),
17024 (1, self.context.minimum_depth, option),
17031 (2, chan_type, option), (3, self.funding.counterparty_selected_channel_reserve_satoshis, option),
17034 (4, serialized_holder_selected_reserve, option),
17035 (5, self.context.config, required),
17036 (6, serialized_holder_htlc_max_in_flight, option),
17037 (7, self.context.shutdown_scriptpubkey, option),
17038 (8, self.context.blocked_monitor_updates, optional_vec),
17039 (9, self.context.target_closing_feerate_sats_per_kw, option),
17040 (10, monitor_pending_update_adds, option), (11, self.context.monitor_pending_finalized_fulfills, required_vec),
17042 (12, monitor_pending_tx_signatures, option), (13, self.context.channel_creation_height, required),
17044 (15, preimages, required_vec),
17045 (17, self.context.announcement_sigs_state, required),
17046 (19, self.context.latest_inbound_scid_alias, option),
17047 (21, self.context.outbound_scid_alias, required),
17048 (23, initial_channel_ready_event_emitted, option),
17049 (25, user_id_high_opt, option),
17050 (27, self.context.channel_keys_id, required),
17051 (28, holder_max_accepted_htlcs, option),
17052 (29, self.context.temporary_channel_id, option),
17053 (31, channel_pending_event_emitted, option),
17054 (35, pending_outbound_skimmed_fees, optional_vec),
17055 (37, holding_cell_skimmed_fees, optional_vec),
17056 (38, self.context.is_batch_funding, option),
17057 (39, pending_outbound_blinding_points, optional_vec),
17058 (41, holding_cell_blinding_points, optional_vec),
17059 (43, malformed_htlcs, optional_vec), (45, holder_commitment_point_next, required),
17061 (47, holder_commitment_point_pending_next, option),
17062 (49, self.context.local_initiated_shutdown, option), (51, is_manual_broadcast, option), (53, funding_tx_broadcast_safe_event_emitted, option), (55, removed_htlc_attribution_data, optional_vec), (57, holding_cell_attribution_data, optional_vec), (58, self.context.interactive_tx_signing_session, option), (59, self.funding.minimum_depth_override, option), (60, self.context.historical_scids, optional_vec), (61, fulfill_attribution_data, optional_vec), (63, holder_commitment_point_current, option), (64, pending_splice, option), (67, pending_outbound_held_htlc_flags, optional_vec), (69, holding_cell_held_htlc_flags, optional_vec), (70, has_0reserve, option), (71, holder_commitment_point_previous_revoked, option), (73, holder_commitment_point_last_revoked, option), (75, inbound_committed_update_adds, optional_vec),
17080 (77, holding_cell_accountable_flags, optional_vec), (79, pending_outbound_accountable, optional_vec), });
17083
17084 Ok(())
17085 }
17086}
17087
17088impl<'a, 'b, 'c, ES: EntropySource, SP: SignerProvider>
17089 ReadableArgs<(&'a ES, &'b SP, &'c ChannelTypeFeatures)> for FundedChannel<SP>
17090{
17091 fn read<R: io::Read>(
17092 reader: &mut R, args: (&'a ES, &'b SP, &'c ChannelTypeFeatures),
17093 ) -> Result<Self, DecodeError> {
17094 let (entropy_source, signer_provider, our_supported_features) = args;
17095 let ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
17096 if ver <= 2 {
17097 return Err(DecodeError::UnknownVersion);
17098 }
17099
17100 let user_id_low: u64 = Readable::read(reader)?;
17104
17105 let mut config = LegacyChannelConfig::default();
17106 {
17107 let mut _val: u64 = Readable::read(reader)?;
17109 }
17110
17111 let channel_id: ChannelId = Readable::read(reader)?;
17112 let channel_state = ChannelState::from_u32(Readable::read(reader)?)
17113 .map_err(|_| DecodeError::InvalidValue)?;
17114 let channel_value_satoshis = Readable::read(reader)?;
17115
17116 let latest_monitor_update_id = Readable::read(reader)?;
17117
17118 let mut shutdown_scriptpubkey = match <PublicKey as Readable>::read(reader) {
17120 Ok(pubkey) => Some(ShutdownScript::new_p2wpkh_from_pubkey(pubkey)),
17121 Err(_) => None,
17122 };
17123 let destination_script = Readable::read(reader)?;
17124
17125 let holder_commitment_next_transaction_number = Readable::read(reader)?;
17126 let counterparty_next_commitment_transaction_number = Readable::read(reader)?;
17127 let value_to_self_msat = Readable::read(reader)?;
17128
17129 let pending_inbound_htlc_count: u64 = Readable::read(reader)?;
17130
17131 let mut pending_inbound_htlcs = Vec::with_capacity(cmp::min(
17132 pending_inbound_htlc_count as usize,
17133 DEFAULT_MAX_HTLCS as usize,
17134 ));
17135 for _ in 0..pending_inbound_htlc_count {
17136 pending_inbound_htlcs.push(InboundHTLCOutput {
17137 htlc_id: Readable::read(reader)?,
17138 amount_msat: Readable::read(reader)?,
17139 cltv_expiry: Readable::read(reader)?,
17140 payment_hash: Readable::read(reader)?,
17141 state: match <u8 as Readable>::read(reader)? {
17142 1 => {
17143 let resolution = if ver <= 3 {
17144 InboundHTLCResolution::Resolved {
17145 pending_htlc_status: Readable::read(reader)?,
17146 }
17147 } else {
17148 Readable::read(reader)?
17149 };
17150 InboundHTLCState::AwaitingRemoteRevokeToAnnounce(resolution)
17151 },
17152 2 => {
17153 let resolution = if ver <= 3 {
17154 InboundHTLCResolution::Resolved {
17155 pending_htlc_status: Readable::read(reader)?,
17156 }
17157 } else {
17158 Readable::read(reader)?
17159 };
17160 InboundHTLCState::AwaitingAnnouncedRemoteRevoke(resolution)
17161 },
17162 3 => InboundHTLCState::Committed { update_add_htlc: InboundUpdateAdd::Legacy },
17163 4 => {
17164 let reason = match <u8 as Readable>::read(reader)? {
17165 0 => InboundHTLCRemovalReason::FailRelay(msgs::OnionErrorPacket {
17166 data: Readable::read(reader)?,
17167 attribution_data: None,
17168 }),
17169 1 => {
17170 let (hash, code) = Readable::read(reader)?;
17171 InboundHTLCRemovalReason::FailMalformed {
17172 sha256_of_onion: hash,
17173 failure_code: code,
17174 }
17175 },
17176 2 => InboundHTLCRemovalReason::Fulfill {
17177 preimage: Readable::read(reader)?,
17178 attribution_data: None,
17179 },
17180 _ => return Err(DecodeError::InvalidValue),
17181 };
17182 InboundHTLCState::LocalRemoved(reason)
17183 },
17184 _ => return Err(DecodeError::InvalidValue),
17185 },
17186 });
17187 }
17188
17189 let pending_outbound_htlc_count: u64 = Readable::read(reader)?;
17190 let mut pending_outbound_htlcs = Vec::with_capacity(cmp::min(
17191 pending_outbound_htlc_count as usize,
17192 DEFAULT_MAX_HTLCS as usize,
17193 ));
17194 for _ in 0..pending_outbound_htlc_count {
17195 pending_outbound_htlcs.push(OutboundHTLCOutput {
17196 htlc_id: Readable::read(reader)?,
17197 amount_msat: Readable::read(reader)?,
17198 cltv_expiry: Readable::read(reader)?,
17199 payment_hash: Readable::read(reader)?,
17200 source: Readable::read(reader)?,
17201 state: match <u8 as Readable>::read(reader)? {
17202 0 => OutboundHTLCState::LocalAnnounced(Box::new(Readable::read(reader)?)),
17203 1 => OutboundHTLCState::Committed,
17204 2 => {
17205 let option: Option<HTLCFailReason> = Readable::read(reader)?;
17206 let outcome = match option {
17207 Some(r) => OutboundHTLCOutcome::Failure(r),
17208 None => OutboundHTLCOutcome::Success {
17210 preimage: PaymentPreimage([0u8; 32]),
17211 attribution_data: None,
17212 },
17213 };
17214 OutboundHTLCState::RemoteRemoved(outcome)
17215 },
17216 3 => {
17217 let option: Option<HTLCFailReason> = Readable::read(reader)?;
17218 let outcome = match option {
17219 Some(r) => OutboundHTLCOutcome::Failure(r),
17220 None => OutboundHTLCOutcome::Success {
17222 preimage: PaymentPreimage([0u8; 32]),
17223 attribution_data: None,
17224 },
17225 };
17226 OutboundHTLCState::AwaitingRemoteRevokeToRemove(outcome)
17227 },
17228 4 => {
17229 let option: Option<HTLCFailReason> = Readable::read(reader)?;
17230 let outcome = match option {
17231 Some(r) => OutboundHTLCOutcome::Failure(r),
17232 None => OutboundHTLCOutcome::Success {
17234 preimage: PaymentPreimage([0u8; 32]),
17235 attribution_data: None,
17236 },
17237 };
17238 OutboundHTLCState::AwaitingRemovedRemoteRevoke(outcome)
17239 },
17240 _ => return Err(DecodeError::InvalidValue),
17241 },
17242 skimmed_fee_msat: None,
17243 blinding_point: None,
17244 send_timestamp: None,
17245 hold_htlc: None,
17246 accountable: false,
17247 });
17248 }
17249
17250 let holding_cell_htlc_update_count: u64 = Readable::read(reader)?;
17251 let mut holding_cell_htlc_updates = Vec::with_capacity(cmp::min(
17252 holding_cell_htlc_update_count as usize,
17253 DEFAULT_MAX_HTLCS as usize * 2,
17254 ));
17255 for _ in 0..holding_cell_htlc_update_count {
17256 holding_cell_htlc_updates.push(match <u8 as Readable>::read(reader)? {
17257 0 => HTLCUpdateAwaitingACK::AddHTLC {
17258 amount_msat: Readable::read(reader)?,
17259 cltv_expiry: Readable::read(reader)?,
17260 payment_hash: Readable::read(reader)?,
17261 source: Readable::read(reader)?,
17262 onion_routing_packet: Readable::read(reader)?,
17263 skimmed_fee_msat: None,
17264 blinding_point: None,
17265 hold_htlc: None,
17266 accountable: false,
17267 },
17268 1 => HTLCUpdateAwaitingACK::ClaimHTLC {
17269 payment_preimage: Readable::read(reader)?,
17270 htlc_id: Readable::read(reader)?,
17271 attribution_data: None,
17272 },
17273 2 => HTLCUpdateAwaitingACK::FailHTLC {
17274 htlc_id: Readable::read(reader)?,
17275 err_packet: OnionErrorPacket {
17276 data: Readable::read(reader)?,
17277 attribution_data: None,
17278 },
17279 },
17280 _ => return Err(DecodeError::InvalidValue),
17281 });
17282 }
17283
17284 let resend_order = match <u8 as Readable>::read(reader)? {
17285 0 => RAACommitmentOrder::CommitmentFirst,
17286 1 => RAACommitmentOrder::RevokeAndACKFirst,
17287 _ => return Err(DecodeError::InvalidValue),
17288 };
17289
17290 let monitor_pending_channel_ready = Readable::read(reader)?;
17291 let monitor_pending_revoke_and_ack = Readable::read(reader)?;
17292 let monitor_pending_commitment_signed = Readable::read(reader)?;
17293
17294 let monitor_pending_forwards_count: u64 = Readable::read(reader)?;
17295 let mut monitor_pending_forwards = Vec::with_capacity(cmp::min(
17296 monitor_pending_forwards_count as usize,
17297 DEFAULT_MAX_HTLCS as usize,
17298 ));
17299 for _ in 0..monitor_pending_forwards_count {
17300 monitor_pending_forwards.push((Readable::read(reader)?, Readable::read(reader)?));
17301 }
17302
17303 let monitor_pending_failures_count: u64 = Readable::read(reader)?;
17304 let mut monitor_pending_failures = Vec::with_capacity(cmp::min(
17305 monitor_pending_failures_count as usize,
17306 DEFAULT_MAX_HTLCS as usize,
17307 ));
17308 for _ in 0..monitor_pending_failures_count {
17309 monitor_pending_failures.push((
17310 Readable::read(reader)?,
17311 Readable::read(reader)?,
17312 Readable::read(reader)?,
17313 ));
17314 }
17315
17316 let pending_update_fee_value: Option<u32> = Readable::read(reader)?;
17317
17318 let holding_cell_update_fee = Readable::read(reader)?;
17319
17320 let next_holder_htlc_id = Readable::read(reader)?;
17321 let next_counterparty_htlc_id = Readable::read(reader)?;
17322 let update_time_counter = Readable::read(reader)?;
17323 let feerate_per_kw = Readable::read(reader)?;
17324
17325 match <u8 as Readable>::read(reader)? {
17330 0 => {},
17331 1 => {
17332 let _: u32 = Readable::read(reader)?;
17333 let _: u64 = Readable::read(reader)?;
17334 let _: Signature = Readable::read(reader)?;
17335 },
17336 _ => return Err(DecodeError::InvalidValue),
17337 }
17338
17339 let funding_tx_confirmed_in = Readable::read(reader)?;
17340 let funding_tx_confirmation_height = Readable::read(reader)?;
17341 let short_channel_id = Readable::read(reader)?;
17342
17343 let counterparty_dust_limit_satoshis = Readable::read(reader)?;
17344 let holder_dust_limit_satoshis = Readable::read(reader)?;
17345 let counterparty_max_htlc_value_in_flight_msat = Readable::read(reader)?;
17346 let mut counterparty_selected_channel_reserve_satoshis = None;
17347 {
17348 let _dummy: u64 = Readable::read(reader)?;
17350 }
17351 let counterparty_htlc_minimum_msat = Readable::read(reader)?;
17352 let holder_htlc_minimum_msat = Readable::read(reader)?;
17353 let counterparty_max_accepted_htlcs = Readable::read(reader)?;
17354
17355 let mut minimum_depth = None;
17356 {
17357 let _dummy: u32 = Readable::read(reader)?;
17359 }
17360
17361 let counterparty_forwarding_info = match <u8 as Readable>::read(reader)? {
17362 0 => None,
17363 1 => Some(CounterpartyForwardingInfo {
17364 fee_base_msat: Readable::read(reader)?,
17365 fee_proportional_millionths: Readable::read(reader)?,
17366 cltv_expiry_delta: Readable::read(reader)?,
17367 }),
17368 _ => return Err(DecodeError::InvalidValue),
17369 };
17370
17371 let channel_parameters: ChannelTransactionParameters =
17372 ReadableArgs::<Option<u64>>::read(reader, Some(channel_value_satoshis))?;
17373 let funding_transaction: Option<Transaction> = Readable::read(reader)?;
17374
17375 let counterparty_next_commitment_point = Readable::read(reader)?;
17376
17377 let counterparty_current_commitment_point = Readable::read(reader)?;
17378 let counterparty_node_id = Readable::read(reader)?;
17379
17380 let counterparty_shutdown_scriptpubkey = Readable::read(reader)?;
17381 let commitment_secrets = Readable::read(reader)?;
17382
17383 let channel_update_status = Readable::read(reader)?;
17384
17385 let pending_update_fee = if let Some(feerate) = pending_update_fee_value {
17386 Some((
17387 feerate,
17388 if channel_parameters.is_outbound_from_holder {
17389 FeeUpdateState::Outbound
17390 } else {
17391 FeeUpdateState::AwaitingRemoteRevokeToAnnounce
17392 },
17393 ))
17394 } else {
17395 None
17396 };
17397
17398 let mut announcement_sigs = None;
17399 let mut target_closing_feerate_sats_per_kw = None;
17400 let mut monitor_pending_finalized_fulfills = Some(Vec::new());
17401 let mut holder_selected_channel_reserve_satoshis = Some(
17402 get_legacy_default_holder_selected_channel_reserve_satoshis(channel_value_satoshis),
17403 );
17404
17405 let mut holder_max_htlc_value_in_flight_msat =
17406 Some(get_legacy_default_holder_max_htlc_value_in_flight_msat(channel_value_satoshis));
17407 let mut channel_type = None;
17408 let mut channel_creation_height = 0u32;
17409 let mut preimages: Vec<Option<PaymentPreimage>> = Vec::new();
17412 let mut fulfill_attribution_data: Option<Vec<Option<AttributionData>>> = None;
17413
17414 let mut announcement_sigs_state = AnnouncementSigsState::NotSent;
17417 let mut latest_inbound_scid_alias = None;
17418 let mut outbound_scid_alias = 0u64;
17419 let mut channel_pending_event_emitted = None;
17420 let mut initial_channel_ready_event_emitted = None;
17421 let mut funding_tx_broadcast_safe_event_emitted = None;
17422
17423 let mut user_id_high_opt: Option<u64> = None;
17424 let mut channel_keys_id = [0u8; 32];
17425 let mut temporary_channel_id: Option<ChannelId> = None;
17426 let mut holder_max_accepted_htlcs: Option<u16> = None;
17427
17428 let mut blocked_monitor_updates = Some(Vec::new());
17429
17430 let mut pending_outbound_skimmed_fees_opt: Option<Vec<Option<u64>>> = None;
17431 let mut holding_cell_skimmed_fees_opt: Option<Vec<Option<u64>>> = None;
17432
17433 let mut is_batch_funding: Option<()> = None;
17434
17435 let mut local_initiated_shutdown: Option<()> = None;
17436
17437 let mut pending_outbound_blinding_points_opt: Option<Vec<Option<PublicKey>>> = None;
17438 let mut holding_cell_blinding_points_opt: Option<Vec<Option<PublicKey>>> = None;
17439
17440 let mut removed_htlc_attribution_data: Option<Vec<Option<AttributionData>>> = None;
17441 let mut holding_cell_attribution_data: Option<Vec<Option<AttributionData>>> = None;
17442
17443 let mut malformed_htlcs: Option<Vec<(u64, u16, [u8; 32])>> = None;
17444 let mut monitor_pending_update_adds: Option<Vec<msgs::UpdateAddHTLC>> = None;
17445
17446 let mut _has_0reserve: Option<()> = None;
17447 let mut holder_commitment_point_previous_revoked_opt: Option<PublicKey> = None;
17448 let mut holder_commitment_point_last_revoked_opt: Option<PublicKey> = None;
17449 let mut holder_commitment_point_current_opt: Option<PublicKey> = None;
17450 let mut holder_commitment_point_next_opt: Option<PublicKey> = None;
17451 let mut holder_commitment_point_pending_next_opt: Option<PublicKey> = None;
17452 let mut is_manual_broadcast = None;
17453
17454 let mut historical_scids = Some(Vec::new());
17455
17456 let mut interactive_tx_signing_session: Option<InteractiveTxSigningSession> = None;
17457
17458 let mut minimum_depth_override: Option<u32> = None;
17459
17460 let mut pending_splice: Option<PendingFunding> = None;
17461
17462 let mut pending_outbound_held_htlc_flags_opt: Option<Vec<Option<()>>> = None;
17463 let mut holding_cell_held_htlc_flags_opt: Option<Vec<Option<()>>> = None;
17464 let mut inbound_committed_update_adds_opt: Option<Vec<InboundUpdateAdd>> = None;
17465 let mut holding_cell_accountable: Option<Vec<bool>> = None;
17466 let mut pending_outbound_accountable: Option<Vec<bool>> = None;
17467
17468 let mut monitor_pending_tx_signatures: Option<()> = None;
17469
17470 read_tlv_fields!(reader, {
17471 (0, announcement_sigs, option),
17472 (1, minimum_depth, option),
17473 (2, channel_type, option),
17474 (3, counterparty_selected_channel_reserve_satoshis, option),
17475 (4, holder_selected_channel_reserve_satoshis, option),
17476 (5, config, required),
17477 (6, holder_max_htlc_value_in_flight_msat, option),
17478 (7, shutdown_scriptpubkey, option),
17479 (8, blocked_monitor_updates, optional_vec),
17480 (9, target_closing_feerate_sats_per_kw, option),
17481 (10, monitor_pending_update_adds, option), (11, monitor_pending_finalized_fulfills, optional_vec),
17483 (12, monitor_pending_tx_signatures, option), (13, channel_creation_height, required),
17485 (15, preimages, required_vec), (17, announcement_sigs_state, required),
17487 (19, latest_inbound_scid_alias, option),
17488 (21, outbound_scid_alias, required),
17489 (23, initial_channel_ready_event_emitted, option),
17490 (25, user_id_high_opt, option),
17491 (27, channel_keys_id, required),
17492 (28, holder_max_accepted_htlcs, option),
17493 (29, temporary_channel_id, option),
17494 (31, channel_pending_event_emitted, option),
17495 (35, pending_outbound_skimmed_fees_opt, optional_vec),
17496 (37, holding_cell_skimmed_fees_opt, optional_vec),
17497 (38, is_batch_funding, option),
17498 (39, pending_outbound_blinding_points_opt, optional_vec),
17499 (41, holding_cell_blinding_points_opt, optional_vec),
17500 (43, malformed_htlcs, optional_vec), (45, holder_commitment_point_next_opt, option),
17502 (47, holder_commitment_point_pending_next_opt, option),
17503 (49, local_initiated_shutdown, option),
17504 (51, is_manual_broadcast, option),
17505 (53, funding_tx_broadcast_safe_event_emitted, option),
17506 (55, removed_htlc_attribution_data, optional_vec), (57, holding_cell_attribution_data, optional_vec), (58, interactive_tx_signing_session, option), (59, minimum_depth_override, option), (60, historical_scids, optional_vec), (61, fulfill_attribution_data, optional_vec), (63, holder_commitment_point_current_opt, option), (64, pending_splice, option), (67, pending_outbound_held_htlc_flags_opt, optional_vec), (69, holding_cell_held_htlc_flags_opt, optional_vec), (70, _has_0reserve, option), (71, holder_commitment_point_previous_revoked_opt, option), (73, holder_commitment_point_last_revoked_opt, option), (75, inbound_committed_update_adds_opt, optional_vec),
17521 (77, holding_cell_accountable, optional_vec), (79, pending_outbound_accountable, optional_vec), });
17524
17525 let holder_signer = signer_provider.derive_channel_signer(channel_keys_id);
17526
17527 let mut iter = preimages.into_iter();
17528 let mut fulfill_attribution_data_iter = fulfill_attribution_data.map(Vec::into_iter);
17529 for htlc in pending_outbound_htlcs.iter_mut() {
17530 match &mut htlc.state {
17531 OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Success {
17532 ref mut preimage,
17533 ref mut attribution_data,
17534 })
17535 | OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Success {
17536 ref mut preimage,
17537 ref mut attribution_data,
17538 }) => {
17539 debug_assert_eq!(preimage, &PaymentPreimage([0u8; 32]));
17541 *preimage = iter.next().flatten().ok_or(DecodeError::InvalidValue)?;
17543
17544 *attribution_data = fulfill_attribution_data_iter
17545 .as_mut()
17546 .and_then(Iterator::next)
17547 .ok_or(DecodeError::InvalidValue)?;
17548 },
17549 _ => {},
17550 }
17551 }
17552 if iter.next().is_some() {
17554 return Err(DecodeError::InvalidValue);
17555 }
17556
17557 if let Some(channel_type) = channel_type {
17558 let chan_features = verify_channel_type_features(Some(channel_type), None)?;
17559
17560 if chan_features != channel_parameters.channel_type_features {
17561 return Err(DecodeError::InvalidValue);
17562 }
17563 }
17564 let chan_type = &channel_parameters.channel_type_features;
17565 if chan_type.supports_any_optional_bits()
17566 || chan_type.requires_unknown_bits_from(&our_supported_features)
17567 {
17568 return Err(DecodeError::UnknownRequiredFeature);
17571 }
17572
17573 let mut secp_ctx = Secp256k1::new();
17574 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
17575
17576 let user_id = user_id_low as u128 + ((user_id_high_opt.unwrap_or(0) as u128) << 64);
17580
17581 let holder_max_accepted_htlcs = holder_max_accepted_htlcs.unwrap_or(DEFAULT_MAX_HTLCS);
17582
17583 if let Some(skimmed_fees) = pending_outbound_skimmed_fees_opt {
17584 let mut iter = skimmed_fees.into_iter();
17585 for htlc in pending_outbound_htlcs.iter_mut() {
17586 htlc.skimmed_fee_msat = iter.next().ok_or(DecodeError::InvalidValue)?;
17587 }
17588 if iter.next().is_some() {
17590 return Err(DecodeError::InvalidValue);
17591 }
17592 }
17593 if let Some(skimmed_fees) = holding_cell_skimmed_fees_opt {
17594 let mut iter = skimmed_fees.into_iter();
17595 for htlc in holding_cell_htlc_updates.iter_mut() {
17596 if let HTLCUpdateAwaitingACK::AddHTLC { ref mut skimmed_fee_msat, .. } = htlc {
17597 *skimmed_fee_msat = iter.next().ok_or(DecodeError::InvalidValue)?;
17598 }
17599 }
17600 if iter.next().is_some() {
17602 return Err(DecodeError::InvalidValue);
17603 }
17604 }
17605 if let Some(blinding_pts) = pending_outbound_blinding_points_opt {
17606 let mut iter = blinding_pts.into_iter();
17607 for htlc in pending_outbound_htlcs.iter_mut() {
17608 htlc.blinding_point = iter.next().ok_or(DecodeError::InvalidValue)?;
17609 }
17610 if iter.next().is_some() {
17612 return Err(DecodeError::InvalidValue);
17613 }
17614 }
17615 if let Some(blinding_pts) = holding_cell_blinding_points_opt {
17616 let mut iter = blinding_pts.into_iter();
17617 for htlc in holding_cell_htlc_updates.iter_mut() {
17618 if let HTLCUpdateAwaitingACK::AddHTLC { ref mut blinding_point, .. } = htlc {
17619 *blinding_point = iter.next().ok_or(DecodeError::InvalidValue)?;
17620 }
17621 }
17622 if iter.next().is_some() {
17624 return Err(DecodeError::InvalidValue);
17625 }
17626 }
17627 if let Some(held_htlcs) = pending_outbound_held_htlc_flags_opt {
17628 let mut iter = held_htlcs.into_iter();
17629 for htlc in pending_outbound_htlcs.iter_mut() {
17630 htlc.hold_htlc = iter.next().ok_or(DecodeError::InvalidValue)?;
17631 }
17632 if iter.next().is_some() {
17634 return Err(DecodeError::InvalidValue);
17635 }
17636 }
17637 if let Some(held_htlcs) = holding_cell_held_htlc_flags_opt {
17638 let mut iter = held_htlcs.into_iter();
17639 for htlc in holding_cell_htlc_updates.iter_mut() {
17640 if let HTLCUpdateAwaitingACK::AddHTLC { ref mut hold_htlc, .. } = htlc {
17641 *hold_htlc = iter.next().ok_or(DecodeError::InvalidValue)?;
17642 }
17643 }
17644 if iter.next().is_some() {
17646 return Err(DecodeError::InvalidValue);
17647 }
17648 }
17649 if let Some(update_adds) = inbound_committed_update_adds_opt {
17650 let mut iter = update_adds.into_iter();
17651 for htlc in pending_inbound_htlcs.iter_mut() {
17652 if let InboundHTLCState::Committed { ref mut update_add_htlc } = htlc.state {
17653 *update_add_htlc = iter.next().ok_or(DecodeError::InvalidValue)?;
17654 }
17655 }
17656 if iter.next().is_some() {
17657 return Err(DecodeError::InvalidValue);
17658 }
17659 }
17660
17661 if let Some(accountable_htlcs) = holding_cell_accountable {
17662 let mut iter = accountable_htlcs.into_iter();
17663 for htlc in holding_cell_htlc_updates.iter_mut() {
17664 if let HTLCUpdateAwaitingACK::AddHTLC { ref mut accountable, .. } = htlc {
17665 *accountable = iter.next().ok_or(DecodeError::InvalidValue)?;
17666 }
17667 }
17668 if iter.next().is_some() {
17670 return Err(DecodeError::InvalidValue);
17671 }
17672 }
17673 if let Some(accountable_htlcs) = pending_outbound_accountable {
17674 let mut iter = accountable_htlcs.into_iter();
17675 for htlc in pending_outbound_htlcs.iter_mut() {
17676 htlc.accountable = iter.next().ok_or(DecodeError::InvalidValue)?;
17677 }
17678 if iter.next().is_some() {
17680 return Err(DecodeError::InvalidValue);
17681 }
17682 }
17683 if let Some(attribution_data_list) = removed_htlc_attribution_data {
17684 let mut removed_htlcs = pending_inbound_htlcs.iter_mut().filter_map(|status| {
17685 if let InboundHTLCState::LocalRemoved(reason) = &mut status.state {
17686 match reason {
17687 InboundHTLCRemovalReason::FailRelay(ref mut packet) => {
17688 Some(&mut packet.attribution_data)
17689 },
17690 InboundHTLCRemovalReason::Fulfill { ref mut attribution_data, .. } => {
17691 Some(attribution_data)
17692 },
17693 _ => None,
17694 }
17695 } else {
17696 None
17697 }
17698 });
17699
17700 for attribution_data in attribution_data_list {
17701 *removed_htlcs.next().ok_or(DecodeError::InvalidValue)? = attribution_data;
17702 }
17703 if removed_htlcs.next().is_some() {
17704 return Err(DecodeError::InvalidValue);
17705 }
17706 }
17707
17708 if let Some(attribution_data_list) = holding_cell_attribution_data {
17709 let mut holding_cell_htlcs =
17710 holding_cell_htlc_updates.iter_mut().filter_map(|upd| match upd {
17711 HTLCUpdateAwaitingACK::FailHTLC {
17712 err_packet: OnionErrorPacket { ref mut attribution_data, .. },
17713 ..
17714 } => Some(attribution_data),
17715 HTLCUpdateAwaitingACK::ClaimHTLC { attribution_data, .. } => {
17716 Some(attribution_data)
17717 },
17718 _ => None,
17719 });
17720
17721 for attribution_data in attribution_data_list {
17722 *holding_cell_htlcs.next().ok_or(DecodeError::InvalidValue)? = attribution_data;
17723 }
17724 if holding_cell_htlcs.next().is_some() {
17725 return Err(DecodeError::InvalidValue);
17726 }
17727 }
17728
17729 if let Some(malformed_htlcs) = malformed_htlcs {
17730 for (malformed_htlc_id, failure_code, sha256_of_onion) in malformed_htlcs {
17731 let htlc_idx = holding_cell_htlc_updates
17732 .iter()
17733 .position(|htlc| {
17734 if let HTLCUpdateAwaitingACK::FailHTLC { htlc_id, err_packet } = htlc {
17735 let matches = *htlc_id == malformed_htlc_id;
17736 if matches {
17737 debug_assert!(err_packet.data.is_empty())
17738 }
17739 matches
17740 } else {
17741 false
17742 }
17743 })
17744 .ok_or(DecodeError::InvalidValue)?;
17745 let malformed_htlc = HTLCUpdateAwaitingACK::FailMalformedHTLC {
17746 htlc_id: malformed_htlc_id,
17747 failure_code,
17748 sha256_of_onion,
17749 };
17750 let _ =
17751 core::mem::replace(&mut holding_cell_htlc_updates[htlc_idx], malformed_htlc);
17752 }
17753 }
17754
17755 let holder_commitment_point = {
17759 let current_point = holder_commitment_point_current_opt.or_else(|| {
17760 if holder_commitment_next_transaction_number == INITIAL_COMMITMENT_NUMBER {
17761 None
17762 } else {
17763 holder_signer
17766 .get_per_commitment_point(
17767 holder_commitment_next_transaction_number + 1,
17768 &secp_ctx,
17769 )
17770 .ok()
17771 }
17772 });
17773
17774 let previous_revoked_point =
17775 holder_commitment_point_previous_revoked_opt.or_else(|| {
17776 if holder_commitment_next_transaction_number > INITIAL_COMMITMENT_NUMBER - 3 {
17777 None
17778 } else {
17779 Some(holder_signer
17780 .get_per_commitment_point(
17781 holder_commitment_next_transaction_number + 3,
17782 &secp_ctx,
17783 )
17784 .expect("Must be able to derive the previous revoked commitment point upon channel restoration"))
17785 }
17786 });
17787 let last_revoked_point = holder_commitment_point_last_revoked_opt.or_else(|| {
17788 if holder_commitment_next_transaction_number > INITIAL_COMMITMENT_NUMBER - 2 {
17789 None
17790 } else {
17791 Some(holder_signer
17792 .get_per_commitment_point(
17793 holder_commitment_next_transaction_number + 2,
17794 &secp_ctx,
17795 )
17796 .expect("Must be able to derive the last revoked commitment point upon channel restoration"))
17797 }
17798 });
17799
17800 match (holder_commitment_point_next_opt, holder_commitment_point_pending_next_opt) {
17801 (Some(next_point), pending_next_point) => HolderCommitmentPoint {
17802 next_transaction_number: holder_commitment_next_transaction_number,
17803 previous_revoked_point,
17804 last_revoked_point,
17805 current_point,
17806 next_point,
17807 pending_next_point,
17808 },
17809 (_, _) => {
17810 let next_point = holder_signer
17811 .get_per_commitment_point(holder_commitment_next_transaction_number, &secp_ctx)
17812 .expect(
17813 "Must be able to derive the next commitment point upon channel restoration",
17814 );
17815 let pending_next_point = holder_signer
17816 .get_per_commitment_point(
17817 holder_commitment_next_transaction_number - 1,
17818 &secp_ctx,
17819 )
17820 .expect(
17821 "Must be able to derive the pending next commitment point upon channel restoration",
17822 );
17823 HolderCommitmentPoint {
17824 next_transaction_number: holder_commitment_next_transaction_number,
17825 previous_revoked_point,
17826 last_revoked_point,
17827 current_point,
17828 next_point,
17829 pending_next_point: Some(pending_next_point),
17830 }
17831 },
17832 }
17833 };
17834
17835 if let Some(funding_negotiation) = pending_splice
17836 .as_ref()
17837 .and_then(|pending_splice| pending_splice.funding_negotiation.as_ref())
17838 {
17839 if !matches!(funding_negotiation, FundingNegotiation::AwaitingSignatures { .. }) {
17840 return Err(DecodeError::InvalidValue);
17841 }
17842 }
17843
17844 Ok(FundedChannel {
17845 funding: FundingScope {
17846 value_to_self_msat,
17847 counterparty_selected_channel_reserve_satoshis,
17848 holder_selected_channel_reserve_satoshis: holder_selected_channel_reserve_satoshis
17849 .unwrap(),
17850
17851 #[cfg(debug_assertions)]
17852 holder_prev_commitment_tx_balance: Mutex::new((0, 0)),
17853 #[cfg(debug_assertions)]
17854 counterparty_prev_commitment_tx_balance: Mutex::new((0, 0)),
17855
17856 #[cfg(any(test, fuzzing))]
17857 next_local_fee: Mutex::new(PredictedNextFee::default()),
17858 #[cfg(any(test, fuzzing))]
17859 next_remote_fee: Mutex::new(PredictedNextFee::default()),
17860
17861 channel_transaction_parameters: channel_parameters,
17862 funding_transaction,
17863 funding_tx_confirmed_in,
17864 funding_tx_confirmation_height,
17865 short_channel_id,
17866 minimum_depth_override,
17867 },
17868 context: ChannelContext {
17869 user_id,
17870
17871 config,
17872
17873 prev_config: None,
17874
17875 inbound_handshake_limits_override: None,
17878
17879 channel_id,
17880 temporary_channel_id,
17881 channel_state,
17882 announcement_sigs_state,
17883 secp_ctx,
17884
17885 latest_monitor_update_id,
17886
17887 holder_signer,
17888 shutdown_scriptpubkey,
17889 destination_script,
17890
17891 counterparty_next_commitment_transaction_number,
17892
17893 holder_max_accepted_htlcs,
17894 pending_inbound_htlcs,
17895 pending_outbound_htlcs,
17896 holding_cell_htlc_updates,
17897
17898 resend_order,
17899
17900 monitor_pending_tx_signatures: monitor_pending_tx_signatures.is_some(),
17901 monitor_pending_channel_ready,
17902 monitor_pending_revoke_and_ack,
17903 monitor_pending_commitment_signed,
17904 monitor_pending_forwards,
17905 monitor_pending_failures,
17906 monitor_pending_finalized_fulfills: monitor_pending_finalized_fulfills.unwrap(),
17907 monitor_pending_update_adds: monitor_pending_update_adds.unwrap_or_default(),
17908
17909 signer_pending_revoke_and_ack: false,
17910 signer_pending_commitment_update: false,
17911 signer_pending_funding: false,
17912 signer_pending_closing: false,
17913 signer_pending_channel_ready: false,
17914 signer_pending_stale_state_verification: None,
17915
17916 pending_update_fee,
17917 holding_cell_update_fee,
17918 next_holder_htlc_id,
17919 next_counterparty_htlc_id,
17920 update_time_counter,
17921 feerate_per_kw,
17922
17923 last_sent_closing_fee: None,
17924 last_received_closing_sig: None,
17925 pending_counterparty_closing_signed: None,
17926 expecting_peer_commitment_signed: false,
17927 closing_fee_limits: None,
17928 target_closing_feerate_sats_per_kw,
17929
17930 channel_creation_height,
17931
17932 counterparty_dust_limit_satoshis,
17933 holder_dust_limit_satoshis,
17934 counterparty_max_htlc_value_in_flight_msat,
17935 holder_max_htlc_value_in_flight_msat: holder_max_htlc_value_in_flight_msat.unwrap(),
17936 counterparty_htlc_minimum_msat,
17937 holder_htlc_minimum_msat,
17938 counterparty_max_accepted_htlcs,
17939 minimum_depth,
17940
17941 counterparty_forwarding_info,
17942
17943 is_batch_funding,
17944
17945 counterparty_next_commitment_point,
17946 counterparty_current_commitment_point,
17947 counterparty_node_id,
17948
17949 counterparty_shutdown_scriptpubkey,
17950
17951 commitment_secrets,
17952
17953 channel_update_status,
17954 closing_signed_in_flight: false,
17955
17956 announcement_sigs,
17957
17958 workaround_lnd_bug_4006: None,
17959 funding_locked_txid_sent_in_reestablish: None,
17960 sent_message_awaiting_response: None,
17961
17962 latest_inbound_scid_alias,
17963 outbound_scid_alias,
17965 historical_scids: historical_scids.unwrap(),
17966
17967 funding_tx_broadcast_safe_event_emitted: funding_tx_broadcast_safe_event_emitted
17968 .unwrap_or(false),
17969 channel_pending_event_emitted: channel_pending_event_emitted.unwrap_or(true),
17970 initial_channel_ready_event_emitted: initial_channel_ready_event_emitted
17971 .unwrap_or(true),
17972
17973 channel_keys_id,
17974
17975 local_initiated_shutdown,
17976
17977 blocked_monitor_updates: blocked_monitor_updates.unwrap(),
17978 is_manual_broadcast: is_manual_broadcast.unwrap_or(false),
17979
17980 interactive_tx_signing_session,
17981 },
17982 holder_commitment_point,
17983 pending_splice,
17984 quiescent_action: None,
17985 })
17986 }
17987}
17988
17989fn duration_since_epoch() -> Option<Duration> {
17990 #[cfg(any(not(feature = "std"), fuzzing))]
17991 let now = None;
17992
17993 #[cfg(all(feature = "std", not(fuzzing)))]
17994 let now = Some(
17995 std::time::SystemTime::now()
17996 .duration_since(std::time::SystemTime::UNIX_EPOCH)
17997 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH"),
17998 );
17999
18000 now
18001}
18002
18003pub(crate) fn hold_time_since(send_timestamp: Option<Duration>) -> Option<u32> {
18006 send_timestamp.and_then(|t| {
18007 duration_since_epoch().map(|now| {
18008 let elapsed = now.saturating_sub(t).as_millis() / HOLD_TIME_UNIT_MILLIS;
18009 u32::try_from(elapsed).unwrap_or(u32::MAX)
18010 })
18011 })
18012}
18013
18014#[cfg(test)]
18015mod tests {
18016 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
18017 use crate::chain::transaction::OutPoint;
18018 use crate::chain::BlockLocator;
18019 use crate::ln::chan_utils::{self, commit_tx_fee_sat};
18020 use crate::ln::channel::{
18021 AwaitingChannelReadyFlags, ChannelState, FundedChannel, HTLCUpdateAwaitingACK,
18022 InboundHTLCOutput, InboundHTLCState, InboundUpdateAdd, InboundV1Channel,
18023 NextCommitmentView, OutboundHTLCOutput, OutboundHTLCState, OutboundV1Channel,
18024 WithChannelContext, MIN_THEIR_CHAN_RESERVE_SATOSHIS,
18025 };
18026 use crate::ln::channel_keys::{RevocationBasepoint, RevocationKey};
18027 use crate::ln::channelmanager::{self, HTLCSource, PaymentId, TrustedChannelFeatures};
18028 use crate::ln::msgs;
18029 use crate::ln::msgs::{ChannelUpdate, UnsignedChannelUpdate, MAX_VALUE_MSAT};
18030 use crate::ln::onion_utils::{AttributionData, LocalHTLCFailureReason};
18031 use crate::ln::script::ShutdownScript;
18032 use crate::prelude::*;
18033 use crate::routing::router::{Path, RouteHop};
18034 use crate::sign::tx_builder::HTLCAmountDirection;
18035 #[cfg(ldk_test_vectors)]
18036 use crate::sign::{ChannelSigner, EntropySource, InMemorySigner, SignerProvider};
18037 #[cfg(ldk_test_vectors)]
18038 use crate::sync::Mutex;
18039 #[cfg(ldk_test_vectors)]
18040 use crate::types::features::ChannelTypeFeatures;
18041 use crate::types::features::{ChannelFeatures, NodeFeatures};
18042 use crate::types::payment::{PaymentHash, PaymentPreimage};
18043 use crate::util::config::UserConfig;
18044 use crate::util::errors::APIError;
18045 use crate::util::ser::{ReadableArgs, Writeable};
18046 use crate::util::test_utils::{
18047 self, OnGetShutdownScriptpubkey, TestFeeEstimator, TestKeysInterface, TestLogger,
18048 };
18049 use bitcoin::amount::Amount;
18050 use bitcoin::constants::ChainHash;
18051 use bitcoin::hashes::sha256::Hash as Sha256;
18052 use bitcoin::hashes::Hash;
18053 use bitcoin::hex::FromHex;
18054 use bitcoin::locktime::absolute::LockTime;
18055 use bitcoin::network::Network;
18056 use bitcoin::script::Builder;
18057 use bitcoin::secp256k1::ffi::Signature as FFISignature;
18058 use bitcoin::secp256k1::{ecdsa::Signature, Secp256k1};
18059 use bitcoin::secp256k1::{PublicKey, SecretKey};
18060 use bitcoin::transaction::{Transaction, TxOut, Version};
18061 use bitcoin::{WitnessProgram, WitnessVersion};
18062 use std::cmp;
18063
18064 fn dummy_inbound_update_add() -> InboundUpdateAdd {
18065 InboundUpdateAdd::Legacy
18066 }
18067
18068 fn do_test_htlc_removal_credit_for_peer_updates_before_our_ack(
18071 fulfill: bool, update_fee: bool,
18072 ) {
18073 use crate::events::HTLCHandlingFailureType;
18074 use crate::ln::functional_test_utils::*;
18075 use crate::ln::msgs::ChannelMessageHandler;
18076 use crate::ln::onion_utils::create_payment_onion;
18077 use crate::ln::outbound_payment::RecipientOnionFields;
18078
18079 const NEW_FEERATE: u32 = 20_000;
18080 let chanmon_cfgs = create_chanmon_cfgs(2);
18081 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
18082 let legacy_cfg = test_legacy_channel_config();
18083 let node_chanmgrs =
18084 create_node_chanmgrs(2, &node_cfgs, &[Some(legacy_cfg.clone()), Some(legacy_cfg)]);
18085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
18086 let (_, _, channel_id, _) = if update_fee {
18087 create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 90_000_000)
18088 } else {
18089 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0)
18090 };
18091 let node_a_id = nodes[0].node.get_our_node_id();
18092 let node_b_id = nodes[1].node.get_our_node_id();
18093 let (route, payment_hash, payment_preimage, payment_secret) =
18094 get_route_and_payment_hash!(nodes[0], nodes[1], 10_000_000);
18095 let onion = RecipientOnionFields::secret_only(payment_secret, 10_000_000);
18096 nodes[0]
18097 .node
18098 .send_payment_with_route(route, payment_hash, onion, PaymentId(payment_hash.0))
18099 .unwrap();
18100 check_added_monitors(&nodes[0], 1);
18101 let send_event = SendEvent::from_node(&nodes[0]);
18102 nodes[1].node.handle_update_add_htlc(node_a_id, &send_event.msgs[0]);
18103 do_commitment_signed_dance(&nodes[1], &nodes[0], &send_event.commitment_msg, false, false);
18104 expect_and_process_pending_htlcs(&nodes[1], false);
18105 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, 10_000_000);
18106
18107 let fee_estimator = LowerBoundedFeeEstimator::new(&chanmon_cfgs[0].fee_estimator);
18108 let assert_unaffordable = |updates: &msgs::CommitmentUpdate| {
18109 let per_peer_lock;
18110 let mut peer_state_lock;
18111 let channel =
18112 get_channel_ref!(nodes[0], nodes[1], per_peer_lock, peer_state_lock, channel_id)
18113 .as_funded_mut()
18114 .unwrap();
18115 if let Some(fee) = &updates.update_fee {
18116 assert_eq!(
18117 channel
18118 .context
18119 .validate_update_fee(&channel.funding, &fee_estimator, fee.feerate_per_kw)
18120 .unwrap_err()
18121 .to_string(),
18122 "Funding remote cannot afford proposed new fee"
18123 );
18124 } else {
18125 assert_eq!(
18126 channel
18127 .update_add_htlc(&updates.update_add_htlcs[0], &fee_estimator)
18128 .unwrap_err()
18129 .to_string(),
18130 "Remote HTLC add would overdraw remaining funds"
18131 );
18132 }
18133 };
18134
18135 if !fulfill {
18136 nodes[1].node.fail_htlc_backwards(&payment_hash);
18137 expect_and_process_pending_htlcs_and_htlc_handling_failed(
18138 &nodes[1],
18139 &[HTLCHandlingFailureType::Receive { payment_hash }],
18140 );
18141 check_added_monitors(&nodes[1], 1);
18142 let mut updates = get_htlc_update_msgs(&nodes[1], &node_a_id);
18143 assert_eq!(updates.update_fail_htlcs.len(), 1);
18144
18145 if update_fee {
18147 updates.update_fee =
18148 Some(msgs::UpdateFee { channel_id, feerate_per_kw: NEW_FEERATE });
18149 } else {
18150 let mut add = send_event.msgs[0].clone();
18151 add.amount_msat = 5_000_000;
18152 updates.update_add_htlcs.push(add);
18153 }
18154 assert_unaffordable(&updates);
18155 nodes[0].node.handle_update_fail_htlc(node_b_id, &updates.update_fail_htlcs[0]);
18156 assert_unaffordable(&updates);
18157 return;
18158 }
18159
18160 let (_, peer_payment_hash, peer_payment_secret) =
18161 get_payment_preimage_hash(&nodes[0], Some(5_000_000), None);
18162
18163 if update_fee {
18166 let per_peer_lock;
18167 let mut peer_state_lock;
18168 let channel =
18169 get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, channel_id)
18170 .as_funded_mut()
18171 .unwrap();
18172 let fee_msat =
18173 commit_tx_fee_sat(NEW_FEERATE, 0, channel.funding.get_channel_type()) * 1000;
18174 assert!(fee_msat > channel.funding.value_to_self_msat);
18175 channel.context.pending_update_fee =
18176 Some((NEW_FEERATE, super::FeeUpdateState::Outbound));
18177 } else {
18178 let mut htlc = {
18179 let per_peer_lock;
18180 let mut peer_state_lock;
18181 let channel = get_channel_ref!(
18182 nodes[0],
18183 nodes[1],
18184 per_peer_lock,
18185 peer_state_lock,
18186 channel_id
18187 )
18188 .as_funded()
18189 .unwrap();
18190 channel.context.pending_outbound_htlcs[0].clone()
18191 };
18192 htlc.amount_msat = 5_000_000;
18193 htlc.payment_hash = peer_payment_hash;
18194 if let HTLCSource::OutboundRoute {
18195 path,
18196 session_priv,
18197 first_hop_htlc_msat,
18198 payment_id,
18199 ..
18200 } = &mut htlc.source
18201 {
18202 path.hops[0].pubkey = node_a_id;
18203 path.hops[0].fee_msat = htlc.amount_msat;
18204 *first_hop_htlc_msat = htlc.amount_msat;
18205 *payment_id = PaymentId(htlc.payment_hash.0);
18206 let onion =
18207 RecipientOnionFields::secret_only(peer_payment_secret, htlc.amount_msat);
18208 let (onion_packet, _, cltv_expiry) = create_payment_onion(
18209 &Secp256k1::new(),
18210 path,
18211 session_priv,
18212 &onion,
18213 nodes[1].best_block_info().1 + 1,
18214 &htlc.payment_hash,
18215 &None,
18216 None,
18217 [0; 32],
18218 )
18219 .unwrap();
18220 htlc.cltv_expiry = cltv_expiry;
18221 htlc.state = OutboundHTLCState::LocalAnnounced(Box::new(onion_packet));
18222 } else {
18223 unreachable!();
18224 }
18225 let per_peer_lock;
18226 let mut peer_state_lock;
18227 let channel =
18228 get_channel_ref!(nodes[1], nodes[0], per_peer_lock, peer_state_lock, channel_id)
18229 .as_funded_mut()
18230 .unwrap();
18231 assert_eq!(channel.context.next_holder_htlc_id, htlc.htlc_id);
18232 channel.context.next_holder_htlc_id += 1;
18233 channel.context.pending_outbound_htlcs.push(htlc);
18234 }
18235
18236 nodes[1].node.claim_funds(payment_preimage);
18237 expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
18238 check_added_monitors(&nodes[1], 1);
18239 let updates = get_htlc_update_msgs(&nodes[1], &node_a_id);
18240 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
18241 assert_eq!(updates.update_add_htlcs.len(), if update_fee { 0 } else { 1 });
18242 assert_eq!(updates.update_fee.is_some(), update_fee);
18243 assert_unaffordable(&updates);
18244
18245 nodes[0]
18246 .node
18247 .handle_update_fulfill_htlc(node_b_id, updates.update_fulfill_htlcs[0].clone());
18248 let mut overspend = updates.clone();
18249 if let Some(fee) = &mut overspend.update_fee {
18250 assert_eq!(fee.feerate_per_kw, NEW_FEERATE);
18251 nodes[0].node.handle_update_fee(node_b_id, fee);
18252 fee.feerate_per_kw = 30_000;
18253 } else {
18254 let add = &mut overspend.update_add_htlcs[0];
18255 nodes[0].node.handle_update_add_htlc(node_b_id, add);
18256 add.htlc_id += 1;
18257 add.amount_msat = 5_000_001;
18258 }
18259 assert_unaffordable(&overspend);
18260
18261 do_commitment_signed_dance(&nodes[0], &nodes[1], &updates.commitment_signed, false, false);
18262 expect_payment_sent!(nodes[0], payment_preimage, Some(0));
18263 if !update_fee {
18264 expect_and_process_pending_htlcs(&nodes[0], false);
18265 expect_payment_claimable!(nodes[0], peer_payment_hash, peer_payment_secret, 5_000_000);
18266 check_added_monitors(&nodes[0], 0);
18267 }
18268 for (local, remote) in [(0, 1), (1, 0)] {
18269 let per_peer_lock;
18270 let mut peer_state_lock;
18271 let channel = get_channel_ref!(
18272 nodes[local],
18273 nodes[remote],
18274 per_peer_lock,
18275 peer_state_lock,
18276 channel_id
18277 )
18278 .as_funded()
18279 .unwrap();
18280 if update_fee {
18281 assert_eq!(channel.context.feerate_per_kw, NEW_FEERATE);
18282 assert!(channel.context.pending_inbound_htlcs.is_empty());
18283 assert!(channel.context.pending_outbound_htlcs.is_empty());
18284 } else if local == 0 {
18285 assert!(channel.context.pending_outbound_htlcs.is_empty());
18286 assert_eq!(channel.context.pending_inbound_htlcs.len(), 1);
18287 assert!(matches!(
18288 channel.context.pending_inbound_htlcs[0].state,
18289 InboundHTLCState::Committed { .. }
18290 ));
18291 } else {
18292 assert!(channel.context.pending_inbound_htlcs.is_empty());
18293 assert_eq!(channel.context.pending_outbound_htlcs.len(), 1);
18294 assert!(matches!(
18295 channel.context.pending_outbound_htlcs[0].state,
18296 OutboundHTLCState::Committed
18297 ));
18298 }
18299 }
18300 }
18301
18302 #[test]
18303 fn test_peer_update_fail_htlc_does_not_fund_peer_updates() {
18304 do_test_htlc_removal_credit_for_peer_updates_before_our_ack(false, false);
18305 do_test_htlc_removal_credit_for_peer_updates_before_our_ack(false, true);
18306 }
18307
18308 #[test]
18309 fn test_update_fulfill_htlc_frees_liquidity_for_peer_updates_before_our_ack() {
18310 do_test_htlc_removal_credit_for_peer_updates_before_our_ack(true, false);
18311 do_test_htlc_removal_credit_for_peer_updates_before_our_ack(true, true);
18312 }
18313
18314 #[test]
18315 #[rustfmt::skip]
18316 fn test_channel_state_order() {
18317 use crate::ln::channel::NegotiatingFundingFlags;
18318 use crate::ln::channel::FundingNegotiatedFlags;
18319 use crate::ln::channel::AwaitingChannelReadyFlags;
18320 use crate::ln::channel::ChannelReadyFlags;
18321
18322 assert!(ChannelState::NegotiatingFunding(NegotiatingFundingFlags::new()) < ChannelState::FundingNegotiated(FundingNegotiatedFlags::new()));
18323 assert!(ChannelState::FundingNegotiated(FundingNegotiatedFlags::new()) < ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new()));
18324 assert!(ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::new()) < ChannelState::ChannelReady(ChannelReadyFlags::new()));
18325 assert!(ChannelState::ChannelReady(ChannelReadyFlags::new()) < ChannelState::ShutdownComplete);
18326 }
18327
18328 #[cfg(ldk_test_vectors)]
18329 struct Keys {
18330 signer: crate::sign::InMemorySigner,
18331 }
18332
18333 #[cfg(ldk_test_vectors)]
18334 impl EntropySource for Keys {
18335 fn get_secure_random_bytes(&self) -> [u8; 32] {
18336 [0; 32]
18337 }
18338 }
18339
18340 #[cfg(ldk_test_vectors)]
18341 impl SignerProvider for Keys {
18342 type EcdsaSigner = InMemorySigner;
18343
18344 fn generate_channel_keys_id(&self, _inbound: bool, _user_channel_id: u128) -> [u8; 32] {
18345 self.signer.channel_keys_id()
18346 }
18347
18348 fn derive_channel_signer(&self, _channel_keys_id: [u8; 32]) -> Self::EcdsaSigner {
18349 self.signer.clone()
18350 }
18351
18352 fn get_destination_script(
18353 &self, _channel_keys_id: [u8; 32],
18354 ) -> Result<bitcoin::script::ScriptBuf, ()> {
18355 let secp_ctx = Secp256k1::signing_only();
18356 let hex = "0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
18357 let channel_monitor_claim_key =
18358 SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
18359 let channel_monitor_claim_key_hash = bitcoin::WPubkeyHash::hash(
18360 &PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize(),
18361 );
18362 Ok(Builder::new()
18363 .push_opcode(bitcoin::opcodes::all::OP_PUSHBYTES_0)
18364 .push_slice(channel_monitor_claim_key_hash)
18365 .into_script())
18366 }
18367
18368 fn get_shutdown_scriptpubkey(&self) -> Result<ShutdownScript, ()> {
18369 let secp_ctx = Secp256k1::signing_only();
18370 let hex = "0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
18371 let channel_close_key =
18372 SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
18373 Ok(ShutdownScript::new_p2wpkh_from_pubkey(PublicKey::from_secret_key(
18374 &secp_ctx,
18375 &channel_close_key,
18376 )))
18377 }
18378 }
18379
18380 #[test]
18381 fn upfront_shutdown_script_incompatibility() {
18382 let mut features = channelmanager::provided_init_features(&UserConfig::default());
18383 features.clear_shutdown_anysegwit();
18384 let non_v0_segwit_shutdown_script = ShutdownScript::new_witness_program(
18385 &WitnessProgram::new(WitnessVersion::V16, &[0, 40]).unwrap(),
18386 )
18387 .unwrap();
18388
18389 let seed = [42; 32];
18390 let network = Network::Testnet;
18391 let keys_provider = TestKeysInterface::new(&seed, network);
18392 keys_provider
18393 .expect(OnGetShutdownScriptpubkey { returns: non_v0_segwit_shutdown_script.clone() });
18394 let fee_estimator = TestFeeEstimator::new(253);
18395 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_estimator);
18396 let logger = TestLogger::new();
18397
18398 let secp_ctx = Secp256k1::new();
18399 let node_id =
18400 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18401 let config = UserConfig::default();
18402 let res = OutboundV1Channel::new(
18403 &bounded_fee_estimator,
18404 &&keys_provider,
18405 &&keys_provider,
18406 node_id,
18407 &features,
18408 10000000,
18409 100000,
18410 42,
18411 &config,
18412 0,
18413 42,
18414 None,
18415 &logger,
18416 None,
18417 );
18418 match res {
18419 Err(APIError::IncompatibleShutdownScript { script }) => {
18420 assert_eq!(script.into_inner(), non_v0_segwit_shutdown_script.into_inner());
18421 },
18422 Err(e) => panic!("Unexpected error: {:?}", e),
18423 Ok(_) => panic!("Expected error"),
18424 }
18425 }
18426
18427 #[test]
18430 #[rustfmt::skip]
18431 fn test_open_channel_msg_fee() {
18432 let original_fee = 253;
18433 let fee_est = TestFeeEstimator::new(original_fee);
18434 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&fee_est);
18435 let secp_ctx = Secp256k1::new();
18436 let seed = [42; 32];
18437 let network = Network::Testnet;
18438 let keys_provider = TestKeysInterface::new(&seed, network);
18439 let logger = TestLogger::new();
18440
18441 let node_a_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18442 let config = UserConfig::default();
18443 let mut node_a_chan = OutboundV1Channel::<&TestKeysInterface>::new(&bounded_fee_estimator, &&keys_provider, &&keys_provider, node_a_node_id, &channelmanager::provided_init_features(&config), 10000000, 100000, 42, &config, 0, 42, None, &logger, None).unwrap();
18444
18445 *fee_est.sat_per_kw.lock().unwrap() = 500;
18448 let open_channel_msg = node_a_chan.get_open_channel(ChainHash::using_genesis_block(network), &&logger).unwrap();
18449 assert_eq!(open_channel_msg.common_fields.commitment_feerate_sat_per_1000_weight, original_fee);
18450 }
18451
18452 #[test]
18453 #[rustfmt::skip]
18454 fn test_holder_vs_counterparty_dust_limit() {
18455 let test_est = TestFeeEstimator::new(15000);
18458 let feeest = LowerBoundedFeeEstimator::new(&test_est);
18459 let secp_ctx = Secp256k1::new();
18460 let seed = [42; 32];
18461 let network = Network::Testnet;
18462 let keys_provider = TestKeysInterface::new(&seed, network);
18463 let logger = TestLogger::new();
18464 let best_block = BlockLocator::from_network(network);
18465
18466 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18471 let mut config = UserConfig::default();
18472 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
18473 let mut node_a_chan = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, node_b_node_id, &channelmanager::provided_init_features(&config), 10_000_000, 100_000_000, 42, &config, 0, 42, None, &logger, None).unwrap();
18474
18475 let open_channel_msg = node_a_chan.get_open_channel(ChainHash::using_genesis_block(network), &&logger).unwrap();
18478 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
18479 let mut node_b_chan = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, node_b_node_id, &channelmanager::provided_channel_type_features(&config), &channelmanager::provided_init_features(&config), &open_channel_msg, 7, &config, 0, &&logger, None).unwrap();
18480
18481 let mut accept_channel_msg = node_b_chan.accept_inbound_channel(&&logger).unwrap();
18483 accept_channel_msg.common_fields.dust_limit_satoshis = 546;
18484 node_a_chan.accept_channel(&accept_channel_msg, &config.channel_handshake_limits, &channelmanager::provided_init_features(&config)).unwrap();
18485 node_a_chan.context.holder_dust_limit_satoshis = 1560;
18486
18487 let output_script = node_a_chan.funding.get_funding_redeemscript();
18489 let tx = Transaction { version: Version::ONE, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
18490 value: Amount::from_sat(10000000), script_pubkey: output_script.clone(),
18491 }]};
18492 let funding_outpoint = OutPoint{ txid: tx.compute_txid(), index: 0 };
18493 let funding_created_msg = node_a_chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap();
18494 let (_, funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg.unwrap(), best_block, &&keys_provider, &&logger).map_err(|_| ()).unwrap();
18495
18496 let res = node_a_chan.funding_signed(&funding_signed_msg.unwrap(), best_block, &&keys_provider, &&logger);
18498 let (mut node_a_chan, _) = if let Ok(res) = res { res } else { panic!(); };
18499
18500 let htlc_amount_msat = 11_092_000; node_a_chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
18503 htlc_id: 0,
18504 amount_msat: htlc_amount_msat,
18505 payment_hash: PaymentHash(Sha256::hash(&[42; 32]).to_byte_array()),
18506 cltv_expiry: 300000000,
18507 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
18508 });
18509
18510 node_a_chan.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
18511 htlc_id: 1,
18512 amount_msat: htlc_amount_msat, payment_hash: PaymentHash(Sha256::hash(&[43; 32]).to_byte_array()),
18514 cltv_expiry: 200000000,
18515 state: OutboundHTLCState::Committed,
18516 source: HTLCSource::OutboundRoute {
18517 path: Path { hops: Vec::new(), blinded_tail: None },
18518 session_priv: SecretKey::from_slice(&<Vec<u8>>::from_hex("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()[..]).unwrap(),
18519 first_hop_htlc_msat: 548,
18520 payment_id: PaymentId([42; 32]),
18521 bolt12_invoice: None,
18522 },
18523 skimmed_fee_msat: None,
18524 blinding_point: None,
18525 send_timestamp: None,
18526 hold_htlc: None,
18527 accountable: false,
18528 });
18529
18530 let htlc_candidate = HTLCAmountDirection { amount_msat: htlc_amount_msat, outbound: true };
18533 let local_commit_tx_fee = node_a_chan.context.get_next_local_commitment_stats(&node_a_chan.funding, Some(htlc_candidate), NextCommitmentView::ValidatingOwnUpdate, 0, node_a_chan.context.feerate_per_kw, false, None).unwrap().0.commitment_stats.commit_tx_fee_sat * 1000;
18534 let local_commit_fee_0_htlcs = commit_tx_fee_sat(node_a_chan.context.feerate_per_kw, 0, node_a_chan.funding.get_channel_type()) * 1000;
18535 assert_eq!(local_commit_tx_fee, local_commit_fee_0_htlcs);
18536
18537 node_a_chan.funding.channel_transaction_parameters.is_outbound_from_holder = false;
18540 let remote_commit_fee_3_htlcs = commit_tx_fee_sat(node_a_chan.context.feerate_per_kw, 3, node_a_chan.funding.get_channel_type()) * 1000;
18541 let htlc_candidate = HTLCAmountDirection { amount_msat: htlc_amount_msat, outbound: true };
18542 let remote_commit_tx_fee = node_a_chan.context.get_next_remote_commitment_stats(&node_a_chan.funding, Some(htlc_candidate), NextCommitmentView::ValidatingOwnUpdate, 0, node_a_chan.context.feerate_per_kw, false, None).unwrap().0.commitment_stats.commit_tx_fee_sat * 1000;
18543 assert_eq!(remote_commit_tx_fee, remote_commit_fee_3_htlcs);
18544 }
18545
18546 #[test]
18547 #[rustfmt::skip]
18548 fn test_timeout_vs_success_htlc_dust_limit() {
18549 let test_est = TestFeeEstimator::new(253);
18554 let fee_est = LowerBoundedFeeEstimator::new(&test_est);
18555 let secp_ctx = Secp256k1::new();
18556 let seed = [42; 32];
18557 let network = Network::Testnet;
18558 let keys_provider = TestKeysInterface::new(&seed, network);
18559 let logger = TestLogger::new();
18560
18561 let node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18562 let mut config = UserConfig::default();
18563 config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = false;
18564 let mut chan = OutboundV1Channel::<&TestKeysInterface>::new(&fee_est, &&keys_provider, &&keys_provider, node_id, &channelmanager::provided_init_features(&config), 10_000_000, 100_000_000, 42, &config, 0, 42, None, &logger, None).unwrap();
18565 chan.context.counterparty_max_htlc_value_in_flight_msat = 1_000_000_000;
18566
18567 let commitment_tx_fee_0_htlcs = commit_tx_fee_sat(chan.context.feerate_per_kw, 0, chan.funding.get_channel_type()) * 1000;
18568 let commitment_tx_fee_1_htlc = commit_tx_fee_sat(chan.context.feerate_per_kw, 1, chan.funding.get_channel_type()) * 1000;
18569 let (htlc_success_tx_fee_sat, htlc_timeout_tx_fee_sat) = chan_utils::second_stage_tx_fees_sat(
18570 &chan.funding.get_channel_type(), 253
18571 );
18572
18573 let htlc_amt_above_timeout = (htlc_timeout_tx_fee_sat + chan.context.holder_dust_limit_satoshis + 1) * 1000;
18576 let htlc_candidate = HTLCAmountDirection { amount_msat: htlc_amt_above_timeout, outbound: true };
18577 let commitment_tx_fee = chan.context.get_next_local_commitment_stats(&chan.funding, Some(htlc_candidate), NextCommitmentView::ValidatingOwnUpdate, 0, chan.context.feerate_per_kw, false, None).unwrap().0.commitment_stats.commit_tx_fee_sat * 1000;
18578 assert_eq!(commitment_tx_fee, commitment_tx_fee_1_htlc);
18579
18580 let dust_htlc_amt_below_success = (htlc_success_tx_fee_sat + chan.context.holder_dust_limit_satoshis - 1) * 1000;
18582 let htlc_candidate = HTLCAmountDirection { amount_msat: dust_htlc_amt_below_success, outbound: false };
18583 let commitment_tx_fee = chan.context.get_next_local_commitment_stats(&chan.funding, Some(htlc_candidate), NextCommitmentView::ValidatingOwnUpdate, 0, chan.context.feerate_per_kw, false, None).unwrap().0.commitment_stats.commit_tx_fee_sat * 1000;
18584 assert_eq!(commitment_tx_fee, commitment_tx_fee_0_htlcs);
18585
18586 chan.funding.channel_transaction_parameters.is_outbound_from_holder = false;
18587
18588 let dust_htlc_amt_above_timeout = (htlc_timeout_tx_fee_sat + chan.context.counterparty_dust_limit_satoshis + 1) * 1000;
18590 let htlc_candidate = HTLCAmountDirection { amount_msat: dust_htlc_amt_above_timeout, outbound: true };
18591 let commitment_tx_fee = chan.context.get_next_remote_commitment_stats(&chan.funding, Some(htlc_candidate), NextCommitmentView::ValidatingOwnUpdate, 0, chan.context.feerate_per_kw, false, None).unwrap().0.commitment_stats.commit_tx_fee_sat * 1000;
18592 assert_eq!(commitment_tx_fee, commitment_tx_fee_0_htlcs);
18593
18594 let htlc_amt_below_success = (htlc_success_tx_fee_sat + chan.context.counterparty_dust_limit_satoshis - 1) * 1000;
18596 let htlc_candidate = HTLCAmountDirection { amount_msat: htlc_amt_below_success, outbound: false };
18597 let commitment_tx_fee = chan.context.get_next_remote_commitment_stats(&chan.funding, Some(htlc_candidate), NextCommitmentView::ValidatingOwnUpdate, 0, chan.context.feerate_per_kw, false, None).unwrap().0.commitment_stats.commit_tx_fee_sat * 1000;
18598 assert_eq!(commitment_tx_fee, commitment_tx_fee_1_htlc);
18599 }
18600
18601 #[test]
18602 #[rustfmt::skip]
18603 fn channel_reestablish_no_updates() {
18604 let test_est = TestFeeEstimator::new(15000);
18605 let feeest = LowerBoundedFeeEstimator::new(&test_est);
18606 let logger = TestLogger::new();
18607 let secp_ctx = Secp256k1::new();
18608 let seed = [42; 32];
18609 let network = Network::Testnet;
18610 let best_block = BlockLocator::from_network(network);
18611 let chain_hash = ChainHash::using_genesis_block(network);
18612 let keys_provider = TestKeysInterface::new(&seed, network);
18613
18614 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18618 let config = UserConfig::default();
18619 let mut node_a_chan = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, node_b_node_id, &channelmanager::provided_init_features(&config), 10000000, 100000, 42, &config, 0, 42, None, &logger, None).unwrap();
18620
18621 let open_channel_msg = node_a_chan.get_open_channel(chain_hash, &&logger).unwrap();
18623 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
18624 let mut node_b_chan = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, node_b_node_id, &channelmanager::provided_channel_type_features(&config), &channelmanager::provided_init_features(&config), &open_channel_msg, 7, &config, 0, &&logger, None).unwrap();
18625
18626 let accept_channel_msg = node_b_chan.accept_inbound_channel(&&logger).unwrap();
18628 node_a_chan.accept_channel(&accept_channel_msg, &config.channel_handshake_limits, &channelmanager::provided_init_features(&config)).unwrap();
18629
18630 let output_script = node_a_chan.funding.get_funding_redeemscript();
18632 let tx = Transaction { version: Version::ONE, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
18633 value: Amount::from_sat(10000000), script_pubkey: output_script.clone(),
18634 }]};
18635 let funding_outpoint = OutPoint{ txid: tx.compute_txid(), index: 0 };
18636 let funding_created_msg = node_a_chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap();
18637 let (mut node_b_chan, funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg.unwrap(), best_block, &&keys_provider, &&logger).map_err(|_| ()).unwrap();
18638
18639 let res = node_a_chan.funding_signed(&funding_signed_msg.unwrap(), best_block, &&keys_provider, &&logger);
18641 let (mut node_a_chan, _) = if let Ok(res) = res { res } else { panic!(); };
18642
18643 assert!(node_b_chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok());
18646 let msg = node_b_chan.get_channel_reestablish(&&logger);
18647 assert_eq!(msg.next_local_commitment_number, 1); assert_eq!(msg.next_remote_commitment_number, 0); assert_eq!(msg.your_last_per_commitment_secret, [0; 32]);
18650
18651 assert!(node_a_chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok());
18654 let msg = node_a_chan.get_channel_reestablish(&&logger);
18655 assert_eq!(msg.next_local_commitment_number, 1); assert_eq!(msg.next_remote_commitment_number, 0); assert_eq!(msg.your_last_per_commitment_secret, [0; 32]);
18658 }
18659
18660 #[test]
18661 fn test_configured_holder_max_htlc_value_in_flight() {
18662 do_test_configured_holder_max_htlc_value_in_flight(true);
18663 do_test_configured_holder_max_htlc_value_in_flight(false);
18664 }
18665
18666 #[rustfmt::skip]
18667 fn do_test_configured_holder_max_htlc_value_in_flight(announce_channel: bool) {
18668 let test_est = TestFeeEstimator::new(15000);
18669 let feeest = LowerBoundedFeeEstimator::new(&test_est);
18670 let logger = TestLogger::new();
18671 let secp_ctx = Secp256k1::new();
18672 let seed = [42; 32];
18673 let network = Network::Testnet;
18674 let keys_provider = TestKeysInterface::new(&seed, network);
18675 let outbound_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18676 let inbound_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
18677
18678 let mut config_2_percent = UserConfig::default();
18679 config_2_percent.channel_handshake_config.announce_for_forwarding = announce_channel;
18680 if announce_channel {
18681 config_2_percent
18682 .channel_handshake_config
18683 .announced_channel_max_inbound_htlc_value_in_flight_percentage = 2;
18684 } else {
18685 config_2_percent
18686 .channel_handshake_config
18687 .unannounced_channel_max_inbound_htlc_value_in_flight_percentage = 2;
18688 }
18689 let mut config_99_percent = UserConfig::default();
18690 config_99_percent.channel_handshake_config.announce_for_forwarding = announce_channel;
18691 if announce_channel {
18692 config_99_percent
18693 .channel_handshake_config
18694 .announced_channel_max_inbound_htlc_value_in_flight_percentage = 99;
18695 } else {
18696 config_99_percent
18697 .channel_handshake_config
18698 .unannounced_channel_max_inbound_htlc_value_in_flight_percentage = 99;
18699 }
18700 let mut config_0_percent = UserConfig::default();
18701 config_0_percent.channel_handshake_config.announce_for_forwarding = announce_channel;
18702 if announce_channel {
18703 config_0_percent
18704 .channel_handshake_config
18705 .announced_channel_max_inbound_htlc_value_in_flight_percentage = 0;
18706 } else {
18707 config_0_percent
18708 .channel_handshake_config
18709 .unannounced_channel_max_inbound_htlc_value_in_flight_percentage = 0;
18710 }
18711 let mut config_101_percent = UserConfig::default();
18712 config_101_percent.channel_handshake_config.announce_for_forwarding = announce_channel;
18713 if announce_channel {
18714 config_101_percent
18715 .channel_handshake_config
18716 .announced_channel_max_inbound_htlc_value_in_flight_percentage = 101;
18717 } else {
18718 config_101_percent
18719 .channel_handshake_config
18720 .unannounced_channel_max_inbound_htlc_value_in_flight_percentage = 101;
18721 }
18722
18723 let mut chan_1 = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, outbound_node_id, &channelmanager::provided_init_features(&config_2_percent), 10000000, 100000, 42, &config_2_percent, 0, 42, None, &logger, None).unwrap();
18727 let chan_1_value_msat = chan_1.funding.get_value_satoshis() * 1000;
18728 assert_eq!(chan_1.context.holder_max_htlc_value_in_flight_msat, (chan_1_value_msat as f64 * 0.02) as u64);
18729
18730 let chan_2 = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, outbound_node_id, &channelmanager::provided_init_features(&config_99_percent), 10000000, 100000, 42, &config_99_percent, 0, 42, None, &logger, None).unwrap();
18732 let chan_2_value_msat = chan_2.funding.get_value_satoshis() * 1000;
18733 assert_eq!(chan_2.context.holder_max_htlc_value_in_flight_msat, (chan_2_value_msat as f64 * 0.99) as u64);
18734
18735 let chan_1_open_channel_msg = chan_1.get_open_channel(ChainHash::using_genesis_block(network), &&logger).unwrap();
18736
18737 let chan_3 = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, inbound_node_id, &channelmanager::provided_channel_type_features(&config_2_percent), &channelmanager::provided_init_features(&config_2_percent), &chan_1_open_channel_msg, 7, &config_2_percent, 0, &&logger, None).unwrap();
18741 let chan_3_value_msat = chan_3.funding.get_value_satoshis() * 1000;
18742 assert_eq!(chan_3.context.holder_max_htlc_value_in_flight_msat, (chan_3_value_msat as f64 * 0.02) as u64);
18743
18744 let chan_4 = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, inbound_node_id, &channelmanager::provided_channel_type_features(&config_99_percent), &channelmanager::provided_init_features(&config_99_percent), &chan_1_open_channel_msg, 7, &config_99_percent, 0, &&logger, None).unwrap();
18746 let chan_4_value_msat = chan_4.funding.get_value_satoshis() * 1000;
18747 assert_eq!(chan_4.context.holder_max_htlc_value_in_flight_msat, (chan_4_value_msat as f64 * 0.99) as u64);
18748
18749 let chan_5 = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, outbound_node_id, &channelmanager::provided_init_features(&config_0_percent), 10000000, 100000, 42, &config_0_percent, 0, 42, None, &logger, None).unwrap();
18752 let chan_5_value_msat = chan_5.funding.get_value_satoshis() * 1000;
18753 assert_eq!(chan_5.context.holder_max_htlc_value_in_flight_msat, (chan_5_value_msat as f64 * 0.01) as u64);
18754
18755 let chan_6 = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, outbound_node_id, &channelmanager::provided_init_features(&config_101_percent), 10000000, 100000, 42, &config_101_percent, 0, 42, None, &logger, None).unwrap();
18759 let chan_6_value_msat = chan_6.funding.get_value_satoshis() * 1000;
18760 assert_eq!(chan_6.context.holder_max_htlc_value_in_flight_msat, chan_6_value_msat);
18761
18762 let chan_7 = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, inbound_node_id, &channelmanager::provided_channel_type_features(&config_0_percent), &channelmanager::provided_init_features(&config_0_percent), &chan_1_open_channel_msg, 7, &config_0_percent, 0, &&logger, None).unwrap();
18765 let chan_7_value_msat = chan_7.funding.get_value_satoshis() * 1000;
18766 assert_eq!(chan_7.context.holder_max_htlc_value_in_flight_msat, (chan_7_value_msat as f64 * 0.01) as u64);
18767
18768 let chan_8 = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, inbound_node_id, &channelmanager::provided_channel_type_features(&config_101_percent), &channelmanager::provided_init_features(&config_101_percent), &chan_1_open_channel_msg, 7, &config_101_percent, 0, &&logger, None).unwrap();
18772 let chan_8_value_msat = chan_8.funding.get_value_satoshis() * 1000;
18773 assert_eq!(chan_8.context.holder_max_htlc_value_in_flight_msat, chan_8_value_msat);
18774 }
18775
18776 #[test]
18777 #[rustfmt::skip]
18778 fn test_configured_holder_selected_channel_reserve_satoshis() {
18779
18780 test_self_and_counterparty_channel_reserve(10_000_000, 0.02, 0.02);
18783
18784 test_self_and_counterparty_channel_reserve(10_000_000, 0.49, 0.49);
18787 test_self_and_counterparty_channel_reserve(10_000_000, 0.60, 0.30);
18788
18789 test_self_and_counterparty_channel_reserve(100_000, 0.00002, 0.30);
18792
18793 test_self_and_counterparty_channel_reserve(10_000_000, 0.50, 0.50);
18796 test_self_and_counterparty_channel_reserve(10_000_000, 0.60, 0.50);
18797
18798 test_self_and_counterparty_channel_reserve(100_000, 1.1, 0.30);
18800 test_self_and_counterparty_channel_reserve(100_000, 0.30, 1.1);
18801 }
18802
18803 #[rustfmt::skip]
18804 fn test_self_and_counterparty_channel_reserve(channel_value_satoshis: u64, outbound_selected_channel_reserve_perc: f64, inbound_selected_channel_reserve_perc: f64) {
18805 let test_est = TestFeeEstimator::new(15000);
18806 let fee_est = LowerBoundedFeeEstimator::new(&test_est);
18807 let logger = TestLogger::new();
18808 let secp_ctx = Secp256k1::new();
18809 let seed = [42; 32];
18810 let network = Network::Testnet;
18811 let keys_provider = TestKeysInterface::new(&seed, network);
18812 let outbound_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18813 let inbound_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
18814
18815
18816 let mut outbound_node_config = UserConfig::default();
18817 outbound_node_config.channel_handshake_config.their_channel_reserve_proportional_millionths = (outbound_selected_channel_reserve_perc * 1_000_000.0) as u32;
18818 let mut chan = OutboundV1Channel::<&TestKeysInterface>::new(&&fee_est, &&keys_provider, &&keys_provider, outbound_node_id, &channelmanager::provided_init_features(&outbound_node_config), channel_value_satoshis, 100_000, 42, &outbound_node_config, 0, 42, None, &logger, None).unwrap();
18819
18820 let outbound_capped_reserve_perc = if outbound_selected_channel_reserve_perc.lt(&1.0) {
18821 outbound_selected_channel_reserve_perc
18822 } else {
18823 1.0
18824 };
18825
18826 let inbound_capped_reserve_perc = if inbound_selected_channel_reserve_perc.lt(&1.0) {
18827 inbound_selected_channel_reserve_perc
18828 } else {
18829 1.0
18830 };
18831
18832 let expected_outbound_selected_chan_reserve = cmp::max(MIN_THEIR_CHAN_RESERVE_SATOSHIS, (chan.funding.get_value_satoshis() as f64 * outbound_capped_reserve_perc) as u64);
18833 assert_eq!(chan.funding.holder_selected_channel_reserve_satoshis, expected_outbound_selected_chan_reserve);
18834
18835 let chan_open_channel_msg = chan.get_open_channel(ChainHash::using_genesis_block(network), &&logger).unwrap();
18836 let mut inbound_node_config = UserConfig::default();
18837 inbound_node_config.channel_handshake_config.their_channel_reserve_proportional_millionths = (inbound_selected_channel_reserve_perc * 1_000_000.0) as u32;
18838
18839 if outbound_selected_channel_reserve_perc + inbound_selected_channel_reserve_perc < 1.0 {
18840 let chan_inbound_node = InboundV1Channel::<&TestKeysInterface>::new(&&fee_est, &&keys_provider, &&keys_provider, inbound_node_id, &channelmanager::provided_channel_type_features(&inbound_node_config), &channelmanager::provided_init_features(&outbound_node_config), &chan_open_channel_msg, 7, &inbound_node_config, 0, &&logger, None).unwrap();
18841
18842 let expected_inbound_selected_chan_reserve = cmp::max(MIN_THEIR_CHAN_RESERVE_SATOSHIS, (chan.funding.get_value_satoshis() as f64 * inbound_capped_reserve_perc) as u64);
18843
18844 assert_eq!(chan_inbound_node.funding.holder_selected_channel_reserve_satoshis, expected_inbound_selected_chan_reserve);
18845 assert_eq!(chan_inbound_node.funding.counterparty_selected_channel_reserve_satoshis.unwrap(), expected_outbound_selected_chan_reserve);
18846 } else {
18847 let result = InboundV1Channel::<&TestKeysInterface>::new(&&fee_est, &&keys_provider, &&keys_provider, inbound_node_id, &channelmanager::provided_channel_type_features(&inbound_node_config), &channelmanager::provided_init_features(&outbound_node_config), &chan_open_channel_msg, 7, &inbound_node_config, 0, &&logger, None);
18849 assert!(result.is_err());
18850 }
18851 }
18852
18853 #[test]
18854 #[rustfmt::skip]
18855 fn channel_update() {
18856 let test_est = TestFeeEstimator::new(15000);
18857 let feeest = LowerBoundedFeeEstimator::new(&test_est);
18858 let logger = TestLogger::new();
18859 let secp_ctx = Secp256k1::new();
18860 let seed = [42; 32];
18861 let network = Network::Testnet;
18862 let best_block = BlockLocator::from_network(network);
18863 let chain_hash = ChainHash::using_genesis_block(network);
18864 let keys_provider = TestKeysInterface::new(&seed, network);
18865
18866 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18868 let config = UserConfig::default();
18869 let mut node_a_chan = OutboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, node_b_node_id, &channelmanager::provided_init_features(&config), 10000000, 100000, 42, &config, 0, 42, None, &logger, None).unwrap();
18870
18871 let open_channel_msg = node_a_chan.get_open_channel(ChainHash::using_genesis_block(network), &&logger).unwrap();
18874 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
18875 let mut node_b_chan = InboundV1Channel::<&TestKeysInterface>::new(&feeest, &&keys_provider, &&keys_provider, node_b_node_id, &channelmanager::provided_channel_type_features(&config), &channelmanager::provided_init_features(&config), &open_channel_msg, 7, &config, 0, &&logger, None).unwrap();
18876
18877 let mut accept_channel_msg = node_b_chan.accept_inbound_channel(&&logger).unwrap();
18879 accept_channel_msg.common_fields.dust_limit_satoshis = 546;
18880 node_a_chan.accept_channel(&accept_channel_msg, &config.channel_handshake_limits, &channelmanager::provided_init_features(&config)).unwrap();
18881 node_a_chan.context.holder_dust_limit_satoshis = 1560;
18882
18883 let output_script = node_a_chan.funding.get_funding_redeemscript();
18885 let tx = Transaction { version: Version::ONE, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
18886 value: Amount::from_sat(10000000), script_pubkey: output_script.clone(),
18887 }]};
18888 let funding_outpoint = OutPoint{ txid: tx.compute_txid(), index: 0 };
18889 let funding_created_msg = node_a_chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap();
18890 let (_, funding_signed_msg, _) = node_b_chan.funding_created(&funding_created_msg.unwrap(), best_block, &&keys_provider, &&logger).map_err(|_| ()).unwrap();
18891
18892 let res = node_a_chan.funding_signed(&funding_signed_msg.unwrap(), best_block, &&keys_provider, &&logger);
18894 let (mut node_a_chan, _) = if let Ok(res) = res { res } else { panic!(); };
18895
18896 let update = ChannelUpdate {
18898 contents: UnsignedChannelUpdate {
18899 chain_hash,
18900 short_channel_id: 0,
18901 timestamp: 0,
18902 message_flags: 1, channel_flags: 0,
18904 cltv_expiry_delta: 100,
18905 htlc_minimum_msat: 5,
18906 htlc_maximum_msat: MAX_VALUE_MSAT,
18907 fee_base_msat: 110,
18908 fee_proportional_millionths: 11,
18909 excess_data: Vec::new(),
18910 },
18911 signature: Signature::from(unsafe { FFISignature::new() })
18912 };
18913 assert!(node_a_chan.channel_update(&update).unwrap());
18914
18915 assert_eq!(node_a_chan.context.holder_htlc_minimum_msat, 1);
18918 match node_a_chan.context.counterparty_forwarding_info() {
18919 Some(info) => {
18920 assert_eq!(info.cltv_expiry_delta, 100);
18921 assert_eq!(info.fee_base_msat, 110);
18922 assert_eq!(info.fee_proportional_millionths, 11);
18923 },
18924 None => panic!("expected counterparty forwarding info to be Some")
18925 }
18926
18927 assert!(!node_a_chan.channel_update(&update).unwrap());
18928 }
18929
18930 #[test]
18931 fn blinding_point_skimmed_fee_malformed_ser() {
18932 let logger = TestLogger::new();
18935 let test_est = TestFeeEstimator::new(15000);
18936 let feeest = LowerBoundedFeeEstimator::new(&test_est);
18937 let secp_ctx = Secp256k1::new();
18938 let seed = [42; 32];
18939 let network = Network::Testnet;
18940 let best_block = BlockLocator::from_network(network);
18941 let keys_provider = TestKeysInterface::new(&seed, network);
18942
18943 let node_b_node_id =
18944 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
18945 let config = UserConfig::default();
18946 let features = channelmanager::provided_init_features(&config);
18947 let mut outbound_chan = OutboundV1Channel::<&TestKeysInterface>::new(
18948 &feeest,
18949 &&keys_provider,
18950 &&keys_provider,
18951 node_b_node_id,
18952 &features,
18953 10000000,
18954 100000,
18955 42,
18956 &config,
18957 0,
18958 42,
18959 None,
18960 &logger,
18961 None,
18962 )
18963 .unwrap();
18964 let open_channel_msg = &outbound_chan
18965 .get_open_channel(ChainHash::using_genesis_block(network), &&logger)
18966 .unwrap();
18967 let mut inbound_chan = InboundV1Channel::<&TestKeysInterface>::new(
18968 &feeest,
18969 &&keys_provider,
18970 &&keys_provider,
18971 node_b_node_id,
18972 &channelmanager::provided_channel_type_features(&config),
18973 &features,
18974 open_channel_msg,
18975 7,
18976 &config,
18977 0,
18978 &&logger,
18979 None,
18980 )
18981 .unwrap();
18982 outbound_chan
18983 .accept_channel(
18984 &inbound_chan.get_accept_channel_message(&&logger).unwrap(),
18985 &config.channel_handshake_limits,
18986 &features,
18987 )
18988 .unwrap();
18989 let tx = Transaction {
18990 version: Version::ONE,
18991 lock_time: LockTime::ZERO,
18992 input: Vec::new(),
18993 output: vec![TxOut {
18994 value: Amount::from_sat(10000000),
18995 script_pubkey: outbound_chan.funding.get_funding_redeemscript(),
18996 }],
18997 };
18998 let funding_outpoint = OutPoint { txid: tx.compute_txid(), index: 0 };
18999 let funding_created = outbound_chan
19000 .get_funding_created(tx.clone(), funding_outpoint, false, &&logger)
19001 .map_err(|_| ())
19002 .unwrap()
19003 .unwrap();
19004 let mut chan = match inbound_chan.funding_created(
19005 &funding_created,
19006 best_block,
19007 &&keys_provider,
19008 &&logger,
19009 ) {
19010 Ok((chan, _, _)) => chan,
19011 Err((_, e)) => panic!("{}", e),
19012 };
19013
19014 let dummy_htlc_source = HTLCSource::OutboundRoute {
19015 path: Path {
19016 hops: vec![RouteHop {
19017 pubkey: test_utils::pubkey(2),
19018 channel_features: ChannelFeatures::empty(),
19019 node_features: NodeFeatures::empty(),
19020 short_channel_id: 0,
19021 fee_msat: 0,
19022 cltv_expiry_delta: 0,
19023 maybe_announced_channel: false,
19024 }],
19025 blinded_tail: None,
19026 },
19027 session_priv: test_utils::privkey(42),
19028 first_hop_htlc_msat: 0,
19029 payment_id: PaymentId([42; 32]),
19030 bolt12_invoice: None,
19031 };
19032 let dummy_outbound_output = OutboundHTLCOutput {
19033 htlc_id: 0,
19034 amount_msat: 0,
19035 payment_hash: PaymentHash([43; 32]),
19036 cltv_expiry: 0,
19037 state: OutboundHTLCState::Committed,
19038 source: dummy_htlc_source.clone(),
19039 skimmed_fee_msat: None,
19040 blinding_point: None,
19041 send_timestamp: None,
19042 hold_htlc: None,
19043 accountable: false,
19044 };
19045 let mut pending_outbound_htlcs = vec![dummy_outbound_output.clone(); 10];
19046 for (idx, htlc) in pending_outbound_htlcs.iter_mut().enumerate() {
19047 if idx % 2 == 0 {
19048 htlc.blinding_point = Some(test_utils::pubkey(42 + idx as u8));
19049 }
19050 if idx % 3 == 0 {
19051 htlc.skimmed_fee_msat = Some(1);
19052 }
19053 }
19054 chan.context.pending_outbound_htlcs = pending_outbound_htlcs.clone();
19055
19056 let dummy_holding_cell_add_htlc = HTLCUpdateAwaitingACK::AddHTLC {
19057 amount_msat: 0,
19058 cltv_expiry: 0,
19059 payment_hash: PaymentHash([43; 32]),
19060 source: dummy_htlc_source.clone(),
19061 onion_routing_packet: msgs::OnionPacket {
19062 version: 0,
19063 public_key: Ok(test_utils::pubkey(1)),
19064 hop_data: [0; 20 * 65],
19065 hmac: [0; 32],
19066 },
19067 skimmed_fee_msat: None,
19068 blinding_point: None,
19069 hold_htlc: None,
19070 accountable: false,
19071 };
19072 let dummy_holding_cell_claim_htlc = |attribution_data| HTLCUpdateAwaitingACK::ClaimHTLC {
19073 payment_preimage: PaymentPreimage([42; 32]),
19074 htlc_id: 0,
19075 attribution_data,
19076 };
19077 let dummy_holding_cell_failed_htlc =
19078 |htlc_id, attribution_data| HTLCUpdateAwaitingACK::FailHTLC {
19079 htlc_id,
19080 err_packet: msgs::OnionErrorPacket { data: vec![42], attribution_data },
19081 };
19082 let dummy_holding_cell_malformed_htlc =
19083 |htlc_id| HTLCUpdateAwaitingACK::FailMalformedHTLC {
19084 htlc_id,
19085 failure_code: LocalHTLCFailureReason::InvalidOnionBlinding.failure_code(),
19086 sha256_of_onion: [0; 32],
19087 };
19088 let mut holding_cell_htlc_updates = Vec::with_capacity(12);
19089 for i in 0..16 {
19090 match i % 7 {
19091 0 => {
19092 holding_cell_htlc_updates.push(dummy_holding_cell_add_htlc.clone());
19093 },
19094 1 => {
19095 holding_cell_htlc_updates.push(dummy_holding_cell_claim_htlc(None));
19096 },
19097 2 => {
19098 holding_cell_htlc_updates
19099 .push(dummy_holding_cell_claim_htlc(Some(AttributionData::new())));
19100 },
19101 3 => {
19102 let mut dummy_add = dummy_holding_cell_add_htlc.clone();
19103 if let HTLCUpdateAwaitingACK::AddHTLC {
19104 ref mut blinding_point,
19105 ref mut skimmed_fee_msat,
19106 ..
19107 } = &mut dummy_add
19108 {
19109 *blinding_point = Some(test_utils::pubkey(42 + i));
19110 *skimmed_fee_msat = Some(42);
19111 } else {
19112 panic!()
19113 }
19114 holding_cell_htlc_updates.push(dummy_add);
19115 },
19116 4 => {
19117 holding_cell_htlc_updates.push(dummy_holding_cell_malformed_htlc(i as u64));
19118 },
19119 5 => {
19120 holding_cell_htlc_updates.push(dummy_holding_cell_failed_htlc(i as u64, None));
19121 },
19122 _ => {
19123 holding_cell_htlc_updates.push(dummy_holding_cell_failed_htlc(
19124 i as u64,
19125 Some(AttributionData::new()),
19126 ));
19127 },
19128 }
19129 }
19130 chan.context.holding_cell_htlc_updates = holding_cell_htlc_updates.clone();
19131
19132 let encoded_chan = chan.encode();
19134 let mut s = crate::io::Cursor::new(&encoded_chan);
19135 let mut reader =
19136 crate::util::ser::FixedLengthReader::new(&mut s, encoded_chan.len() as u64);
19137 let features = channelmanager::provided_channel_type_features(&config);
19138 let decoded_chan =
19139 FundedChannel::read(&mut reader, (&&keys_provider, &&keys_provider, &features))
19140 .unwrap();
19141 assert_eq!(decoded_chan.context.pending_outbound_htlcs, pending_outbound_htlcs);
19142 assert_eq!(decoded_chan.context.holding_cell_htlc_updates, holding_cell_htlc_updates);
19143 }
19144
19145 #[cfg(ldk_test_vectors)]
19146 macro_rules! test_commitment_common {
19147 ( $chan: expr, $logger: expr, $secp_ctx: expr, $signer: expr, $holder_pubkeys: expr, $per_commitment_point: expr, $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $channel_type_features: expr, {
19148 $( { $htlc_idx: expr, $counterparty_htlc_sig_hex: expr, $htlc_sig_hex: expr, $htlc_tx_hex: expr, $preimage: expr } ), *
19149 } ) => { {
19150 let commitment_data = $chan.context.build_commitment_transaction(&$chan.funding,
19151 0xffffffffffff - 42, &$per_commitment_point, true, false, &$logger);
19152 let commitment_tx = commitment_data.tx;
19153 let trusted_tx = commitment_tx.trust();
19154 let unsigned_tx = trusted_tx.built_transaction();
19155 let redeemscript = $chan.funding.get_funding_redeemscript();
19156 let counterparty_signature = Signature::from_der(&<Vec<u8>>::from_hex($counterparty_sig_hex).unwrap()[..]).unwrap();
19157 let sighash = unsigned_tx.get_sighash_all(&redeemscript, $chan.funding.get_value_satoshis());
19158 log_trace!($logger, "unsigned_tx = {}", serialize(&unsigned_tx.transaction).as_hex());
19159 assert!($secp_ctx.verify_ecdsa(&sighash, &counterparty_signature, $chan.funding.counterparty_funding_pubkey()).is_ok(), "verify counterparty commitment sig");
19160
19161 let mut per_htlc: Vec<(HTLCOutputInCommitment, Option<Signature>)> = Vec::new();
19162 per_htlc.clear(); let mut counterparty_htlc_sigs = Vec::new();
19164 counterparty_htlc_sigs.clear(); $({
19166 let remote_signature = Signature::from_der(&<Vec<u8>>::from_hex($counterparty_htlc_sig_hex).unwrap()[..]).unwrap();
19167 per_htlc.push((commitment_tx.nondust_htlcs()[$htlc_idx].clone(), Some(remote_signature)));
19168 counterparty_htlc_sigs.push(remote_signature);
19169 })*
19170 assert_eq!(commitment_tx.nondust_htlcs().len(), per_htlc.len());
19171
19172 let holder_commitment_tx = HolderCommitmentTransaction::new(
19173 commitment_tx.clone(),
19174 counterparty_signature,
19175 counterparty_htlc_sigs,
19176 &$holder_pubkeys.funding_pubkey,
19177 $chan.funding.counterparty_funding_pubkey()
19178 );
19179 let holder_sig = $signer.sign_holder_commitment(&$chan.funding.channel_transaction_parameters, &holder_commitment_tx, &$secp_ctx).unwrap();
19180 assert_eq!(Signature::from_der(&<Vec<u8>>::from_hex($sig_hex).unwrap()[..]).unwrap(), holder_sig, "holder_sig");
19181
19182 let funding_redeemscript = $chan.funding.get_funding_redeemscript();
19183 let tx = holder_commitment_tx.add_holder_sig(&funding_redeemscript, holder_sig);
19184 assert_eq!(serialize(&tx)[..], <Vec<u8>>::from_hex($tx_hex).unwrap()[..], "tx");
19185
19186 let mut htlc_counterparty_sig_iter = holder_commitment_tx.counterparty_htlc_sigs.iter();
19188
19189 $({
19190 let (htlc_sighashtype, num_anchors) = if $channel_type_features.supports_anchor_zero_fee_commitments() {
19191 (EcdsaSighashType::SinglePlusAnyoneCanPay, 1)
19192 } else if $channel_type_features.supports_anchors_zero_fee_htlc_tx() {
19193 (EcdsaSighashType::SinglePlusAnyoneCanPay, 2)
19194 } else {
19195 (EcdsaSighashType::All, 0)
19196 };
19197
19198 log_trace!($logger, "verifying htlc {}", $htlc_idx);
19199 let remote_signature = Signature::from_der(&<Vec<u8>>::from_hex($counterparty_htlc_sig_hex).unwrap()[..]).unwrap();
19200
19201 let ref htlc = commitment_tx.nondust_htlcs()[$htlc_idx];
19202 let keys = commitment_tx.trust().keys();
19203 let mut htlc_tx = chan_utils::build_htlc_transaction(&unsigned_tx.txid, $chan.context.feerate_per_kw,
19204 $chan.funding.get_counterparty_selected_contest_delay().unwrap(),
19205 &htlc, $channel_type_features, &keys.broadcaster_delayed_payment_key, &keys.revocation_key);
19206 let htlc_redeemscript = chan_utils::get_htlc_redeemscript(&htlc, $channel_type_features, &keys);
19207 let htlc_sighash = Message::from_digest(sighash::SighashCache::new(&htlc_tx).p2wsh_signature_hash(0, &htlc_redeemscript, htlc.to_bitcoin_amount(), htlc_sighashtype).unwrap().as_raw_hash().to_byte_array());
19208 assert!($secp_ctx.verify_ecdsa(&htlc_sighash, &remote_signature, &keys.countersignatory_htlc_key.to_public_key()).is_ok(), "verify counterparty htlc sig");
19209
19210 assert_eq!(htlc.offered, $preimage.is_none(), "htlc is offered: {}, with preimage: {:?}", htlc.offered, $preimage);
19212
19213 let htlc_counterparty_sig = htlc_counterparty_sig_iter.next().unwrap();
19214 let htlc_holder_sig = $signer.sign_holder_htlc_transaction(&htlc_tx, 0, &HTLCDescriptor {
19215 channel_derivation_parameters: ChannelDerivationParameters {
19216 value_satoshis: $chan.funding.get_value_satoshis(),
19217 keys_id: $chan.context.channel_keys_id,
19218 transaction_parameters: $chan.funding.channel_transaction_parameters.clone(),
19219 },
19220 commitment_txid: trusted_tx.txid(),
19221 per_commitment_number: trusted_tx.commitment_number(),
19222 per_commitment_point: trusted_tx.per_commitment_point(),
19223 feerate_per_kw: trusted_tx.negotiated_feerate_per_kw(),
19224 htlc: htlc.clone(),
19225 preimage: $preimage.clone(),
19226 counterparty_sig: *htlc_counterparty_sig,
19227 }, &$secp_ctx).unwrap();
19228 assert_eq!(htlc.transaction_output_index, Some($htlc_idx + num_anchors), "output index");
19229
19230 let signature = Signature::from_der(&<Vec<u8>>::from_hex($htlc_sig_hex).unwrap()[..]).unwrap();
19231 assert_eq!(signature, htlc_holder_sig, "htlc sig");
19232 htlc_tx.input[0].witness = chan_utils::build_htlc_input_witness(
19233 &htlc_holder_sig, htlc_counterparty_sig, &$preimage, &htlc_redeemscript,
19234 $channel_type_features,
19235 );
19236 log_trace!($logger, "htlc_tx = {}", serialize(&htlc_tx).as_hex());
19237 assert_eq!(serialize(&htlc_tx)[..], <Vec<u8>>::from_hex($htlc_tx_hex).unwrap()[..], "htlc tx");
19238 })*
19239 assert!(htlc_counterparty_sig_iter.next().is_none());
19240 } }
19241 }
19242
19243 #[cfg(ldk_test_vectors)]
19244 #[test]
19245 fn outbound_commitment_test() {
19246 assert!(cfg!(not(feature = "grind_signatures")));
19247
19248 use crate::ln::chan_utils::{
19249 ChannelPublicKeys, CounterpartyChannelTransactionParameters,
19250 HolderCommitmentTransaction,
19251 };
19252 use crate::ln::channel::{HTLCOutputInCommitment, PredictedNextFee};
19253 use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint};
19254 use crate::sign::{ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, HTLCDescriptor};
19255 use crate::sync::Arc;
19256 use crate::types::payment::PaymentPreimage;
19257 use crate::util::logger::Logger;
19258 use crate::util::test_utils::{
19259 preimage_from_hex, pubkey_from_hex, public_from_secret_hex, secret_from_hex,
19260 };
19261 use bitcoin::consensus::encode::serialize;
19262 use bitcoin::hash_types::Txid;
19263 use bitcoin::hex::DisplayHex;
19264 use bitcoin::hex::FromHex;
19265 use bitcoin::secp256k1::Message;
19266 use bitcoin::sighash;
19267 use bitcoin::sighash::EcdsaSighashType;
19268 use core::str::FromStr;
19269
19270 let feeest = TestFeeEstimator::new(15000);
19272 let logger: Arc<dyn Logger> = Arc::new(TestLogger::new());
19273 let secp_ctx = Secp256k1::new();
19274
19275 let signer = InMemorySigner::new(
19276 secret_from_hex("30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749"),
19277 secret_from_hex("0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
19278 secret_from_hex("1111111111111111111111111111111111111111111111111111111111111111"),
19279 secret_from_hex("1111111111111111111111111111111111111111111111111111111111111111"),
19280 true,
19281 secret_from_hex("3333333333333333333333333333333333333333333333333333333333333333"),
19282 secret_from_hex("1111111111111111111111111111111111111111111111111111111111111111"),
19283 [
19285 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
19286 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
19287 0xff, 0xff, 0xff, 0xff,
19288 ],
19289 [0; 32],
19290 [0; 32],
19291 );
19292
19293 let holder_pubkeys = signer.pubkeys(&secp_ctx);
19294 assert_eq!(
19295 holder_pubkeys.funding_pubkey,
19296 pubkey_from_hex("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb")
19297 );
19298 let keys_provider = Keys { signer: signer.clone() };
19299
19300 let counterparty_node_id =
19301 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
19302 let mut config = UserConfig::default();
19303 config.channel_handshake_config.announce_for_forwarding = false;
19304 let mut chan = OutboundV1Channel::<&Keys>::new(
19305 &LowerBoundedFeeEstimator::new(&feeest),
19306 &&keys_provider,
19307 &&keys_provider,
19308 counterparty_node_id,
19309 &channelmanager::provided_init_features(&config),
19310 10_000_000,
19311 0,
19312 42,
19313 &config,
19314 0,
19315 42,
19316 None,
19317 &*logger,
19318 None,
19319 )
19320 .unwrap(); chan.context.holder_dust_limit_satoshis = 546;
19322 chan.funding.counterparty_selected_channel_reserve_satoshis = Some(0); let funding_txid =
19325 Txid::from_str("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be")
19326 .unwrap();
19327 let funding_info = OutPoint { txid: funding_txid, index: 0 };
19328
19329 let counterparty_pubkeys = ChannelPublicKeys {
19330 funding_pubkey: public_from_secret_hex(
19331 &secp_ctx,
19332 "1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13",
19333 ),
19334 revocation_basepoint: RevocationBasepoint::from(pubkey_from_hex(
19335 "02466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f27",
19336 )),
19337 payment_point: public_from_secret_hex(
19338 &secp_ctx,
19339 "4444444444444444444444444444444444444444444444444444444444444444",
19340 ),
19341 delayed_payment_basepoint: DelayedPaymentBasepoint::from(public_from_secret_hex(
19342 &secp_ctx,
19343 "1552dfba4f6cf29a62a0af13c8d6981d36d0ef8d61ba10fb0fe90da7634d7e13",
19344 )),
19345 htlc_basepoint: HtlcBasepoint::from(public_from_secret_hex(
19346 &secp_ctx,
19347 "4444444444444444444444444444444444444444444444444444444444444444",
19348 )),
19349 };
19350 chan.funding.channel_transaction_parameters.counterparty_parameters =
19351 Some(CounterpartyChannelTransactionParameters {
19352 pubkeys: counterparty_pubkeys.clone(),
19353 selected_contest_delay: 144,
19354 });
19355 chan.funding.channel_transaction_parameters.funding_outpoint = Some(funding_info);
19356
19357 assert_eq!(
19358 counterparty_pubkeys.payment_point,
19359 pubkey_from_hex("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991"),
19360 );
19361
19362 assert_eq!(
19363 counterparty_pubkeys.funding_pubkey,
19364 pubkey_from_hex("030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1")
19365 );
19366
19367 assert_eq!(
19368 counterparty_pubkeys.htlc_basepoint.to_public_key(),
19369 pubkey_from_hex("032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991")
19370 );
19371
19372 let per_commitment_secret =
19376 secret_from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100");
19377 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
19378
19379 macro_rules! test_commitment {
19380 ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $($remain:tt)* ) => {
19381 chan.funding.channel_transaction_parameters.channel_type_features = ChannelTypeFeatures::only_static_remote_key();
19382 chan.funding.next_local_fee = Mutex::new(PredictedNextFee::default());
19383 chan.funding.next_remote_fee = Mutex::new(PredictedNextFee::default());
19384 test_commitment_common!(chan, logger, secp_ctx, signer, holder_pubkeys, per_commitment_point, $counterparty_sig_hex, $sig_hex, $tx_hex, &ChannelTypeFeatures::only_static_remote_key(), $($remain)*);
19385 };
19386 }
19387
19388 macro_rules! test_commitment_with_anchors {
19389 ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $($remain:tt)* ) => {
19390 chan.funding.channel_transaction_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
19391 chan.funding.next_local_fee = Mutex::new(PredictedNextFee::default());
19392 chan.funding.next_remote_fee = Mutex::new(PredictedNextFee::default());
19393 test_commitment_common!(chan, logger, secp_ctx, signer, holder_pubkeys, per_commitment_point, $counterparty_sig_hex, $sig_hex, $tx_hex, &ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies(), $($remain)*);
19394 };
19395 }
19396
19397 test_commitment_with_anchors!("30440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a8658",
19399 "3044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778",
19400 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f10529800000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778014730440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a865801475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19401
19402 chan.funding.value_to_self_msat = 7000000000;
19404
19405 test_commitment!("3045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b0",
19406 "30440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae055647142",
19407 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e48454a56a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004730440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae05564714201483045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19408
19409 test_commitment_with_anchors!("3045022100f89034eba16b2be0e5581f750a0a6309192b75cce0f202f0ee2b4ec0cc394850022076c65dc507fe42276152b7a3d90e961e678adbe966e916ecfe85e64d430e75f3",
19411 "30450221008266ac6db5ea71aac3c95d97b0e172ff596844851a3216eb88382a8dddfd33d2022050e240974cfd5d708708b4365574517c18e7ae535ef732a3484d43d0d82be9f7",
19412 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80044a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994a508b6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221008266ac6db5ea71aac3c95d97b0e172ff596844851a3216eb88382a8dddfd33d2022050e240974cfd5d708708b4365574517c18e7ae535ef732a3484d43d0d82be9f701483045022100f89034eba16b2be0e5581f750a0a6309192b75cce0f202f0ee2b4ec0cc394850022076c65dc507fe42276152b7a3d90e961e678adbe966e916ecfe85e64d430e75f301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19413
19414 let payment_preimage_0 =
19415 preimage_from_hex("0000000000000000000000000000000000000000000000000000000000000000");
19416 chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
19417 htlc_id: 0,
19418 amount_msat: 1000000,
19419 cltv_expiry: 500,
19420 payment_hash: PaymentHash::from(payment_preimage_0),
19421 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
19422 });
19423
19424 let payment_preimage_1 =
19425 preimage_from_hex("0101010101010101010101010101010101010101010101010101010101010101");
19426 chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
19427 htlc_id: 1,
19428 amount_msat: 2000000,
19429 cltv_expiry: 501,
19430 payment_hash: PaymentHash::from(payment_preimage_1),
19431 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
19432 });
19433
19434 let payment_preimage_2 =
19435 preimage_from_hex("0202020202020202020202020202020202020202020202020202020202020202");
19436 chan.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
19437 htlc_id: 2,
19438 amount_msat: 2000000,
19439 cltv_expiry: 502,
19440 payment_hash: PaymentHash::from(payment_preimage_2),
19441 state: OutboundHTLCState::Committed,
19442 source: HTLCSource::dummy(),
19443 skimmed_fee_msat: None,
19444 blinding_point: None,
19445 send_timestamp: None,
19446 hold_htlc: None,
19447 accountable: false,
19448 });
19449
19450 let payment_preimage_3 =
19451 preimage_from_hex("0303030303030303030303030303030303030303030303030303030303030303");
19452 chan.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
19453 htlc_id: 3,
19454 amount_msat: 3000000,
19455 cltv_expiry: 503,
19456 payment_hash: PaymentHash::from(payment_preimage_3),
19457 state: OutboundHTLCState::Committed,
19458 source: HTLCSource::dummy(),
19459 skimmed_fee_msat: None,
19460 blinding_point: None,
19461 send_timestamp: None,
19462 hold_htlc: None,
19463 accountable: false,
19464 });
19465
19466 let payment_preimage_4 =
19467 preimage_from_hex("0404040404040404040404040404040404040404040404040404040404040404");
19468 chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
19469 htlc_id: 4,
19470 amount_msat: 4000000,
19471 cltv_expiry: 504,
19472 payment_hash: PaymentHash::from(payment_preimage_4),
19473 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
19474 });
19475
19476 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 0;
19479
19480 test_commitment!("3044022009b048187705a8cbc9ad73adbe5af148c3d012e1f067961486c822c7af08158c022006d66f3704cfab3eb2dc49dae24e4aa22a6910fc9b424007583204e3621af2e5",
19481 "304402206fc2d1f10ea59951eefac0b4b7c396a3c3d87b71ff0b019796ef4535beaf36f902201765b0181e514d04f4c8ad75659d7037be26cdb3f8bb6f78fe61decef484c3ea",
19482 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8007e80300000000000022002052bfef0479d7b293c27e0f1eb294bea154c63a3294ef092c19af51409bce0e2ad007000000000000220020403d394747cae42e98ff01734ad5c08f82ba123d3d9a620abda88989651e2ab5d007000000000000220020748eba944fedc8827f6b06bc44678f93c0f9e6078b35c6331ed31e75f8ce0c2db80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484e0a06a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e040047304402206fc2d1f10ea59951eefac0b4b7c396a3c3d87b71ff0b019796ef4535beaf36f902201765b0181e514d04f4c8ad75659d7037be26cdb3f8bb6f78fe61decef484c3ea01473044022009b048187705a8cbc9ad73adbe5af148c3d012e1f067961486c822c7af08158c022006d66f3704cfab3eb2dc49dae24e4aa22a6910fc9b424007583204e3621af2e501475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19483
19484 { 0,
19485 "3045022100d9e29616b8f3959f1d3d7f7ce893ffedcdc407717d0de8e37d808c91d3a7c50d022078c3033f6d00095c8720a4bc943c1b45727818c082e4e3ddbc6d3116435b624b",
19486 "30440220636de5682ef0c5b61f124ec74e8aa2461a69777521d6998295dcea36bc3338110220165285594b23c50b28b82df200234566628a27bcd17f7f14404bd865354eb3ce",
19487 "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b00000000000000000001e8030000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100d9e29616b8f3959f1d3d7f7ce893ffedcdc407717d0de8e37d808c91d3a7c50d022078c3033f6d00095c8720a4bc943c1b45727818c082e4e3ddbc6d3116435b624b014730440220636de5682ef0c5b61f124ec74e8aa2461a69777521d6998295dcea36bc3338110220165285594b23c50b28b82df200234566628a27bcd17f7f14404bd865354eb3ce012000000000000000000000000000000000000000000000000000000000000000008a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a914b8bcb07f6344b42ab04250c86a6e8b75d3fdbbc688527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f401b175ac686800000000", Some(payment_preimage_0) },
19488
19489 { 1,
19490 "30440220649fe8b20e67e46cbb0d09b4acea87dbec001b39b08dee7bdd0b1f03922a8640022037c462dff79df501cecfdb12ea7f4de91f99230bb544726f6e04527b1f896004",
19491 "3045022100803159dee7935dba4a1d36a61055ce8fd62caa528573cc221ae288515405a252022029c59e7cffce374fe860100a4a63787e105c3cf5156d40b12dd53ff55ac8cf3f",
19492 "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b01000000000000000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220649fe8b20e67e46cbb0d09b4acea87dbec001b39b08dee7bdd0b1f03922a8640022037c462dff79df501cecfdb12ea7f4de91f99230bb544726f6e04527b1f89600401483045022100803159dee7935dba4a1d36a61055ce8fd62caa528573cc221ae288515405a252022029c59e7cffce374fe860100a4a63787e105c3cf5156d40b12dd53ff55ac8cf3f01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000", None::<PaymentPreimage> },
19493
19494 { 2,
19495 "30440220770fc321e97a19f38985f2e7732dd9fe08d16a2efa4bcbc0429400a447faf49102204d40b417f3113e1b0944ae0986f517564ab4acd3d190503faf97a6e420d43352",
19496 "3045022100a437cc2ce77400ecde441b3398fea3c3ad8bdad8132be818227fe3c5b8345989022069d45e7fa0ae551ec37240845e2c561ceb2567eacf3076a6a43a502d05865faa",
19497 "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b02000000000000000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220770fc321e97a19f38985f2e7732dd9fe08d16a2efa4bcbc0429400a447faf49102204d40b417f3113e1b0944ae0986f517564ab4acd3d190503faf97a6e420d4335201483045022100a437cc2ce77400ecde441b3398fea3c3ad8bdad8132be818227fe3c5b8345989022069d45e7fa0ae551ec37240845e2c561ceb2567eacf3076a6a43a502d05865faa012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000", Some(payment_preimage_1) },
19498
19499 { 3,
19500 "304402207bcbf4f60a9829b05d2dbab84ed593e0291836be715dc7db6b72a64caf646af802201e489a5a84f7c5cc130398b841d138d031a5137ac8f4c49c770a4959dc3c1363",
19501 "304402203121d9b9c055f354304b016a36662ee99e1110d9501cb271b087ddb6f382c2c80220549882f3f3b78d9c492de47543cb9a697cecc493174726146536c5954dac7487",
19502 "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b03000000000000000001b80b0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402207bcbf4f60a9829b05d2dbab84ed593e0291836be715dc7db6b72a64caf646af802201e489a5a84f7c5cc130398b841d138d031a5137ac8f4c49c770a4959dc3c13630147304402203121d9b9c055f354304b016a36662ee99e1110d9501cb271b087ddb6f382c2c80220549882f3f3b78d9c492de47543cb9a697cecc493174726146536c5954dac748701008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19503
19504 { 4,
19505 "3044022076dca5cb81ba7e466e349b7128cdba216d4d01659e29b96025b9524aaf0d1899022060de85697b88b21c749702b7d2cfa7dfeaa1f472c8f1d7d9c23f2bf968464b87",
19506 "3045022100d9080f103cc92bac15ec42464a95f070c7fb6925014e673ee2ea1374d36a7f7502200c65294d22eb20d48564954d5afe04a385551919d8b2ddb4ae2459daaeee1d95",
19507 "02000000000101ab84ff284f162cfbfef241f853b47d4368d171f9e2a1445160cd591c4c7d882b04000000000000000001a00f0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022076dca5cb81ba7e466e349b7128cdba216d4d01659e29b96025b9524aaf0d1899022060de85697b88b21c749702b7d2cfa7dfeaa1f472c8f1d7d9c23f2bf968464b8701483045022100d9080f103cc92bac15ec42464a95f070c7fb6925014e673ee2ea1374d36a7f7502200c65294d22eb20d48564954d5afe04a385551919d8b2ddb4ae2459daaeee1d95012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4)}
19508 } );
19509
19510 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 647;
19513
19514 test_commitment!("3045022100a135f9e8a5ed25f7277446c67956b00ce6f610ead2bdec2c2f686155b7814772022059f1f6e1a8b336a68efcc1af3fe4d422d4827332b5b067501b099c47b7b5b5ee",
19515 "30450221009ec15c687898bb4da8b3a833e5ab8bfc51ec6e9202aaa8e66611edfd4a85ed1102203d7183e45078b9735c93450bc3415d3e5a8c576141a711ec6ddcb4a893926bb7",
19516 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8007e80300000000000022002052bfef0479d7b293c27e0f1eb294bea154c63a3294ef092c19af51409bce0e2ad007000000000000220020403d394747cae42e98ff01734ad5c08f82ba123d3d9a620abda88989651e2ab5d007000000000000220020748eba944fedc8827f6b06bc44678f93c0f9e6078b35c6331ed31e75f8ce0c2db80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484e09c6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221009ec15c687898bb4da8b3a833e5ab8bfc51ec6e9202aaa8e66611edfd4a85ed1102203d7183e45078b9735c93450bc3415d3e5a8c576141a711ec6ddcb4a893926bb701483045022100a135f9e8a5ed25f7277446c67956b00ce6f610ead2bdec2c2f686155b7814772022059f1f6e1a8b336a68efcc1af3fe4d422d4827332b5b067501b099c47b7b5b5ee01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19517
19518 { 0,
19519 "30450221008437627f9ad84ac67052e2a414a4367b8556fd1f94d8b02590f89f50525cd33502205b9c21ff6e7fc864f2352746ad8ba59182510819acb644e25b8a12fc37bbf24f",
19520 "30440220344b0deb055230d01703e6c7acd45853c4af2328b49b5d8af4f88a060733406602202ea64f2a43d5751edfe75503cbc35a62e3141b5ed032fa03360faf4ca66f670b",
19521 "020000000001012cfb3e4788c206881d38f2996b6cb2109b5935acb527d14bdaa7b908afa9b2fe0000000000000000000122020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004830450221008437627f9ad84ac67052e2a414a4367b8556fd1f94d8b02590f89f50525cd33502205b9c21ff6e7fc864f2352746ad8ba59182510819acb644e25b8a12fc37bbf24f014730440220344b0deb055230d01703e6c7acd45853c4af2328b49b5d8af4f88a060733406602202ea64f2a43d5751edfe75503cbc35a62e3141b5ed032fa03360faf4ca66f670b012000000000000000000000000000000000000000000000000000000000000000008a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a914b8bcb07f6344b42ab04250c86a6e8b75d3fdbbc688527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f401b175ac686800000000", Some(payment_preimage_0) },
19522
19523 { 1,
19524 "304402205a67f92bf6845cf2892b48d874ac1daf88a36495cf8a06f93d83180d930a6f75022031da1621d95c3f335cc06a3056cf960199dae600b7cf89088f65fc53cdbef28c",
19525 "30450221009e5e3822b0185c6799a95288c597b671d6cc69ab80f43740f00c6c3d0752bdda02206da947a74bd98f3175324dc56fdba86cc783703a120a6f0297537e60632f4c7f",
19526 "020000000001012cfb3e4788c206881d38f2996b6cb2109b5935acb527d14bdaa7b908afa9b2fe0100000000000000000124060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402205a67f92bf6845cf2892b48d874ac1daf88a36495cf8a06f93d83180d930a6f75022031da1621d95c3f335cc06a3056cf960199dae600b7cf89088f65fc53cdbef28c014830450221009e5e3822b0185c6799a95288c597b671d6cc69ab80f43740f00c6c3d0752bdda02206da947a74bd98f3175324dc56fdba86cc783703a120a6f0297537e60632f4c7f01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000", None::<PaymentPreimage> },
19527
19528 { 2,
19529 "30440220437e21766054a3eef7f65690c5bcfa9920babbc5af92b819f772f6ea96df6c7402207173622024bd97328cfb26c6665e25c2f5d67c319443ccdc60c903217005d8c8",
19530 "3045022100fcfc47e36b712624677626cef3dc1d67f6583bd46926a6398fe6b00b0c9a37760220525788257b187fc775c6370d04eadf34d06f3650a63f8df851cee0ecb47a1673",
19531 "020000000001012cfb3e4788c206881d38f2996b6cb2109b5935acb527d14bdaa7b908afa9b2fe020000000000000000010a060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220437e21766054a3eef7f65690c5bcfa9920babbc5af92b819f772f6ea96df6c7402207173622024bd97328cfb26c6665e25c2f5d67c319443ccdc60c903217005d8c801483045022100fcfc47e36b712624677626cef3dc1d67f6583bd46926a6398fe6b00b0c9a37760220525788257b187fc775c6370d04eadf34d06f3650a63f8df851cee0ecb47a1673012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000", Some(payment_preimage_1) },
19532
19533 { 3,
19534 "304402207436e10737e4df499fc051686d3e11a5bb2310e4d1f1e691d287cef66514791202207cb58e71a6b7a42dd001b7e3ae672ea4f71ea3e1cd412b742e9124abb0739c64",
19535 "3045022100e78211b8409afb7255ffe37337da87f38646f1faebbdd61bc1920d69e3ead67a02201a626305adfcd16bfb7e9340928d9b6305464eab4aa4c4a3af6646e9b9f69dee",
19536 "020000000001012cfb3e4788c206881d38f2996b6cb2109b5935acb527d14bdaa7b908afa9b2fe030000000000000000010c0a0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402207436e10737e4df499fc051686d3e11a5bb2310e4d1f1e691d287cef66514791202207cb58e71a6b7a42dd001b7e3ae672ea4f71ea3e1cd412b742e9124abb0739c6401483045022100e78211b8409afb7255ffe37337da87f38646f1faebbdd61bc1920d69e3ead67a02201a626305adfcd16bfb7e9340928d9b6305464eab4aa4c4a3af6646e9b9f69dee01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19537
19538 { 4,
19539 "30450221009acd6a827a76bfee50806178dfe0495cd4e1d9c58279c194c7b01520fe68cb8d022024d439047c368883e570997a7d40f0b430cb5a742f507965e7d3063ae3feccca",
19540 "3044022048762cf546bbfe474f1536365ea7c416e3c0389d60558bc9412cb148fb6ab68202207215d7083b75c96ff9d2b08c59c34e287b66820f530b486a9aa4cdd9c347d5b9",
19541 "020000000001012cfb3e4788c206881d38f2996b6cb2109b5935acb527d14bdaa7b908afa9b2fe04000000000000000001da0d0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004830450221009acd6a827a76bfee50806178dfe0495cd4e1d9c58279c194c7b01520fe68cb8d022024d439047c368883e570997a7d40f0b430cb5a742f507965e7d3063ae3feccca01473044022048762cf546bbfe474f1536365ea7c416e3c0389d60558bc9412cb148fb6ab68202207215d7083b75c96ff9d2b08c59c34e287b66820f530b486a9aa4cdd9c347d5b9012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4)}
19542 } );
19543
19544 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 648;
19547
19548 test_commitment!("304402203948f900a5506b8de36a4d8502f94f21dd84fd9c2314ab427d52feaa7a0a19f2022059b6a37a4adaa2c5419dc8aea63c6e2a2ec4c4bde46207f6dc1fcd22152fc6e5",
19549 "3045022100b15f72908ba3382a34ca5b32519240a22300cc6015b6f9418635fb41f3d01d8802207adb331b9ed1575383dca0f2355e86c173802feecf8298fbea53b9d4610583e9",
19550 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8006d007000000000000220020403d394747cae42e98ff01734ad5c08f82ba123d3d9a620abda88989651e2ab5d007000000000000220020748eba944fedc8827f6b06bc44678f93c0f9e6078b35c6331ed31e75f8ce0c2db80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e4844e9d6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100b15f72908ba3382a34ca5b32519240a22300cc6015b6f9418635fb41f3d01d8802207adb331b9ed1575383dca0f2355e86c173802feecf8298fbea53b9d4610583e90147304402203948f900a5506b8de36a4d8502f94f21dd84fd9c2314ab427d52feaa7a0a19f2022059b6a37a4adaa2c5419dc8aea63c6e2a2ec4c4bde46207f6dc1fcd22152fc6e501475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19551
19552 { 0,
19553 "3045022100a031202f3be94678f0e998622ee95ebb6ada8da1e9a5110228b5e04a747351e4022010ca6a21e18314ed53cfaae3b1f51998552a61a468e596368829a50ce40110e0",
19554 "304502210097e1873b57267730154595187a34949d3744f52933070c74757005e61ce2112e02204ecfba2aa42d4f14bdf8bad4206bb97217b702e6c433e0e1b0ce6587e6d46ec6",
19555 "020000000001010f44041fdfba175987cf4e6135ba2a154e3b7fb96483dc0ed5efc0678e5b6bf10000000000000000000123060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100a031202f3be94678f0e998622ee95ebb6ada8da1e9a5110228b5e04a747351e4022010ca6a21e18314ed53cfaae3b1f51998552a61a468e596368829a50ce40110e00148304502210097e1873b57267730154595187a34949d3744f52933070c74757005e61ce2112e02204ecfba2aa42d4f14bdf8bad4206bb97217b702e6c433e0e1b0ce6587e6d46ec601008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000", None::<PaymentPreimage> },
19556
19557 { 1,
19558 "304402202361012a634aee7835c5ecdd6413dcffa8f404b7e77364c792cff984e4ee71e90220715c5e90baa08daa45a7439b1ee4fa4843ed77b19c058240b69406606d384124",
19559 "3044022019de73b00f1d818fb388e83b2c8c31f6bce35ac624e215bc12f88f9dc33edf48022006ff814bb9f700ee6abc3294e146fac3efd4f13f0005236b41c0a946ee00c9ae",
19560 "020000000001010f44041fdfba175987cf4e6135ba2a154e3b7fb96483dc0ed5efc0678e5b6bf10100000000000000000109060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402202361012a634aee7835c5ecdd6413dcffa8f404b7e77364c792cff984e4ee71e90220715c5e90baa08daa45a7439b1ee4fa4843ed77b19c058240b69406606d38412401473044022019de73b00f1d818fb388e83b2c8c31f6bce35ac624e215bc12f88f9dc33edf48022006ff814bb9f700ee6abc3294e146fac3efd4f13f0005236b41c0a946ee00c9ae012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000", Some(payment_preimage_1) },
19561
19562 { 2,
19563 "304402207e8e82cd71ed4febeb593732c260456836e97d81896153ecd2b3cf320ca6861702202dd4a30f68f98ced7cc56a36369ac1fdd978248c5ff4ed204fc00cc625532989",
19564 "3045022100bd0be6100c4fd8f102ec220e1b053e4c4e2ecca25615490150007b40d314dc3902201a1e0ea266965b43164d9e6576f58fa6726d42883dd1c3996d2925c2e2260796",
19565 "020000000001010f44041fdfba175987cf4e6135ba2a154e3b7fb96483dc0ed5efc0678e5b6bf1020000000000000000010b0a0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402207e8e82cd71ed4febeb593732c260456836e97d81896153ecd2b3cf320ca6861702202dd4a30f68f98ced7cc56a36369ac1fdd978248c5ff4ed204fc00cc62553298901483045022100bd0be6100c4fd8f102ec220e1b053e4c4e2ecca25615490150007b40d314dc3902201a1e0ea266965b43164d9e6576f58fa6726d42883dd1c3996d2925c2e226079601008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19566
19567 { 3,
19568 "3044022024cd52e4198c8ae0e414a86d86b5a65ea7450f2eb4e783096736d93395eca5ce022078f0094745b45be4d4b2b04dd5978c9e66ba49109e5704403e84aaf5f387d6be",
19569 "3045022100bbfb9d0a946d420807c86e985d636cceb16e71c3694ed186316251a00cbd807202207773223f9a337e145f64673825be9b30d07ef1542c82188b264bedcf7cda78c6",
19570 "020000000001010f44041fdfba175987cf4e6135ba2a154e3b7fb96483dc0ed5efc0678e5b6bf103000000000000000001d90d0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022024cd52e4198c8ae0e414a86d86b5a65ea7450f2eb4e783096736d93395eca5ce022078f0094745b45be4d4b2b04dd5978c9e66ba49109e5704403e84aaf5f387d6be01483045022100bbfb9d0a946d420807c86e985d636cceb16e71c3694ed186316251a00cbd807202207773223f9a337e145f64673825be9b30d07ef1542c82188b264bedcf7cda78c6012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19571 } );
19572
19573 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 645;
19576 chan.context.holder_dust_limit_satoshis = 1001;
19577
19578 test_commitment_with_anchors!("3044022025d97466c8049e955a5afce28e322f4b34d2561118e52332fb400f9b908cc0a402205dc6fba3a0d67ee142c428c535580cd1f2ff42e2f89b47e0c8a01847caffc312",
19579 "3045022100d57697c707b6f6d053febf24b98e8989f186eea42e37e9e91663ec2c70bb8f70022079b0715a472118f262f43016a674f59c015d9cafccec885968e76d9d9c5d0051",
19580 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80084a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994d0070000000000002200203e68115ae0b15b8de75b6c6bc9af5ac9f01391544e0870dae443a1e8fe7837ead007000000000000220020fe0598d74fee2205cc3672e6e6647706b4f3099713b4661b62482c3addd04a5eb80b000000000000220020f96d0334feb64a4f40eb272031d07afcb038db56aa57446d60308c9f8ccadef9a00f000000000000220020ce6e751274836ff59622a0d1e07f8831d80bd6730bd48581398bfadd2bb8da9ac0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994abc996a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100d57697c707b6f6d053febf24b98e8989f186eea42e37e9e91663ec2c70bb8f70022079b0715a472118f262f43016a674f59c015d9cafccec885968e76d9d9c5d005101473044022025d97466c8049e955a5afce28e322f4b34d2561118e52332fb400f9b908cc0a402205dc6fba3a0d67ee142c428c535580cd1f2ff42e2f89b47e0c8a01847caffc31201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19581
19582 { 0,
19583 "3045022100e04d160a326432659fe9fb127304c1d348dfeaba840081bdc57d8efd902a48d8022008a824e7cf5492b97e4d9e03c06a09f822775a44f6b5b2533a2088904abfc282",
19584 "3045022100b7c49846466b13b190ff739bbe3005c105482fc55539e55b1c561f76b6982b6c02200e5c35808619cf543c8405cff9fedd25f333a4a2f6f6d5e8af8150090c40ef09",
19585 "02000000000101104f394af4c4fad78337f95e3e9f802f4c0d86ab231853af09b285348561320002000000000100000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100e04d160a326432659fe9fb127304c1d348dfeaba840081bdc57d8efd902a48d8022008a824e7cf5492b97e4d9e03c06a09f822775a44f6b5b2533a2088904abfc28283483045022100b7c49846466b13b190ff739bbe3005c105482fc55539e55b1c561f76b6982b6c02200e5c35808619cf543c8405cff9fedd25f333a4a2f6f6d5e8af8150090c40ef0901008876a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6851b27568f6010000", None::<PaymentPreimage> },
19586
19587 { 1,
19588 "3045022100fbdc3c367ce3bf30796025cc590ee1f2ce0e72ae1ac19f5986d6d0a4fc76211f02207e45ae9267e8e820d188569604f71d1abd11bd385d58853dd7dc034cdb3e9a6e",
19589 "3045022100d29330f24db213b262068706099b39c15fa7e070c3fcdf8836c09723fc4d365602203ce57d01e9f28601e461a0b5c4a50119b270bde8b70148d133a6849c70b115ac",
19590 "02000000000101104f394af4c4fad78337f95e3e9f802f4c0d86ab231853af09b285348561320003000000000100000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100fbdc3c367ce3bf30796025cc590ee1f2ce0e72ae1ac19f5986d6d0a4fc76211f02207e45ae9267e8e820d188569604f71d1abd11bd385d58853dd7dc034cdb3e9a6e83483045022100d29330f24db213b262068706099b39c15fa7e070c3fcdf8836c09723fc4d365602203ce57d01e9f28601e461a0b5c4a50119b270bde8b70148d133a6849c70b115ac012001010101010101010101010101010101010101010101010101010101010101018d76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac6851b2756800000000", Some(payment_preimage_1) },
19591
19592 { 2,
19593 "3044022066c5ef625cee3ddd2bc7b6bfb354b5834cf1cc6d52dd972fb41b7b225437ae4a022066cb85647df65c6b87a54e416dcdcca778a776c36a9643d2b5dc793c9b29f4c1",
19594 "304402202d4ce515cd9000ec37575972d70b8d24f73909fb7012e8ebd8c2066ef6fe187902202830b53e64ea565fecd0f398100691da6bb2a5cf9bb0d1926f1d71d05828a11e",
19595 "02000000000101104f394af4c4fad78337f95e3e9f802f4c0d86ab231853af09b285348561320004000000000100000001b80b0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022066c5ef625cee3ddd2bc7b6bfb354b5834cf1cc6d52dd972fb41b7b225437ae4a022066cb85647df65c6b87a54e416dcdcca778a776c36a9643d2b5dc793c9b29f4c18347304402202d4ce515cd9000ec37575972d70b8d24f73909fb7012e8ebd8c2066ef6fe187902202830b53e64ea565fecd0f398100691da6bb2a5cf9bb0d1926f1d71d05828a11e01008876a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6851b27568f7010000", None::<PaymentPreimage> },
19596
19597 { 3,
19598 "3044022022c7e11595c53ee89a57ca76baf0aed730da035952d6ab3fe6459f5eff3b337a022075e10cc5f5fd724a35ce4087a5d03cd616698626c69814032132b50bb97dc615",
19599 "3045022100b20cd63e0587d1711beaebda4730775c4ac8b8b2ec78fe18a0c44c3f168c25230220079abb7fc4924e2fca5950842e5b9e416735585026914570078c4ef62f286226",
19600 "02000000000101104f394af4c4fad78337f95e3e9f802f4c0d86ab231853af09b285348561320005000000000100000001a00f0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022022c7e11595c53ee89a57ca76baf0aed730da035952d6ab3fe6459f5eff3b337a022075e10cc5f5fd724a35ce4087a5d03cd616698626c69814032132b50bb97dc61583483045022100b20cd63e0587d1711beaebda4730775c4ac8b8b2ec78fe18a0c44c3f168c25230220079abb7fc4924e2fca5950842e5b9e416735585026914570078c4ef62f286226012004040404040404040404040404040404040404040404040404040404040404048d76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac6851b2756800000000", Some(payment_preimage_4) }
19601 } );
19602
19603 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 2069;
19606 chan.context.holder_dust_limit_satoshis = 546;
19607
19608 test_commitment!("304502210090b96a2498ce0c0f2fadbec2aab278fed54c1a7838df793ec4d2c78d96ec096202204fdd439c50f90d483baa7b68feeef4bd33bc277695405447bcd0bfb2ca34d7bc",
19609 "3045022100ad9a9bbbb75d506ca3b716b336ee3cf975dd7834fcf129d7dd188146eb58a8b4022061a759ee417339f7fe2ea1e8deb83abb6a74db31a09b7648a932a639cda23e33",
19610 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8006d007000000000000220020403d394747cae42e98ff01734ad5c08f82ba123d3d9a620abda88989651e2ab5d007000000000000220020748eba944fedc8827f6b06bc44678f93c0f9e6078b35c6331ed31e75f8ce0c2db80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e48477956a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100ad9a9bbbb75d506ca3b716b336ee3cf975dd7834fcf129d7dd188146eb58a8b4022061a759ee417339f7fe2ea1e8deb83abb6a74db31a09b7648a932a639cda23e330148304502210090b96a2498ce0c0f2fadbec2aab278fed54c1a7838df793ec4d2c78d96ec096202204fdd439c50f90d483baa7b68feeef4bd33bc277695405447bcd0bfb2ca34d7bc01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19611
19612 { 0,
19613 "3045022100f33513ee38abf1c582876f921f8fddc06acff48e04515532a32d3938de938ffd02203aa308a2c1863b7d6fdf53159a1465bf2e115c13152546cc5d74483ceaa7f699",
19614 "3045022100a637902a5d4c9ba9e7c472a225337d5aac9e2e3f6744f76e237132e7619ba0400220035c60d784a031c0d9f6df66b7eab8726a5c25397399ee4aa960842059eb3f9d",
19615 "02000000000101adbe717a63fb658add30ada1e6e12ed257637581898abe475c11d7bbcd65bd4d0000000000000000000175020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100f33513ee38abf1c582876f921f8fddc06acff48e04515532a32d3938de938ffd02203aa308a2c1863b7d6fdf53159a1465bf2e115c13152546cc5d74483ceaa7f69901483045022100a637902a5d4c9ba9e7c472a225337d5aac9e2e3f6744f76e237132e7619ba0400220035c60d784a031c0d9f6df66b7eab8726a5c25397399ee4aa960842059eb3f9d01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000", None::<PaymentPreimage> },
19616
19617 { 1,
19618 "3045022100ce07682cf4b90093c22dc2d9ab2a77ad6803526b655ef857221cc96af5c9e0bf02200f501cee22e7a268af40b555d15a8237c9f36ad67ef1841daf9f6a0267b1e6df",
19619 "3045022100e57e46234f8782d3ff7aa593b4f7446fb5316c842e693dc63ee324fd49f6a1c302204a2f7b44c48bd26e1554422afae13153eb94b29d3687b733d18930615fb2db61",
19620 "02000000000101adbe717a63fb658add30ada1e6e12ed257637581898abe475c11d7bbcd65bd4d0100000000000000000122020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100ce07682cf4b90093c22dc2d9ab2a77ad6803526b655ef857221cc96af5c9e0bf02200f501cee22e7a268af40b555d15a8237c9f36ad67ef1841daf9f6a0267b1e6df01483045022100e57e46234f8782d3ff7aa593b4f7446fb5316c842e693dc63ee324fd49f6a1c302204a2f7b44c48bd26e1554422afae13153eb94b29d3687b733d18930615fb2db61012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000", Some(payment_preimage_1) },
19621
19622 { 2,
19623 "3045022100e3e35492e55f82ec0bc2f317ffd7a486d1f7024330fe9743c3559fc39f32ef0c02203d1d4db651fc388a91d5ad8ecdd8e83673063bc8eefe27cfd8c189090e3a23e0",
19624 "3044022068613fb1b98eb3aec7f44c5b115b12343c2f066c4277c82b5f873dfe68f37f50022028109b4650f3f528ca4bfe9a467aff2e3e43893b61b5159157119d5d95cf1c18",
19625 "02000000000101adbe717a63fb658add30ada1e6e12ed257637581898abe475c11d7bbcd65bd4d020000000000000000015d060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100e3e35492e55f82ec0bc2f317ffd7a486d1f7024330fe9743c3559fc39f32ef0c02203d1d4db651fc388a91d5ad8ecdd8e83673063bc8eefe27cfd8c189090e3a23e001473044022068613fb1b98eb3aec7f44c5b115b12343c2f066c4277c82b5f873dfe68f37f50022028109b4650f3f528ca4bfe9a467aff2e3e43893b61b5159157119d5d95cf1c1801008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19626
19627 { 3,
19628 "304402207475aeb0212ef9bf5130b60937817ad88c9a87976988ef1f323f026148cc4a850220739fea17ad3257dcad72e509c73eebe86bee30b178467b9fdab213d631b109df",
19629 "3045022100d315522e09e7d53d2a659a79cb67fef56d6c4bddf3f46df6772d0d20a7beb7c8022070bcc17e288607b6a72be0bd83368bb6d53488db266c1cdb4d72214e4f02ac33",
19630 "02000000000101adbe717a63fb658add30ada1e6e12ed257637581898abe475c11d7bbcd65bd4d03000000000000000001f2090000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402207475aeb0212ef9bf5130b60937817ad88c9a87976988ef1f323f026148cc4a850220739fea17ad3257dcad72e509c73eebe86bee30b178467b9fdab213d631b109df01483045022100d315522e09e7d53d2a659a79cb67fef56d6c4bddf3f46df6772d0d20a7beb7c8022070bcc17e288607b6a72be0bd83368bb6d53488db266c1cdb4d72214e4f02ac33012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19631 } );
19632
19633 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 2070;
19636
19637 test_commitment!("304402204ca1ba260dee913d318271d86e10ca0f5883026fb5653155cff600fb40895223022037b145204b7054a40e08bb1fefbd826f827b40838d3e501423bcc57924bcb50c",
19638 "3044022001014419b5ba00e083ac4e0a85f19afc848aacac2d483b4b525d15e2ae5adbfe022015ebddad6ee1e72b47cb09f3e78459da5be01ccccd95dceca0e056a00cc773c1",
19639 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8005d007000000000000220020403d394747cae42e98ff01734ad5c08f82ba123d3d9a620abda88989651e2ab5b80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484da966a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022001014419b5ba00e083ac4e0a85f19afc848aacac2d483b4b525d15e2ae5adbfe022015ebddad6ee1e72b47cb09f3e78459da5be01ccccd95dceca0e056a00cc773c10147304402204ca1ba260dee913d318271d86e10ca0f5883026fb5653155cff600fb40895223022037b145204b7054a40e08bb1fefbd826f827b40838d3e501423bcc57924bcb50c01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19640
19641 { 0,
19642 "304402205f6b6d12d8d2529fb24f4445630566cf4abbd0f9330ab6c2bdb94222d6a2a0c502202f556258ae6f05b193749e4c541dfcc13b525a5422f6291f073f15617ba8579b",
19643 "30440220150b11069454da70caf2492ded9e0065c9a57f25ac2a4c52657b1d15b6c6ed85022068a38833b603c8892717206383611bad210f1cbb4b1f87ea29c6c65b9e1cb3e5",
19644 "02000000000101403ad7602b43293497a3a2235a12ecefda4f3a1f1d06e49b1786d945685de1ff0000000000000000000174020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402205f6b6d12d8d2529fb24f4445630566cf4abbd0f9330ab6c2bdb94222d6a2a0c502202f556258ae6f05b193749e4c541dfcc13b525a5422f6291f073f15617ba8579b014730440220150b11069454da70caf2492ded9e0065c9a57f25ac2a4c52657b1d15b6c6ed85022068a38833b603c8892717206383611bad210f1cbb4b1f87ea29c6c65b9e1cb3e501008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000", None::<PaymentPreimage> },
19645
19646 { 1,
19647 "3045022100f960dfb1c9aee7ce1437efa65b523e399383e8149790e05d8fed27ff6e42fe0002202fe8613e062ffe0b0c518cc4101fba1c6de70f64a5bcc7ae663f2efae43b8546",
19648 "30450221009a6ed18e6873bc3644332a6ee21c152a5b102821865350df7a8c74451a51f9f2022050d801fb4895d7d7fbf452824c0168347f5c0cbe821cf6a97a63af5b8b2563c6",
19649 "02000000000101403ad7602b43293497a3a2235a12ecefda4f3a1f1d06e49b1786d945685de1ff010000000000000000015c060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100f960dfb1c9aee7ce1437efa65b523e399383e8149790e05d8fed27ff6e42fe0002202fe8613e062ffe0b0c518cc4101fba1c6de70f64a5bcc7ae663f2efae43b8546014830450221009a6ed18e6873bc3644332a6ee21c152a5b102821865350df7a8c74451a51f9f2022050d801fb4895d7d7fbf452824c0168347f5c0cbe821cf6a97a63af5b8b2563c601008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19650
19651 { 2,
19652 "3045022100ae5fc7717ae684bc1fcf9020854e5dbe9842c9e7472879ac06ff95ac2bb10e4e022057728ada4c00083a3e65493fb5d50a232165948a1a0f530ef63185c2c8c56504",
19653 "30440220408ad3009827a8fccf774cb285587686bfb2ed041f89a89453c311ce9c8ee0f902203c7392d9f8306d3a46522a66bd2723a7eb2628cb2d9b34d4c104f1766bf37502",
19654 "02000000000101403ad7602b43293497a3a2235a12ecefda4f3a1f1d06e49b1786d945685de1ff02000000000000000001f1090000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100ae5fc7717ae684bc1fcf9020854e5dbe9842c9e7472879ac06ff95ac2bb10e4e022057728ada4c00083a3e65493fb5d50a232165948a1a0f530ef63185c2c8c56504014730440220408ad3009827a8fccf774cb285587686bfb2ed041f89a89453c311ce9c8ee0f902203c7392d9f8306d3a46522a66bd2723a7eb2628cb2d9b34d4c104f1766bf37502012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19655 } );
19656
19657 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 2194;
19660
19661 test_commitment!("304402204bb3d6e279d71d9da414c82de42f1f954267c762b2e2eb8b76bc3be4ea07d4b0022014febc009c5edc8c3fc5d94015de163200f780046f1c293bfed8568f08b70fb3",
19662 "3044022072c2e2b1c899b2242656a537dde2892fa3801be0d6df0a87836c550137acde8302201654aa1974d37a829083c3ba15088689f30b56d6a4f6cb14c7bad0ee3116d398",
19663 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8005d007000000000000220020403d394747cae42e98ff01734ad5c08f82ba123d3d9a620abda88989651e2ab5b80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e48440966a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022072c2e2b1c899b2242656a537dde2892fa3801be0d6df0a87836c550137acde8302201654aa1974d37a829083c3ba15088689f30b56d6a4f6cb14c7bad0ee3116d3980147304402204bb3d6e279d71d9da414c82de42f1f954267c762b2e2eb8b76bc3be4ea07d4b0022014febc009c5edc8c3fc5d94015de163200f780046f1c293bfed8568f08b70fb301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19664
19665 { 0,
19666 "3045022100939726680351a7856c1bc386d4a1f422c7d29bd7b56afc139570f508474e6c40022023175a799ccf44c017fbaadb924c40b2a12115a5b7d0dfd3228df803a2de8450",
19667 "304502210099c98c2edeeee6ec0fb5f3bea8b79bb016a2717afa9b5072370f34382de281d302206f5e2980a995e045cf90a547f0752a7ee99d48547bc135258fe7bc07e0154301",
19668 "02000000000101153cd825fdb3aa624bfe513e8031d5d08c5e582fb3d1d1fe8faf27d3eed410cd0000000000000000000122020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100939726680351a7856c1bc386d4a1f422c7d29bd7b56afc139570f508474e6c40022023175a799ccf44c017fbaadb924c40b2a12115a5b7d0dfd3228df803a2de84500148304502210099c98c2edeeee6ec0fb5f3bea8b79bb016a2717afa9b5072370f34382de281d302206f5e2980a995e045cf90a547f0752a7ee99d48547bc135258fe7bc07e015430101008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a914b43e1b38138a41b37f7cd9a1d274bc63e3a9b5d188ac6868f6010000", None::<PaymentPreimage> },
19669
19670 { 1,
19671 "3044022021bb883bf324553d085ba2e821cad80c28ef8b303dbead8f98e548783c02d1600220638f9ef2a9bba25869afc923f4b5dc38be3bb459f9efa5d869392d5f7779a4a0",
19672 "3045022100fd85bd7697b89c08ec12acc8ba89b23090637d83abd26ca37e01ae93e67c367302202b551fe69386116c47f984aab9c8dfd25d864dcde5d3389cfbef2447a85c4b77",
19673 "02000000000101153cd825fdb3aa624bfe513e8031d5d08c5e582fb3d1d1fe8faf27d3eed410cd010000000000000000010a060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022021bb883bf324553d085ba2e821cad80c28ef8b303dbead8f98e548783c02d1600220638f9ef2a9bba25869afc923f4b5dc38be3bb459f9efa5d869392d5f7779a4a001483045022100fd85bd7697b89c08ec12acc8ba89b23090637d83abd26ca37e01ae93e67c367302202b551fe69386116c47f984aab9c8dfd25d864dcde5d3389cfbef2447a85c4b7701008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19674
19675 { 2,
19676 "3045022100c9e6f0454aa598b905a35e641a70cc9f67b5f38cc4b00843a041238c4a9f1c4a0220260a2822a62da97e44583e837245995ca2e36781769c52f19e498efbdcca262b",
19677 "30450221008a9f2ea24cd455c2b64c1472a5fa83865b0a5f49a62b661801e884cf2849af8302204d44180e50bf6adfcf1c1e581d75af91aba4e28681ce4a5ee5f3cbf65eca10f3",
19678 "02000000000101153cd825fdb3aa624bfe513e8031d5d08c5e582fb3d1d1fe8faf27d3eed410cd020000000000000000019a090000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100c9e6f0454aa598b905a35e641a70cc9f67b5f38cc4b00843a041238c4a9f1c4a0220260a2822a62da97e44583e837245995ca2e36781769c52f19e498efbdcca262b014830450221008a9f2ea24cd455c2b64c1472a5fa83865b0a5f49a62b661801e884cf2849af8302204d44180e50bf6adfcf1c1e581d75af91aba4e28681ce4a5ee5f3cbf65eca10f3012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19679 } );
19680
19681 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 2195;
19684
19685 test_commitment!("304402201a8c1b1f9671cd9e46c7323a104d7047cc48d3ee80d40d4512e0c72b8dc65666022066d7f9a2ce18c9eb22d2739ffcce05721c767f9b607622a31b6ea5793ddce403",
19686 "3044022044d592025b610c0d678f65032e87035cdfe89d1598c522cc32524ae8172417c30220749fef9d5b2ae8cdd91ece442ba8809bc891efedae2291e578475f97715d1767",
19687 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8004b80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484b8976a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022044d592025b610c0d678f65032e87035cdfe89d1598c522cc32524ae8172417c30220749fef9d5b2ae8cdd91ece442ba8809bc891efedae2291e578475f97715d17670147304402201a8c1b1f9671cd9e46c7323a104d7047cc48d3ee80d40d4512e0c72b8dc65666022066d7f9a2ce18c9eb22d2739ffcce05721c767f9b607622a31b6ea5793ddce40301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19688
19689 { 0,
19690 "3045022100e57b845066a06ee7c2cbfc29eabffe52daa9bf6f6de760066d04df9f9b250e0002202ffb197f0e6e0a77a75a9aff27014bd3de83b7f748d7efef986abe655e1dd50e",
19691 "3045022100ecc8c6529d0b2316d046f0f0757c1e1c25a636db168ec4f3aa1b9278df685dc0022067ae6b65e936f1337091f7b18a15935b608c5f2cdddb2f892ed0babfdd376d76",
19692 "020000000001018130a10f09b13677ba2885a8bca32860f3a952e5912b829a473639b5a2c07b900000000000000000000109060000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100e57b845066a06ee7c2cbfc29eabffe52daa9bf6f6de760066d04df9f9b250e0002202ffb197f0e6e0a77a75a9aff27014bd3de83b7f748d7efef986abe655e1dd50e01483045022100ecc8c6529d0b2316d046f0f0757c1e1c25a636db168ec4f3aa1b9278df685dc0022067ae6b65e936f1337091f7b18a15935b608c5f2cdddb2f892ed0babfdd376d7601008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage>},
19693
19694 { 1,
19695 "3045022100d193b7ecccad8057571620a0b1ffa6c48e9483311723b59cf536043b20bc51550220546d4bd37b3b101ecda14f6c907af46ec391abce1cd9c7ce22b1a62b534f2f2a",
19696 "3044022014d66f11f9cacf923807eba49542076c5fe5cccf252fb08fe98c78ef3ca6ab5402201b290dbe043cc512d9d78de074a5a129b8759bc6a6c546b190d120b690bd6e82",
19697 "020000000001018130a10f09b13677ba2885a8bca32860f3a952e5912b829a473639b5a2c07b900100000000000000000199090000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100d193b7ecccad8057571620a0b1ffa6c48e9483311723b59cf536043b20bc51550220546d4bd37b3b101ecda14f6c907af46ec391abce1cd9c7ce22b1a62b534f2f2a01473044022014d66f11f9cacf923807eba49542076c5fe5cccf252fb08fe98c78ef3ca6ab5402201b290dbe043cc512d9d78de074a5a129b8759bc6a6c546b190d120b690bd6e82012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19698 } );
19699
19700 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 2185;
19703 chan.context.holder_dust_limit_satoshis = 2001;
19704 let cached_channel_type = chan.funding.get_channel_type().clone();
19705 chan.funding.channel_transaction_parameters.channel_type_features =
19706 ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
19707
19708 test_commitment_with_anchors!("3044022040f63a16148cf35c8d3d41827f5ae7f7c3746885bb64d4d1b895892a83812b3e02202fcf95c2bf02c466163b3fa3ced6a24926fbb4035095a96842ef516e86ba54c0",
19709 "3045022100cd8479cfe1edb1e5a1d487391e0451a469c7171e51e680183f19eb4321f20e9b02204eab7d5a6384b1b08e03baa6e4d9748dfd2b5ab2bae7e39604a0d0055bbffdd5",
19710 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80064a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994b80b000000000000220020f96d0334feb64a4f40eb272031d07afcb038db56aa57446d60308c9f8ccadef9a00f000000000000220020ce6e751274836ff59622a0d1e07f8831d80bd6730bd48581398bfadd2bb8da9ac0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994ac5916a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100cd8479cfe1edb1e5a1d487391e0451a469c7171e51e680183f19eb4321f20e9b02204eab7d5a6384b1b08e03baa6e4d9748dfd2b5ab2bae7e39604a0d0055bbffdd501473044022040f63a16148cf35c8d3d41827f5ae7f7c3746885bb64d4d1b895892a83812b3e02202fcf95c2bf02c466163b3fa3ced6a24926fbb4035095a96842ef516e86ba54c001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19711
19712 { 0,
19713 "304402206870514a72ad6e723ff7f1e0370d7a33c1cd2a0b9272674143ebaf6a1d02dee102205bd953c34faf5e7322e9a1c0103581cb090280fda4f1039ee8552668afa90ebb",
19714 "30440220669de9ca7910eff65a7773ebd14a9fc371fe88cde5b8e2a81609d85c87ac939b02201ac29472fa4067322e92d75b624942d60be5050139b20bb363db75be79eb946f",
19715 "02000000000101ac13a7715f80b8e52dda43c6929cade5521bdced3a405da02b443f1ffb1e33cc02000000000100000001b80b0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402206870514a72ad6e723ff7f1e0370d7a33c1cd2a0b9272674143ebaf6a1d02dee102205bd953c34faf5e7322e9a1c0103581cb090280fda4f1039ee8552668afa90ebb834730440220669de9ca7910eff65a7773ebd14a9fc371fe88cde5b8e2a81609d85c87ac939b02201ac29472fa4067322e92d75b624942d60be5050139b20bb363db75be79eb946f01008876a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6851b27568f7010000", None::<PaymentPreimage> },
19716
19717 { 1,
19718 "3045022100949e8dd938da56445b1cdfdebe1b7efea086edd05d89910d205a1e2e033ce47102202cbd68b5262ab144d9ec12653f87dfb0bb6bd05d1f58ae1e523f028eaefd7271",
19719 "3045022100e3104ed8b239f8019e5f0a1a73d7782a94a8c36e7984f476c3a0b3cb0e62e27902207e3d52884600985f8a2098e53a5c30dd6a5e857733acfaa07ab2162421ed2688",
19720 "02000000000101ac13a7715f80b8e52dda43c6929cade5521bdced3a405da02b443f1ffb1e33cc03000000000100000001a00f0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100949e8dd938da56445b1cdfdebe1b7efea086edd05d89910d205a1e2e033ce47102202cbd68b5262ab144d9ec12653f87dfb0bb6bd05d1f58ae1e523f028eaefd727183483045022100e3104ed8b239f8019e5f0a1a73d7782a94a8c36e7984f476c3a0b3cb0e62e27902207e3d52884600985f8a2098e53a5c30dd6a5e857733acfaa07ab2162421ed2688012004040404040404040404040404040404040404040404040404040404040404048d76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac6851b2756800000000", Some(payment_preimage_4) }
19721 } );
19722
19723 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 3702;
19726 chan.context.holder_dust_limit_satoshis = 546;
19727 chan.funding.channel_transaction_parameters.channel_type_features =
19728 cached_channel_type.clone();
19729
19730 test_commitment!("304502210092a587aeb777f869e7ff0d7898ea619ee26a3dacd1f3672b945eea600be431100220077ee9eae3528d15251f2a52b607b189820e57a6ccfac8d1af502b132ee40169",
19731 "3045022100e5efb73c32d32da2d79702299b6317de6fb24a60476e3855926d78484dd1b3c802203557cb66a42c944ef06e00bcc4da35a5bcb2f185aab0f8e403e519e1d66aaf75",
19732 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8004b80b000000000000220020c20b5d1f8584fd90443e7b7b720136174fa4b9333c261d04dbbd012635c0f419a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e4846f916a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100e5efb73c32d32da2d79702299b6317de6fb24a60476e3855926d78484dd1b3c802203557cb66a42c944ef06e00bcc4da35a5bcb2f185aab0f8e403e519e1d66aaf750148304502210092a587aeb777f869e7ff0d7898ea619ee26a3dacd1f3672b945eea600be431100220077ee9eae3528d15251f2a52b607b189820e57a6ccfac8d1af502b132ee4016901475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19733
19734 { 0,
19735 "304402206fa54c11f98c3bae1e93df43fc7affeb05b476bf8060c03e29c377c69bc08e8b0220672701cce50d5c379ff45a5d2cfe48ac44973adb066ac32608e21221d869bb89",
19736 "304402206e36c683ebf2cb16bcef3d5439cf8b53cd97280a365ed8acd7abb85a8ba5f21c02206e8621edfc2a5766cbc96eb67fd501127ff163eb6b85518a39f7d4974aef126f",
19737 "020000000001018db483bff65c70ee71d8282aeec5a880e2e2b39e45772bda5460403095c62e3f0000000000000000000122020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402206fa54c11f98c3bae1e93df43fc7affeb05b476bf8060c03e29c377c69bc08e8b0220672701cce50d5c379ff45a5d2cfe48ac44973adb066ac32608e21221d869bb890147304402206e36c683ebf2cb16bcef3d5439cf8b53cd97280a365ed8acd7abb85a8ba5f21c02206e8621edfc2a5766cbc96eb67fd501127ff163eb6b85518a39f7d4974aef126f01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9148a486ff2e31d6158bf39e2608864d63fefd09d5b88ac6868f7010000", None::<PaymentPreimage> },
19738
19739 { 1,
19740 "3044022057649739b0eb74d541ead0dfdb3d4b2c15aa192720031044c3434c67812e5ca902201e5ede42d960ae551707f4a6b34b09393cf4dee2418507daa022e3550dbb5817",
19741 "304402207faad26678c8850e01b4a0696d60841f7305e1832b786110ee9075cb92ed14a30220516ef8ee5dfa80824ea28cbcec0dd95f8b847146257c16960db98507db15ffdc",
19742 "020000000001018db483bff65c70ee71d8282aeec5a880e2e2b39e45772bda5460403095c62e3f0100000000000000000176050000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022057649739b0eb74d541ead0dfdb3d4b2c15aa192720031044c3434c67812e5ca902201e5ede42d960ae551707f4a6b34b09393cf4dee2418507daa022e3550dbb58170147304402207faad26678c8850e01b4a0696d60841f7305e1832b786110ee9075cb92ed14a30220516ef8ee5dfa80824ea28cbcec0dd95f8b847146257c16960db98507db15ffdc012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19743 } );
19744
19745 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 3703;
19748
19749 test_commitment!("3045022100b495d239772a237ff2cf354b1b11be152fd852704cb184e7356d13f2fb1e5e430220723db5cdb9cbd6ead7bfd3deb419cf41053a932418cbb22a67b581f40bc1f13e",
19750 "304402201b736d1773a124c745586217a75bed5f66c05716fbe8c7db4fdb3c3069741cdd02205083f39c321c1bcadfc8d97e3c791a66273d936abac0c6a2fde2ed46019508e1",
19751 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8003a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484eb936a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e040047304402201b736d1773a124c745586217a75bed5f66c05716fbe8c7db4fdb3c3069741cdd02205083f39c321c1bcadfc8d97e3c791a66273d936abac0c6a2fde2ed46019508e101483045022100b495d239772a237ff2cf354b1b11be152fd852704cb184e7356d13f2fb1e5e430220723db5cdb9cbd6ead7bfd3deb419cf41053a932418cbb22a67b581f40bc1f13e01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19752
19753 { 0,
19754 "3045022100c34c61735f93f2e324cc873c3b248111ccf8f6db15d5969583757010d4ad2b4602207867bb919b2ddd6387873e425345c9b7fd18d1d66aba41f3607bc2896ef3c30a",
19755 "3045022100988c143e2110067117d2321bdd4bd16ca1734c98b29290d129384af0962b634e02206c1b02478878c5f547018b833986578f90c3e9be669fe5788ad0072a55acbb05",
19756 "0200000000010120060e4a29579d429f0f27c17ee5f1ee282f20d706d6f90b63d35946d8f3029a0000000000000000000175050000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100c34c61735f93f2e324cc873c3b248111ccf8f6db15d5969583757010d4ad2b4602207867bb919b2ddd6387873e425345c9b7fd18d1d66aba41f3607bc2896ef3c30a01483045022100988c143e2110067117d2321bdd4bd16ca1734c98b29290d129384af0962b634e02206c1b02478878c5f547018b833986578f90c3e9be669fe5788ad0072a55acbb05012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19757 } );
19758
19759 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 3687;
19762 chan.context.holder_dust_limit_satoshis = 3001;
19763 chan.funding.channel_transaction_parameters.channel_type_features =
19764 ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
19765
19766 test_commitment_with_anchors!("3045022100ad6c71569856b2d7ff42e838b4abe74a713426b37f22fa667a195a4c88908c6902202b37272b02a42dc6d9f4f82cab3eaf84ac882d9ed762859e1e75455c2c228377",
19767 "3045022100c970799bcb33f43179eb43b3378a0a61991cf2923f69b36ef12548c3df0e6d500220413dc27d2e39ee583093adfcb7799be680141738babb31cc7b0669a777a31f5d",
19768 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80054a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994a00f000000000000220020ce6e751274836ff59622a0d1e07f8831d80bd6730bd48581398bfadd2bb8da9ac0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994aa28b6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100c970799bcb33f43179eb43b3378a0a61991cf2923f69b36ef12548c3df0e6d500220413dc27d2e39ee583093adfcb7799be680141738babb31cc7b0669a777a31f5d01483045022100ad6c71569856b2d7ff42e838b4abe74a713426b37f22fa667a195a4c88908c6902202b37272b02a42dc6d9f4f82cab3eaf84ac882d9ed762859e1e75455c2c22837701475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19769
19770 { 0,
19771 "3044022017b558a3cf5f0cb94269e2e927b29ed22bd2416abb8a7ce6de4d1256f359b93602202e9ca2b1a23ea3e69f433c704e327739e219804b8c188b1d52f74fd5a9de954c",
19772 "3045022100af7a8b7c7ff2080c68995254cb66d64d9954edcc5baac3bb4f27ed2d29aaa6120220421c27da7a60574a9263f271e0f3bd34594ec6011095190022b3b54596ea03de",
19773 "02000000000101542562b326c08e3a076d9cfca2be175041366591da334d8d513ff1686fd95a6002000000000100000001a00f0000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500473044022017b558a3cf5f0cb94269e2e927b29ed22bd2416abb8a7ce6de4d1256f359b93602202e9ca2b1a23ea3e69f433c704e327739e219804b8c188b1d52f74fd5a9de954c83483045022100af7a8b7c7ff2080c68995254cb66d64d9954edcc5baac3bb4f27ed2d29aaa6120220421c27da7a60574a9263f271e0f3bd34594ec6011095190022b3b54596ea03de012004040404040404040404040404040404040404040404040404040404040404048d76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac6851b2756800000000", Some(payment_preimage_4) }
19774 } );
19775
19776 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 4914;
19779 chan.context.holder_dust_limit_satoshis = 546;
19780 chan.funding.channel_transaction_parameters.channel_type_features =
19781 cached_channel_type.clone();
19782
19783 test_commitment!("3045022100b4b16d5f8cc9fc4c1aff48831e832a0d8990e133978a66e302c133550954a44d022073573ce127e2200d316f6b612803a5c0c97b8d20e1e44dbe2ac0dd2fb8c95244",
19784 "3045022100d72638bc6308b88bb6d45861aae83e5b9ff6e10986546e13bce769c70036e2620220320be7c6d66d22f30b9fcd52af66531505b1310ca3b848c19285b38d8a1a8c19",
19785 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8003a00f0000000000002200208c48d15160397c9731df9bc3b236656efb6665fbfe92b4a6878e88a499f741c4c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484ae8f6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100d72638bc6308b88bb6d45861aae83e5b9ff6e10986546e13bce769c70036e2620220320be7c6d66d22f30b9fcd52af66531505b1310ca3b848c19285b38d8a1a8c1901483045022100b4b16d5f8cc9fc4c1aff48831e832a0d8990e133978a66e302c133550954a44d022073573ce127e2200d316f6b612803a5c0c97b8d20e1e44dbe2ac0dd2fb8c9524401475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19786
19787 { 0,
19788 "3045022100f43591c156038ba217756006bb3c55f7d113a325cdd7d9303c82115372858d68022016355b5aadf222bc8d12e426c75f4a03423917b2443a103eb2a498a3a2234374",
19789 "30440220585dee80fafa264beac535c3c0bb5838ac348b156fdc982f86adc08dfc9bfd250220130abb82f9f295cc9ef423dcfef772fde2acd85d9df48cc538981d26a10a9c10",
19790 "02000000000101a9172908eace869cc35128c31fc2ab502f72e4dff31aab23e0244c4b04b11ab00000000000000000000122020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100f43591c156038ba217756006bb3c55f7d113a325cdd7d9303c82115372858d68022016355b5aadf222bc8d12e426c75f4a03423917b2443a103eb2a498a3a2234374014730440220585dee80fafa264beac535c3c0bb5838ac348b156fdc982f86adc08dfc9bfd250220130abb82f9f295cc9ef423dcfef772fde2acd85d9df48cc538981d26a10a9c10012004040404040404040404040404040404040404040404040404040404040404048a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a91418bc1a114ccf9c052d3d23e28d3b0a9d1227434288527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f801b175ac686800000000", Some(payment_preimage_4) }
19791 } );
19792
19793 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 4915;
19796 chan.context.holder_dust_limit_satoshis = 546;
19797
19798 test_commitment!("304402203a286936e74870ca1459c700c71202af0381910a6bfab687ef494ef1bc3e02c902202506c362d0e3bee15e802aa729bf378e051644648253513f1c085b264cc2a720",
19799 "30450221008a953551f4d67cb4df3037207fc082ddaf6be84d417b0bd14c80aab66f1b01a402207508796dc75034b2dee876fe01dc05a08b019f3e5d689ac8842ade2f1befccf5",
19800 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484fa926a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221008a953551f4d67cb4df3037207fc082ddaf6be84d417b0bd14c80aab66f1b01a402207508796dc75034b2dee876fe01dc05a08b019f3e5d689ac8842ade2f1befccf50147304402203a286936e74870ca1459c700c71202af0381910a6bfab687ef494ef1bc3e02c902202506c362d0e3bee15e802aa729bf378e051644648253513f1c085b264cc2a72001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19801
19802 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 4894;
19805 chan.context.holder_dust_limit_satoshis = 4001;
19806 chan.funding.channel_transaction_parameters.channel_type_features =
19807 ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
19808
19809 test_commitment_with_anchors!("3045022100e784a66b1588575801e237d35e510fd92a81ae3a4a2a1b90c031ad803d07b3f3022021bc5f16501f167607d63b681442da193eb0a76b4b7fd25c2ed4f8b28fd35b95",
19810 "30450221009f16ac85d232e4eddb3fcd750a68ebf0b58e3356eaada45d3513ede7e817bf4c02207c2b043b4e5f971261975406cb955219fa56bffe5d834a833694b5abc1ce4cfd",
19811 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80044a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994ad0886a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004830450221009f16ac85d232e4eddb3fcd750a68ebf0b58e3356eaada45d3513ede7e817bf4c02207c2b043b4e5f971261975406cb955219fa56bffe5d834a833694b5abc1ce4cfd01483045022100e784a66b1588575801e237d35e510fd92a81ae3a4a2a1b90c031ad803d07b3f3022021bc5f16501f167607d63b681442da193eb0a76b4b7fd25c2ed4f8b28fd35b9501475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19812
19813 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 9651180;
19816 chan.context.holder_dust_limit_satoshis = 546;
19817 chan.funding.channel_transaction_parameters.channel_type_features =
19818 cached_channel_type.clone();
19819
19820 test_commitment!("304402200a8544eba1d216f5c5e530597665fa9bec56943c0f66d98fc3d028df52d84f7002201e45fa5c6bc3a506cc2553e7d1c0043a9811313fc39c954692c0d47cfce2bbd3",
19821 "3045022100e11b638c05c650c2f63a421d36ef8756c5ce82f2184278643520311cdf50aa200220259565fb9c8e4a87ccaf17f27a3b9ca4f20625754a0920d9c6c239d8156a11de",
19822 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b800222020000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80ec0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e4840400483045022100e11b638c05c650c2f63a421d36ef8756c5ce82f2184278643520311cdf50aa200220259565fb9c8e4a87ccaf17f27a3b9ca4f20625754a0920d9c6c239d8156a11de0147304402200a8544eba1d216f5c5e530597665fa9bec56943c0f66d98fc3d028df52d84f7002201e45fa5c6bc3a506cc2553e7d1c0043a9811313fc39c954692c0d47cfce2bbd301475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19823
19824 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 9651181;
19827
19828 test_commitment!("304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2",
19829 "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379",
19830 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19831
19832 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 6216010;
19835 chan.context.holder_dust_limit_satoshis = 4001;
19836 chan.funding.channel_transaction_parameters.channel_type_features =
19837 ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
19838
19839 test_commitment_with_anchors!("30450221008fd5dbff02e4b59020d4cd23a3c30d3e287065fda75a0a09b402980adf68ccda022001e0b8b620cd915ddff11f1de32addf23d81d51b90e6841b2cb8dcaf3faa5ecf",
19840 "30450221009ad80792e3038fe6968d12ff23e6888a565c3ddd065037f357445f01675d63f3022018384915e5f1f4ae157e15debf4f49b61c8d9d2b073c7d6f97c4a68caa3ed4c1",
19841 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994a04004830450221009ad80792e3038fe6968d12ff23e6888a565c3ddd065037f357445f01675d63f3022018384915e5f1f4ae157e15debf4f49b61c8d9d2b073c7d6f97c4a68caa3ed4c1014830450221008fd5dbff02e4b59020d4cd23a3c30d3e287065fda75a0a09b402980adf68ccda022001e0b8b620cd915ddff11f1de32addf23d81d51b90e6841b2cb8dcaf3faa5ecf01475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19842
19843 chan.funding.value_to_self_msat = 6993000000; chan.context.feerate_per_kw = 9651936;
19846 chan.context.holder_dust_limit_satoshis = 546;
19847 chan.funding.channel_transaction_parameters.channel_type_features = cached_channel_type;
19848
19849 test_commitment!("304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2",
19850 "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379",
19851 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19852
19853 chan.funding.value_to_self_msat = 7_000_000_000 - 2_000_000;
19855 chan.context.feerate_per_kw = 253;
19856 chan.context.pending_inbound_htlcs.clear();
19857 chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
19858 htlc_id: 1,
19859 amount_msat: 2000000,
19860 cltv_expiry: 501,
19861 payment_hash: PaymentHash::from(payment_preimage_1),
19862 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
19863 });
19864
19865 chan.context.pending_outbound_htlcs.clear();
19866 let payment_preimage_5 =
19867 preimage_from_hex("0505050505050505050505050505050505050505050505050505050505050505");
19868 chan.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
19869 htlc_id: 6,
19870 amount_msat: 5000001,
19871 cltv_expiry: 506,
19872 payment_hash: PaymentHash::from(payment_preimage_5),
19873 state: OutboundHTLCState::Committed,
19874 source: HTLCSource::dummy(),
19875 skimmed_fee_msat: None,
19876 blinding_point: None,
19877 send_timestamp: None,
19878 hold_htlc: None,
19879 accountable: false,
19880 });
19881
19882 chan.context.pending_outbound_htlcs.push(OutboundHTLCOutput {
19883 htlc_id: 5,
19884 amount_msat: 5000000,
19885 cltv_expiry: 505,
19886 payment_hash: PaymentHash::from(payment_preimage_5),
19887 state: OutboundHTLCState::Committed,
19888 source: HTLCSource::dummy(),
19889 skimmed_fee_msat: None,
19890 blinding_point: None,
19891 send_timestamp: None,
19892 hold_htlc: None,
19893 accountable: false,
19894 });
19895
19896 test_commitment!("304402207d0870964530f97b62497b11153c551dca0a1e226815ef0a336651158da0f82402200f5378beee0e77759147b8a0a284decd11bfd2bc55c8fafa41c134fe996d43c8",
19897 "304402200d10bf5bc5397fc59d7188ae438d80c77575595a2d488e41bd6363a810cc8d72022012b57e714fbbfdf7a28c47d5b370cb8ac37c8545f596216e5b21e9b236ef457c",
19898 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8005d007000000000000220020748eba944fedc8827f6b06bc44678f93c0f9e6078b35c6331ed31e75f8ce0c2d8813000000000000220020305c12e1a0bc21e283c131cea1c66d68857d28b7b2fce0a6fbc40c164852121b8813000000000000220020305c12e1a0bc21e283c131cea1c66d68857d28b7b2fce0a6fbc40c164852121bc0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484a69f6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e040047304402200d10bf5bc5397fc59d7188ae438d80c77575595a2d488e41bd6363a810cc8d72022012b57e714fbbfdf7a28c47d5b370cb8ac37c8545f596216e5b21e9b236ef457c0147304402207d0870964530f97b62497b11153c551dca0a1e226815ef0a336651158da0f82402200f5378beee0e77759147b8a0a284decd11bfd2bc55c8fafa41c134fe996d43c801475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19899
19900 { 0,
19901 "3045022100b470fe12e5b7fea9eccb8cbff1972cea4f96758041898982a02bcc7f9d56d50b0220338a75b2afaab4ec00cdd2d9273c68c7581ff5a28bcbb40c4d138b81f1d45ce5",
19902 "3044022017b90c65207522a907fb6a137f9dd528b3389465a8ae72308d9e1d564f512cf402204fc917b4f0e88604a3e994f85bfae7c7c1f9d9e9f78e8cd112e0889720d9405b",
19903 "020000000001014bdccf28653066a2c554cafeffdfe1e678e64a69b056684deb0c4fba909423ec000000000000000000011f070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100b470fe12e5b7fea9eccb8cbff1972cea4f96758041898982a02bcc7f9d56d50b0220338a75b2afaab4ec00cdd2d9273c68c7581ff5a28bcbb40c4d138b81f1d45ce501473044022017b90c65207522a907fb6a137f9dd528b3389465a8ae72308d9e1d564f512cf402204fc917b4f0e88604a3e994f85bfae7c7c1f9d9e9f78e8cd112e0889720d9405b012001010101010101010101010101010101010101010101010101010101010101018a76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac686800000000", Some(payment_preimage_1) },
19904 { 1,
19905 "3045022100b575379f6d8743cb0087648f81cfd82d17a97fbf8f67e058c65ce8b9d25df9500220554a210d65b02d9f36c6adf0f639430ca8293196ba5089bf67cc3a9813b7b00a",
19906 "3045022100ee2e16b90930a479b13f8823a7f14b600198c838161160b9436ed086d3fc57e002202a66fa2324f342a17129949c640bfe934cbc73a869ba7c06aa25c5a3d0bfb53d",
19907 "020000000001014bdccf28653066a2c554cafeffdfe1e678e64a69b056684deb0c4fba909423ec01000000000000000001e1120000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100b575379f6d8743cb0087648f81cfd82d17a97fbf8f67e058c65ce8b9d25df9500220554a210d65b02d9f36c6adf0f639430ca8293196ba5089bf67cc3a9813b7b00a01483045022100ee2e16b90930a479b13f8823a7f14b600198c838161160b9436ed086d3fc57e002202a66fa2324f342a17129949c640bfe934cbc73a869ba7c06aa25c5a3d0bfb53d01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9142002cc93ebefbb1b73f0af055dcc27a0b504ad7688ac6868f9010000", None::<PaymentPreimage> },
19908 { 2,
19909 "30440220471c9f3ad92e49b13b7b8059f43ecf8f7887b0dccbb9fdb54bfe23d62a8ae332022024bd22fae0740e86a44228c35330da9526fd7306dffb2b9dc362d5e78abef7cc",
19910 "304402207157f452f2506d73c315192311893800cfb3cc235cc1185b1cfcc136b55230db022014be242dbc6c5da141fec4034e7f387f74d6ff1899453d72ba957467540e1ecb",
19911 "020000000001014bdccf28653066a2c554cafeffdfe1e678e64a69b056684deb0c4fba909423ec02000000000000000001e1120000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220471c9f3ad92e49b13b7b8059f43ecf8f7887b0dccbb9fdb54bfe23d62a8ae332022024bd22fae0740e86a44228c35330da9526fd7306dffb2b9dc362d5e78abef7cc0147304402207157f452f2506d73c315192311893800cfb3cc235cc1185b1cfcc136b55230db022014be242dbc6c5da141fec4034e7f387f74d6ff1899453d72ba957467540e1ecb01008576a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9142002cc93ebefbb1b73f0af055dcc27a0b504ad7688ac6868fa010000", None::<PaymentPreimage> }
19912 } );
19913
19914 chan.funding.channel_transaction_parameters.channel_type_features =
19915 ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
19916 test_commitment_with_anchors!("3044022027b38dfb654c34032ffb70bb43022981652fce923cbbe3cbe7394e2ade8b34230220584195b78da6e25c2e8da6b4308d9db25b65b64975db9266163ef592abb7c725",
19917 "3045022100b4014970d9d7962853f3f85196144671d7d5d87426250f0a5fdaf9a55292e92502205360910c9abb397467e19dbd63d081deb4a3240903114c98cec0a23591b79b76",
19918 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80074a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f4a01000000000000220020e9e86e4823faa62e222ebc858a226636856158f07e69898da3b0d1af0ddb3994d007000000000000220020fe0598d74fee2205cc3672e6e6647706b4f3099713b4661b62482c3addd04a5e881300000000000022002018e40f9072c44350f134bdc887bab4d9bdfc8aa468a25616c80e21757ba5dac7881300000000000022002018e40f9072c44350f134bdc887bab4d9bdfc8aa468a25616c80e21757ba5dac7c0c62d0000000000220020f3394e1e619b0eca1f91be2fb5ab4dfc59ba5b84ebe014ad1d43a564d012994aad9c6a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400483045022100b4014970d9d7962853f3f85196144671d7d5d87426250f0a5fdaf9a55292e92502205360910c9abb397467e19dbd63d081deb4a3240903114c98cec0a23591b79b7601473044022027b38dfb654c34032ffb70bb43022981652fce923cbbe3cbe7394e2ade8b34230220584195b78da6e25c2e8da6b4308d9db25b65b64975db9266163ef592abb7c72501475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {
19919
19920 { 0,
19921 "30440220078fe5343dab88c348a3a8a9c1a9293259dbf35507ae971702cc39dd623ea9af022011ed0c0f35243cd0bb4d9ca3c772379b2b5f4af93140e9fdc5600dfec1cdb0c2",
19922 "304402205df665e2908c7690d2d33eb70e6e119958c28febe141a94ed0dd9a55ce7c8cfc0220364d02663a5d019af35c5cd5fda9465d985d85bbd12db207738d61163449a424",
19923 "020000000001013d060d0305c9616eaabc21d41fae85bcb5477b5d7f1c92aa429cf15339bbe1c402000000000100000001d0070000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e05004730440220078fe5343dab88c348a3a8a9c1a9293259dbf35507ae971702cc39dd623ea9af022011ed0c0f35243cd0bb4d9ca3c772379b2b5f4af93140e9fdc5600dfec1cdb0c28347304402205df665e2908c7690d2d33eb70e6e119958c28febe141a94ed0dd9a55ce7c8cfc0220364d02663a5d019af35c5cd5fda9465d985d85bbd12db207738d61163449a424012001010101010101010101010101010101010101010101010101010101010101018d76a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c8201208763a9144b6b2e5444c2639cc0fb7bcea5afba3f3cdce23988527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae677502f501b175ac6851b2756800000000", Some(payment_preimage_1) },
19924 { 1,
19925 "304402202df6bf0f98a42cfd0172a16bded7d1b16c14f5f42ba23f5c54648c14b647531302200fe1508626817f23925bb56951d5e4b2654c751743ab6db48a6cce7dda17c01c",
19926 "304402203f99ec05cdd89558a23683b471c1dcce8f6a92295f1fff3b0b5d21be4d4f97ea022019d29070690fc2c126fe27cc4ab2f503f289d362721b2efa7418e7fddb939a5b",
19927 "020000000001013d060d0305c9616eaabc21d41fae85bcb5477b5d7f1c92aa429cf15339bbe1c40300000000010000000188130000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e050047304402202df6bf0f98a42cfd0172a16bded7d1b16c14f5f42ba23f5c54648c14b647531302200fe1508626817f23925bb56951d5e4b2654c751743ab6db48a6cce7dda17c01c8347304402203f99ec05cdd89558a23683b471c1dcce8f6a92295f1fff3b0b5d21be4d4f97ea022019d29070690fc2c126fe27cc4ab2f503f289d362721b2efa7418e7fddb939a5b01008876a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9142002cc93ebefbb1b73f0af055dcc27a0b504ad7688ac6851b27568f9010000", None::<PaymentPreimage> },
19928 { 2,
19929 "3045022100bd206b420c495f3aa714d3ea4766cbe95441deacb5d2f737f1913349aee7c2ae02200249d2c950dd3b15326bf378ae5d2b871d33d6737f5d70735f3de8383140f2a1",
19930 "3045022100f2cd35e385b9b7e15b92a5d78d120b6b2c5af4e974bc01e884c5facb3bb5966c0220706e0506477ce809a40022d6de8e041e9ef13136c45abee9c36f58a01fdb188b",
19931 "020000000001013d060d0305c9616eaabc21d41fae85bcb5477b5d7f1c92aa429cf15339bbe1c40400000000010000000188130000000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0500483045022100bd206b420c495f3aa714d3ea4766cbe95441deacb5d2f737f1913349aee7c2ae02200249d2c950dd3b15326bf378ae5d2b871d33d6737f5d70735f3de8383140f2a183483045022100f2cd35e385b9b7e15b92a5d78d120b6b2c5af4e974bc01e884c5facb3bb5966c0220706e0506477ce809a40022d6de8e041e9ef13136c45abee9c36f58a01fdb188b01008876a91414011f7254d96b819c76986c277d115efce6f7b58763ac67210394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b7c820120876475527c21030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e752ae67a9142002cc93ebefbb1b73f0af055dcc27a0b504ad7688ac6851b27568fa010000", None::<PaymentPreimage> }
19932 } );
19933 }
19934
19935 #[cfg(ldk_test_vectors)]
19937 #[test]
19938 fn zero_fee_commitment_test_vectors() {
19939 use crate::chain::transaction::OutPoint;
19940 use crate::ln::chan_utils::{
19941 CounterpartyChannelTransactionParameters, HolderCommitmentTransaction,
19942 };
19943 use crate::ln::channel::HTLCOutputInCommitment;
19944 use crate::sign::{ecdsa::EcdsaChannelSigner, ChannelDerivationParameters, HTLCDescriptor};
19945 use crate::sync::Arc;
19946 use crate::types::features::ChannelTypeFeatures;
19947 use crate::types::payment::PaymentPreimage;
19948 use crate::util::config::UserConfig;
19949 use crate::util::logger::Logger;
19950 use crate::util::test_utils::{
19951 payment_hash_from_hex, preimage_from_hex, pubkey_from_hex, secret_from_hex,
19952 };
19953 use bitcoin::consensus::encode::serialize;
19954 use bitcoin::hash_types::Txid;
19955 use bitcoin::hex::{DisplayHex, FromHex};
19956 use bitcoin::secp256k1::{Message, Secp256k1};
19957 use bitcoin::sighash;
19958 use bitcoin::sighash::EcdsaSighashType;
19959 use core::str::FromStr;
19960
19961 let feeest = TestFeeEstimator::new(250); let logger: Arc<dyn Logger> = Arc::new(TestLogger::new());
19963 let secp_ctx = Secp256k1::new();
19964
19965 let alice_funding_privkey =
19966 secret_from_hex("8f567cb6382507019349a47623902aa65d7a142ac85462eeb63dc11799ac2bb9");
19967 let alice_payment_basepoint_secret =
19968 secret_from_hex("94f29d20a225ea2f7093331ba0f0f28a9382d8ed08e1fd121329925cd0c01b6d");
19969 let alice_delayed_payment_basepoint_secret =
19970 secret_from_hex("e9d4e1935bf16e948d76ad007baf0646df023af38f41bcf2c8799336949d291e");
19971 let alice_htlc_basepoint_secret =
19972 secret_from_hex("f699038ef4f95b6b16b22a5c04fcb3c508d68d02cd2f86cf197e0fac451681b0");
19973 let alice_revocation_base_secret =
19975 secret_from_hex("1111111111111111111111111111111111111111111111111111111111111111");
19976
19977 let alice_signer = InMemorySigner::new(
19978 alice_funding_privkey,
19979 alice_revocation_base_secret,
19980 alice_payment_basepoint_secret,
19981 alice_payment_basepoint_secret,
19982 true,
19983 alice_delayed_payment_basepoint_secret,
19984 alice_htlc_basepoint_secret,
19985 [0xff; 32],
19987 [0; 32],
19988 [0; 32],
19989 );
19990 let alice_keys_provider = Keys { signer: alice_signer.clone() };
19991 let alice_pubkeys = alice_signer.pubkeys(&secp_ctx);
19992
19993 let bob_funding_privkey =
19994 secret_from_hex("4d22d96f0c0ccecffee4554d20ed43e51235917508ee292d281235bb7ebe0e3e");
19995 let bob_payment_basepoint_secret =
19996 secret_from_hex("580bff39085f3a6ae8b1f32905e67366c522ea8f2418391145b2e98f1a7cb3f2");
19997 let bob_htlc_basepoint_secret =
19998 secret_from_hex("32df9c4dd46ab6210e74e81e15282106f8db883f45674eabb3324166c6513062");
19999 let bob_revocation_base_secret =
20000 secret_from_hex("2222222222222222222222222222222222222222222222222222222222222222");
20001 let bob_delayed_payment_basepoint_secret =
20002 secret_from_hex("2222222222222222222222222222222222222222222222222222222222222222");
20003
20004 let bob_signer = InMemorySigner::new(
20005 bob_funding_privkey,
20006 bob_revocation_base_secret,
20007 bob_payment_basepoint_secret,
20008 bob_payment_basepoint_secret,
20009 true,
20010 bob_delayed_payment_basepoint_secret,
20011 bob_htlc_basepoint_secret,
20012 [0xff; 32],
20014 [0; 32],
20015 [0; 32],
20016 );
20017
20018 let mut bob_pubkeys = bob_signer.pubkeys(&secp_ctx);
20020 bob_pubkeys.revocation_basepoint = RevocationBasepoint(pubkey_from_hex(
20021 "026788d019ed90149cbc9aa5ff26dd7f1a6d3cd1bee8bf36cf7d8310fbd3606b14",
20022 ));
20023
20024 let bob_node_id = crate::util::test_utils::pubkey(2);
20026 let mut config = UserConfig::default();
20027 config.channel_handshake_config.negotiate_anchor_zero_fee_commitments = true;
20028
20029 let mut chan = OutboundV1Channel::<&Keys>::new(
20030 &LowerBoundedFeeEstimator::new(&feeest),
20031 &&alice_keys_provider,
20032 &&alice_keys_provider,
20033 bob_node_id,
20034 &crate::ln::channelmanager::provided_init_features(&config),
20035 10_000_000,
20036 0,
20037 0,
20038 &config,
20039 0,
20040 0,
20041 None,
20042 &*logger,
20043 None,
20044 )
20045 .unwrap();
20046
20047 chan.funding.counterparty_selected_channel_reserve_satoshis = Some(0);
20048 chan.funding.holder_selected_channel_reserve_satoshis = 0;
20049
20050 let funding_txid_str = "4b70a2ee47b3005a6316ff87055e94c6b3d433d0fd3b384c9ecf7813843c1eae";
20051 let funding_info = OutPoint { txid: Txid::from_str(funding_txid_str).unwrap(), index: 1 };
20052
20053 chan.funding.channel_transaction_parameters.holder_pubkeys = alice_pubkeys.clone();
20055 chan.funding.channel_transaction_parameters.counterparty_parameters =
20056 Some(CounterpartyChannelTransactionParameters {
20057 pubkeys: bob_pubkeys.clone(),
20058 selected_contest_delay: 720,
20059 });
20060 chan.funding.channel_transaction_parameters.funding_outpoint = Some(funding_info);
20061 chan.funding.channel_transaction_parameters.channel_type_features =
20062 ChannelTypeFeatures::anchors_zero_fee_commitments();
20063
20064 let per_commitment_point =
20065 pubkey_from_hex("0275d12130c276b4274358a328901f8fc47e6c72629102e4b46c9f27dd2c1dda98");
20066
20067 macro_rules! test_commitment_with_zero_fee {
20068 ( $counterparty_sig_hex: expr, $sig_hex: expr, $tx_hex: expr, $($remain:tt)* ) => {
20069 chan.funding.channel_transaction_parameters.channel_type_features = ChannelTypeFeatures::anchors_zero_fee_commitments();
20070 test_commitment_common!(chan, logger, secp_ctx, alice_signer, alice_pubkeys, per_commitment_point,
20071 $counterparty_sig_hex, $sig_hex, $tx_hex, &ChannelTypeFeatures::anchors_zero_fee_commitments(), $($remain)*);
20072 };
20073 }
20074
20075 chan.funding.value_to_self_msat = 8000000000;
20077 test_commitment_with_zero_fee!(
20078 "3045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e",
20079 "304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb82162",
20080 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800300000000000000000451024e7380841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea00127a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e0148304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb8216201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20081
20082 chan.context.holder_dust_limit_satoshis = 330;
20084 chan.funding.value_to_self_msat = 9999800000;
20085 test_commitment_with_zero_fee!(
20086 "3045022100a13c79500a9b30eba7af13418816b54aea1da0bdf41c0aa10f53a29017080d5602201a11bcc10f99c4334f778ea94e83db63d2409ff10e9e95b4260ac0dba27a490f",
20087 "30440220706abbc90e9ab70a7e1f0f28b24baf2f105e49b7a41bf3b5e694f060806fc54402206020a5e51e437c027610a59f0252ac075dfb2b8e5b45f49149e9532935ba5e7a",
20088 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8002c8000000000000000451024e73b895980000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a13c79500a9b30eba7af13418816b54aea1da0bdf41c0aa10f53a29017080d5602201a11bcc10f99c4334f778ea94e83db63d2409ff10e9e95b4260ac0dba27a490f014730440220706abbc90e9ab70a7e1f0f28b24baf2f105e49b7a41bf3b5e694f060806fc54402206020a5e51e437c027610a59f0252ac075dfb2b8e5b45f49149e9532935ba5e7a01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20089
20090 chan.context.holder_dust_limit_satoshis = 15000;
20092 chan.funding.value_to_self_msat = 9990000000;
20093 test_commitment_with_zero_fee!(
20094 "304402204042ce57689bb7e52af7fb9ec28d6610674ce00e5e438bb1119acfb91aad6386022065de45c4fe52d86249d80397f2c85e143550cb14b3de0cd1e6a54d0622a2bbd4",
20095 "30450221009fb4e444e9fe2d7db0f867704745c8ea2e4e1018b5986fd8cb9d9facdc1bb1be02202d6589a20ea8a8e3594eac3c99bad523139a36e313a66c6302e619786cb42396",
20096 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8002f0000000000000000451024e73706f980000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402204042ce57689bb7e52af7fb9ec28d6610674ce00e5e438bb1119acfb91aad6386022065de45c4fe52d86249d80397f2c85e143550cb14b3de0cd1e6a54d0622a2bbd4014830450221009fb4e444e9fe2d7db0f867704745c8ea2e4e1018b5986fd8cb9d9facdc1bb1be02202d6589a20ea8a8e3594eac3c99bad523139a36e313a66c6302e619786cb4239601475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20097
20098 chan.context.holder_dust_limit_satoshis = 5000;
20100 chan.funding.value_to_self_msat = 8000000000;
20101
20102 let htlc_in_preimage =
20103 preimage_from_hex("108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa");
20104 assert_eq!(
20105 payment_hash_from_hex(
20106 "23877c9093799487a8d49c7d6aaff7e06b9831c547400605252e7b07f7ae638a",
20107 ),
20108 PaymentHash::from(htlc_in_preimage),
20109 );
20110 chan.context.pending_inbound_htlcs.extend([1, 2, 5].map(|id| InboundHTLCOutput {
20111 htlc_id: id,
20112 amount_msat: 5000000,
20113 cltv_expiry: 920150,
20114 payment_hash: PaymentHash::from(htlc_in_preimage),
20115 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20116 }));
20117
20118 chan.context.pending_outbound_htlcs.extend(
20119 [
20120 (5, "72c9386ba5a9d97b821d855930236d39c48dab5b1c2efe9ada44e2fbadcff983"),
20121 (8, "10b879729e8ddd44f2cfcf3cad6d62be535ca74e293c5ed4a59bd0dcbdad7ca1"),
20122 (13, "72c9386ba5a9d97b821d855930236d39c48dab5b1c2efe9ada44e2fbadcff983"),
20123 ]
20124 .map(|(htlc_id, hash_str)| OutboundHTLCOutput {
20125 htlc_id,
20126 amount_msat: 25000000,
20127 cltv_expiry: 920141,
20128 payment_hash: payment_hash_from_hex(hash_str),
20129 state: OutboundHTLCState::Committed,
20130 source: HTLCSource::dummy(),
20131 skimmed_fee_msat: None,
20132 blinding_point: None,
20133 send_timestamp: None,
20134 hold_htlc: None,
20135 accountable: false,
20136 }),
20137 );
20138
20139 test_commitment_with_zero_fee!(
20140 "30450221008e951c6305b8d661de280234019d664d7a706b6dc22c23f5488b6b141480d1c202207975f2c477d6fb26ac51b9aa81c1d2b35bb724cebbf21a63e5d7ef3d6e273baf",
20141 "3045022100ea978743401f2834d516ea434c0396c919e22465b4d2e359e61e6783535a89b30220475e2dbcc204016472b8eb9437e237a26ca102c1aa16812baa7ae522cc6291e8",
20142 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800900000000000000000451024e73881300000000000022002075254560bb02c207015847abfda36d3a1b882e78c3f04b08325aac21c53989dc881300000000000022002075254560bb02c207015847abfda36d3a1b882e78c3f04b08325aac21c53989dc881300000000000022002075254560bb02c207015847abfda36d3a1b882e78c3f04b08325aac21c53989dca8610000000000002200200963a1f3e47b8d2a35664f70de49d3331b4499da201004868a9104271f0cd93ba8610000000000002200205b138be4da633f087be191275d3ce30828ae32d1630853fcbf66d22ca6fe2636a8610000000000002200205b138be4da633f087be191275d3ce30828ae32d1630853fcbf66d22ca6fe2636e8491e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea08ed780000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a04004830450221008e951c6305b8d661de280234019d664d7a706b6dc22c23f5488b6b141480d1c202207975f2c477d6fb26ac51b9aa81c1d2b35bb724cebbf21a63e5d7ef3d6e273baf01483045022100ea978743401f2834d516ea434c0396c919e22465b4d2e359e61e6783535a89b30220475e2dbcc204016472b8eb9437e237a26ca102c1aa16812baa7ae522cc6291e801475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {
20143 {0,
20144 "3045022100b82fff4e0652b305cc93f5f8e45362c55591c9ddb8e05a168c5df177ad8ff7ba022061827439423e660099d4c924257314656939b36180bf21b3a253bdd56f9f2b6b",
20145 "3044022024832648de0dc603b955b7b6a8ada64cc305affaf7357b018f481fb7e0c48c8d0220716568bee37589c5b67c941768fb10e10f48c1cc66b1128664455b99749a7c2a",
20146 "03000000000101c3b4fad51418c874498af12060d49477c154845040e3584104ae641c542c0135010000000000000000018813000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100b82fff4e0652b305cc93f5f8e45362c55591c9ddb8e05a168c5df177ad8ff7ba022061827439423e660099d4c924257314656939b36180bf21b3a253bdd56f9f2b6b83473044022024832648de0dc603b955b7b6a8ada64cc305affaf7357b018f481fb7e0c48c8d0220716568bee37589c5b67c941768fb10e10f48c1cc66b1128664455b99749a7c2a0120108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa8b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914f4c8e88504a23ed3e390ea80300c834f0eb79a6c88527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503560a0eb175ac686800000000", Some(htlc_in_preimage) },
20147 {1,
20148 "3045022100c25f58229c0f9f985ef85235877268aad5da9cdcbceeb4425e668c97df2bfc920220053bca5957e55cdaa0734ba9a1b7a3eb0bdeced1d4496196d9d9de8ff1b20d2e",
20149 "3045022100d2f99843a7b29ec1b5044d2dc99f118d25157cdfc07213975a3e0bbc57f22e0a022000ac6b2dab53f34877c376d074d433c599721ea58c113bb7d2b7a540abbaab79",
20150 "03000000000101c3b4fad51418c874498af12060d49477c154845040e3584104ae641c542c0135020000000000000000018813000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100c25f58229c0f9f985ef85235877268aad5da9cdcbceeb4425e668c97df2bfc920220053bca5957e55cdaa0734ba9a1b7a3eb0bdeced1d4496196d9d9de8ff1b20d2e83483045022100d2f99843a7b29ec1b5044d2dc99f118d25157cdfc07213975a3e0bbc57f22e0a022000ac6b2dab53f34877c376d074d433c599721ea58c113bb7d2b7a540abbaab790120108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa8b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914f4c8e88504a23ed3e390ea80300c834f0eb79a6c88527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503560a0eb175ac686800000000", Some(htlc_in_preimage) },
20151 {2,
20152 "3045022100948054ef219ec5af7494224f65ad6fab9cfd415d7260cb70a4719e99d421871f02205a41957a428b7820cef844c41cd06d8443f55953e000f4e40658175544a012ce",
20153 "3045022100efab186c9f98ff2326c56d26e0a4f0f58afc94fc241faae4334a944d277d7f3802207a79eb3f17fa874eca67c4245b670e51ca8d89d3bc02b2a8712ec28e71479eba",
20154 "03000000000101c3b4fad51418c874498af12060d49477c154845040e3584104ae641c542c0135030000000000000000018813000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100948054ef219ec5af7494224f65ad6fab9cfd415d7260cb70a4719e99d421871f02205a41957a428b7820cef844c41cd06d8443f55953e000f4e40658175544a012ce83483045022100efab186c9f98ff2326c56d26e0a4f0f58afc94fc241faae4334a944d277d7f3802207a79eb3f17fa874eca67c4245b670e51ca8d89d3bc02b2a8712ec28e71479eba0120108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa8b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914f4c8e88504a23ed3e390ea80300c834f0eb79a6c88527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503560a0eb175ac686800000000", Some(htlc_in_preimage) },
20155 {3,
20156 "3045022100f2890a34be31987e4cc3e17f71d5174bb85121e57bb0105e8aa6793f6f057a42022000d0e11ffb3217bb91f1b8babb43e2726889cf3281bfaffa3b3b1c9970fa7109",
20157 "304402200373b0e0533fa0140ae10df40b93bb599920ce582d0a9d07398499554591659e02207f6ef44097b4e850bae0a4b5d6e0778a056e32ccd403ea88c62004d84e91a0af",
20158 "03000000000101c3b4fad51418c874498af12060d49477c154845040e3584104ae641c542c013504000000000000000001a861000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100f2890a34be31987e4cc3e17f71d5174bb85121e57bb0105e8aa6793f6f057a42022000d0e11ffb3217bb91f1b8babb43e2726889cf3281bfaffa3b3b1c9970fa71098347304402200373b0e0533fa0140ae10df40b93bb599920ce582d0a9d07398499554591659e02207f6ef44097b4e850bae0a4b5d6e0778a056e32ccd403ea88c62004d84e91a0af01008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a914504170790db95d43716b136806e6a0fdf06e39e488ac68684d0a0e00", None::<PaymentPreimage> },
20159 {4,
20160 "30440220450536f38c6fde3e8777ad9c6d0a505ff44812de86fc82f0f2a0f4ce11f6ac7a022053306d3739ddd8a5cd8e2acba63b2076927200701762b314fb83faafcfcc3893",
20161 "3045022100e506e7ccb18b31fd3785477a3cfd885d7c21bf6eb9f5368cb321913208ae8e31022074c186967bf90a5583b46f445a6cb12fb6f2bf83805e048b486b8da29a553a46",
20162 "03000000000101c3b4fad51418c874498af12060d49477c154845040e3584104ae641c542c013505000000000000000001a861000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a05004730440220450536f38c6fde3e8777ad9c6d0a505ff44812de86fc82f0f2a0f4ce11f6ac7a022053306d3739ddd8a5cd8e2acba63b2076927200701762b314fb83faafcfcc389383483045022100e506e7ccb18b31fd3785477a3cfd885d7c21bf6eb9f5368cb321913208ae8e31022074c186967bf90a5583b46f445a6cb12fb6f2bf83805e048b486b8da29a553a4601008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a914488ed834d26f1a1dc5e3428e1e1a214f743e6a2488ac68684d0a0e00", None::<PaymentPreimage> },
20163 {5,
20164 "3044022061b73271a1b6b5a1bd8e15c58b08320c72da0a1db19493abbfc6f74b5fa80c2c022030ff309d3413b9661fc8f8f2b5fd14bc733c239cc7ba8b971fd562263e62bf3b",
20165 "304402207559852cd036af82658949c28e4922f7351756616f8d04703e8060889b4b484e022050d997e1684826dc61bf0d88d9d08c01b8fcf67958ac7a177c320a1a70305fb0",
20166 "03000000000101c3b4fad51418c874498af12060d49477c154845040e3584104ae641c542c013506000000000000000001a861000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500473044022061b73271a1b6b5a1bd8e15c58b08320c72da0a1db19493abbfc6f74b5fa80c2c022030ff309d3413b9661fc8f8f2b5fd14bc733c239cc7ba8b971fd562263e62bf3b8347304402207559852cd036af82658949c28e4922f7351756616f8d04703e8060889b4b484e022050d997e1684826dc61bf0d88d9d08c01b8fcf67958ac7a177c320a1a70305fb001008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a914488ed834d26f1a1dc5e3428e1e1a214f743e6a2488ac68684d0a0e00", None::<PaymentPreimage> }
20167 });
20168
20169 chan.context.pending_inbound_htlcs.clear();
20171 chan.context.pending_outbound_htlcs.clear();
20172
20173 chan.context.pending_inbound_htlcs.extend([(7, 10000650), (9, 6000320)].map(
20174 |(htlc_id, amount_msat)| InboundHTLCOutput {
20175 htlc_id,
20176 amount_msat,
20177 cltv_expiry: 920150,
20178 payment_hash: PaymentHash::from(htlc_in_preimage),
20179 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20180 },
20181 ));
20182
20183 chan.context.pending_outbound_htlcs.extend(
20184 [
20185 (5, 25000821, "72c9386ba5a9d97b821d855930236d39c48dab5b1c2efe9ada44e2fbadcff983"),
20186 (8, 25000210, "10b879729e8ddd44f2cfcf3cad6d62be535ca74e293c5ed4a59bd0dcbdad7ca1"),
20187 ]
20188 .map(|(htlc_id, amount_msat, hash_str)| OutboundHTLCOutput {
20189 htlc_id,
20190 amount_msat,
20191 cltv_expiry: 920141,
20192 payment_hash: payment_hash_from_hex(hash_str),
20193 state: OutboundHTLCState::Committed,
20194 source: HTLCSource::dummy(),
20195 skimmed_fee_msat: None,
20196 blinding_point: None,
20197 send_timestamp: None,
20198 hold_htlc: None,
20199 accountable: false,
20200 }),
20201 );
20202
20203 test_commitment_with_zero_fee!(
20204 "304402207077d60a004f42171b99c66b1b6b1799910d8f2cb72b0ef6d6500cd2f937c28a022016464954f0c05ae083bf559bc603c89f014006c44258d054a06ded667166a1f7",
20205 "3045022100cb78620afa0efd40d480286b59545e2e00379e78f6fb8c31d0d3659880176ed102201218323fbc8e0cd1184c7a164fad4cecb841f3eb75a3fc7d11208acbcb663865",
20206 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800703000000000000000451024e73701700000000000022002075254560bb02c207015847abfda36d3a1b882e78c3f04b08325aac21c53989dc102700000000000022002075254560bb02c207015847abfda36d3a1b882e78c3f04b08325aac21c53989dca8610000000000002200200963a1f3e47b8d2a35664f70de49d3331b4499da201004868a9104271f0cd93ba8610000000000002200205b138be4da633f087be191275d3ce30828ae32d1630853fcbf66d22ca6fe2636ff451e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaae4e790000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402207077d60a004f42171b99c66b1b6b1799910d8f2cb72b0ef6d6500cd2f937c28a022016464954f0c05ae083bf559bc603c89f014006c44258d054a06ded667166a1f701483045022100cb78620afa0efd40d480286b59545e2e00379e78f6fb8c31d0d3659880176ed102201218323fbc8e0cd1184c7a164fad4cecb841f3eb75a3fc7d11208acbcb66386501475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {
20207 {0,
20208 "3045022100d53dbf9e7479d48322eda78cd96c0d3d6a53c55c7c0d629a2b11e1b1a02d6b95022031a06dda013ee5a26db181552499816de0a9786c71cbefd1614f8b2e6bcb9131",
20209 "304402204e4fd2e36058ed515f36cc609e636989fa89bf0b1d0e968fe642fcca7e2ceb1e022055a69e1e9be2799ae57ebae59792c9f50ca3943e6c154b4b3aabce6b08000930",
20210 "0300000000010122daaec93bca3ee6bee9c78cf7885e538a56d0cbd63e3df086bbac22b4f5455d010000000000000000017017000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100d53dbf9e7479d48322eda78cd96c0d3d6a53c55c7c0d629a2b11e1b1a02d6b95022031a06dda013ee5a26db181552499816de0a9786c71cbefd1614f8b2e6bcb91318347304402204e4fd2e36058ed515f36cc609e636989fa89bf0b1d0e968fe642fcca7e2ceb1e022055a69e1e9be2799ae57ebae59792c9f50ca3943e6c154b4b3aabce6b080009300120108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa8b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914f4c8e88504a23ed3e390ea80300c834f0eb79a6c88527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503560a0eb175ac686800000000", Some(htlc_in_preimage) },
20211 {1,
20212 "304402206556f3ae8fb62fd764f1a65fcc238bfc7cd629872c52ba7ee7b91e34aed4f9de022008545d9f5477371f940d8719270cc1b22d04497f53a97bf75dfb6a9ec5e5b49e",
20213 "304402205aa6b8143ef46e644157c4f4ad2ff439ae3c2e0cd76c2d3050aa6a1f5a31d33d022072f430949c2996233c5e832c3957f4f9bbf5586af3d62ebf3c0621cf92511b1a",
20214 "0300000000010122daaec93bca3ee6bee9c78cf7885e538a56d0cbd63e3df086bbac22b4f5455d020000000000000000011027000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a050047304402206556f3ae8fb62fd764f1a65fcc238bfc7cd629872c52ba7ee7b91e34aed4f9de022008545d9f5477371f940d8719270cc1b22d04497f53a97bf75dfb6a9ec5e5b49e8347304402205aa6b8143ef46e644157c4f4ad2ff439ae3c2e0cd76c2d3050aa6a1f5a31d33d022072f430949c2996233c5e832c3957f4f9bbf5586af3d62ebf3c0621cf92511b1a0120108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa8b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914f4c8e88504a23ed3e390ea80300c834f0eb79a6c88527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503560a0eb175ac686800000000", Some(htlc_in_preimage) },
20215 {2,
20216 "30450221009d775b6e196693171a41c69337de17bd6c7846dd677d0f9db8595faedb3f621f022060eb980ee28effaa38515b31691ec522fef90db0f6b83c07cf3cf3aebc1302c0",
20217 "3045022100e93e04871634a1eded25a6721bb6005787e92cfea09831f7af99433891d5373202204ec63ff8fd536518eca98e068d05d562d7be9465cb4d72a52a35308a4b3d8430",
20218 "0300000000010122daaec93bca3ee6bee9c78cf7885e538a56d0cbd63e3df086bbac22b4f5455d03000000000000000001a861000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a05004830450221009d775b6e196693171a41c69337de17bd6c7846dd677d0f9db8595faedb3f621f022060eb980ee28effaa38515b31691ec522fef90db0f6b83c07cf3cf3aebc1302c083483045022100e93e04871634a1eded25a6721bb6005787e92cfea09831f7af99433891d5373202204ec63ff8fd536518eca98e068d05d562d7be9465cb4d72a52a35308a4b3d843001008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a914504170790db95d43716b136806e6a0fdf06e39e488ac68684d0a0e00", None::<PaymentPreimage> },
20219 {3,
20220 "3045022100c86ebf7f229be7b621a34a3fac39cfe20ea6b26e078eca782c136e635077b47a02205866ca91ef3eb8bc8dd8190c25d8a70dd101b067cc038d367ef2ee5a67c1beea",
20221 "304402203f81e6064b5a57bdc9a8759a0906dd8ee767063878f10133c435198c89c575a2022045d4e28f14aad0be1f03e43b3c6bd994d95b18b7ee979b4166c50659d4c02fa6",
20222 "0300000000010122daaec93bca3ee6bee9c78cf7885e538a56d0cbd63e3df086bbac22b4f5455d04000000000000000001a861000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100c86ebf7f229be7b621a34a3fac39cfe20ea6b26e078eca782c136e635077b47a02205866ca91ef3eb8bc8dd8190c25d8a70dd101b067cc038d367ef2ee5a67c1beea8347304402203f81e6064b5a57bdc9a8759a0906dd8ee767063878f10133c435198c89c575a2022045d4e28f14aad0be1f03e43b3c6bd994d95b18b7ee979b4166c50659d4c02fa601008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a914488ed834d26f1a1dc5e3428e1e1a214f743e6a2488ac68684d0a0e00", None::<PaymentPreimage> }
20223 });
20224
20225 chan.context.holder_dust_limit_satoshis = 1000;
20227 chan.funding.value_to_self_msat = 8000000000;
20228 chan.context.pending_inbound_htlcs.clear();
20229 chan.context.pending_outbound_htlcs.clear();
20230
20231 let htlc_0_in_preimage =
20232 preimage_from_hex("d3ad493d19860e4744491cf0795c0bc96a8e2a49ebb30afadae7a7d077aa93b2");
20233 let htlc_0_in_hash = PaymentHash::from(htlc_0_in_preimage);
20234 assert_eq!(
20235 payment_hash_from_hex(
20236 "ffa4f37b6d7dc03fecaaed8d36ebbea6d199e820e386e4549a69ce733f39f29f",
20237 ),
20238 htlc_0_in_hash,
20239 "test vector hash does not match ours",
20240 );
20241 chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
20242 htlc_id: 0,
20243 amount_msat: 100000,
20244 cltv_expiry: 920125,
20245 payment_hash: htlc_0_in_hash,
20246 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20247 });
20248
20249 let htlc_1_in_preimage =
20250 preimage_from_hex("5591b96c0a6a03f51c27bfa658149260bd2fe5e2ce83130ce50d0229a3a947c5");
20251 let htlc_1_in_hash = PaymentHash::from(htlc_1_in_preimage);
20252 assert_eq!(
20253 payment_hash_from_hex(
20254 "72c9386ba5a9d97b821d855930236d39c48dab5b1c2efe9ada44e2fbadcff983",
20255 ),
20256 htlc_1_in_hash,
20257 "test vector hash does not match ours",
20258 );
20259 chan.context.pending_inbound_htlcs.push(InboundHTLCOutput {
20260 htlc_id: 1,
20261 amount_msat: 49900000,
20262 cltv_expiry: 920125,
20263 payment_hash: htlc_1_in_hash,
20264 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20265 });
20266
20267 chan.context.pending_outbound_htlcs.extend(
20268 [(0, 10000000), (1, 130000), (2, 10000000)].map(|(htlc_id, amount_msat)| {
20269 OutboundHTLCOutput {
20270 htlc_id,
20271 amount_msat,
20272 cltv_expiry: 920140,
20273 payment_hash: payment_hash_from_hex(
20274 "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf",
20275 ),
20276 state: OutboundHTLCState::Committed,
20277 source: HTLCSource::dummy(),
20278 skimmed_fee_msat: None,
20279 blinding_point: None,
20280 send_timestamp: None,
20281 hold_htlc: None,
20282 accountable: false,
20283 }
20284 }),
20285 );
20286
20287 test_commitment_with_zero_fee!(
20288 "3045022100cb7b6ae16b80c1ad74baea6f37be3581ca60915da75a03be3b377493f3359cc302203b591047f669cce31215c8a5a6039d5fd8dbfd8d6b53af39a619e6541d6bcf31",
20289 "3045022100a661444a0800fe5e8bf9ecdef3631610e834485503b8e58d64d08ed5e88ebb2d0220248944d134cadf36cef90d05785ece9432727e81f0f66958a903baa0d69061cd",
20290 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8006e6000000000000000451024e73102700000000000022002081cd2904fc5581e6459d9375384af1223e6bd4fd112f3505e87b81e622a48cb7102700000000000022002081cd2904fc5581e6459d9375384af1223e6bd4fd112f3505e87b81e622a48cb7ecc20000000000002200207c2edfefe2690c02efde0c461b8a9283ed2a68968109306be4cb5fa848bd7a7630c11d0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea5ec3790000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100cb7b6ae16b80c1ad74baea6f37be3581ca60915da75a03be3b377493f3359cc302203b591047f669cce31215c8a5a6039d5fd8dbfd8d6b53af39a619e6541d6bcf3101483045022100a661444a0800fe5e8bf9ecdef3631610e834485503b8e58d64d08ed5e88ebb2d0220248944d134cadf36cef90d05785ece9432727e81f0f66958a903baa0d69061cd01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {
20291 {0,
20292 "30450221009beeb028f6de6f925a986f3aaac7931bd46779b5a2dc8e82ae0509cf0174468002205a2761d34b276752f7f6e62c013c9509104a831df1f4b91a692bb8ad48285d31",
20293 "3045022100c04dd0b08fd50bfc921de2a5d09840aab97b116e95ffd09cc11470404280be1202204aee1cd187f0074c5b80bae98981d232168daba5bde67adc7539b1a55a5a6709",
20294 "03000000000101d8211cfec4c28b189edcf7b12b739bfbc0f77e44cc6fab67e50fa23cc78481c5010000000000000000011027000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a05004830450221009beeb028f6de6f925a986f3aaac7931bd46779b5a2dc8e82ae0509cf0174468002205a2761d34b276752f7f6e62c013c9509104a831df1f4b91a692bb8ad48285d3183483045022100c04dd0b08fd50bfc921de2a5d09840aab97b116e95ffd09cc11470404280be1202204aee1cd187f0074c5b80bae98981d232168daba5bde67adc7539b1a55a5a670901008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a91489baf9f76be304292b0314ffa9c61eb794b05dd188ac68684c0a0e00", None::<PaymentPreimage> },
20295 {1,
20296 "304402203a6ed1dc27298cfb030a5ff0f237b5288e263bd3cfe13ced890f3559e7c25db10220713167cc374f850a2f414dd8988f87cbfe978ba56b8c5cf690aa3c2d357a174c",
20297 "3045022100c2f636b397f0fd6731b04323a0743aee902f01ac2e8bdac72548ab5380fecd0f02206ee5c57fac4c5255018bc687ae46a97a9781b7d87722d3c73b8bc93d951f713f",
20298 "03000000000101d8211cfec4c28b189edcf7b12b739bfbc0f77e44cc6fab67e50fa23cc78481c5020000000000000000011027000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a050047304402203a6ed1dc27298cfb030a5ff0f237b5288e263bd3cfe13ced890f3559e7c25db10220713167cc374f850a2f414dd8988f87cbfe978ba56b8c5cf690aa3c2d357a174c83483045022100c2f636b397f0fd6731b04323a0743aee902f01ac2e8bdac72548ab5380fecd0f02206ee5c57fac4c5255018bc687ae46a97a9781b7d87722d3c73b8bc93d951f713f01008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a91489baf9f76be304292b0314ffa9c61eb794b05dd188ac68684c0a0e00", None::<PaymentPreimage> },
20299 {2,
20300 "3045022100bbafdb3eeb4ab737859798753e0685f203294b6225c1300c9db6867a6f5fde180220769ca281abe51e93d707262ab3f45c54f5ec0ad3529836de0536b24e635e1c9f",
20301 "304402200f60ba0673e03a25cd8ab2f2d8fe4e0bc3ac7ffafe932e7a76afb3be7189b4f50220541a02e557d7ff2ccf0f5be4fa22291d07ecf67d8666dffba55e76ecbb5b9bf9",
20302 "03000000000101d8211cfec4c28b189edcf7b12b739bfbc0f77e44cc6fab67e50fa23cc78481c503000000000000000001ecc2000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100bbafdb3eeb4ab737859798753e0685f203294b6225c1300c9db6867a6f5fde180220769ca281abe51e93d707262ab3f45c54f5ec0ad3529836de0536b24e635e1c9f8347304402200f60ba0673e03a25cd8ab2f2d8fe4e0bc3ac7ffafe932e7a76afb3be7189b4f50220541a02e557d7ff2ccf0f5be4fa22291d07ecf67d8666dffba55e76ecbb5b9bf901205591b96c0a6a03f51c27bfa658149260bd2fe5e2ce83130ce50d0229a3a947c58b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914488ed834d26f1a1dc5e3428e1e1a214f743e6a2488527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae6775033d0a0eb175ac686800000000",
20303 Some(htlc_1_in_preimage) }
20304 });
20305
20306 chan.context.holder_dust_limit_satoshis = 546;
20308 chan.context.pending_inbound_htlcs.clear();
20309 chan.context.pending_outbound_htlcs.clear();
20310
20311 chan.context.pending_inbound_htlcs.extend([(0, htlc_0_in_hash), (1, htlc_1_in_hash)].map(
20312 |(htlc_id, payment_hash)| InboundHTLCOutput {
20313 htlc_id,
20314 amount_msat: 30000,
20315 payment_hash,
20316 cltv_expiry: 920125,
20317 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20318 },
20319 ));
20320
20321 chan.context.pending_outbound_htlcs.extend(
20322 [
20323 (0, "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf"),
20324 (1, "1a04764fd402b5557cba89ec3c4d8931b0225d6436923c65c079ce64a55084c4"),
20325 (2, "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf"),
20326 (3, "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf"),
20327 ]
20328 .map(|(id, hash)| OutboundHTLCOutput {
20329 htlc_id: id,
20330 amount_msat: 30000,
20331 cltv_expiry: 920125,
20332 payment_hash: payment_hash_from_hex(hash),
20333 state: OutboundHTLCState::Committed,
20334 source: HTLCSource::dummy(),
20335 skimmed_fee_msat: None,
20336 blinding_point: None,
20337 send_timestamp: None,
20338 hold_htlc: None,
20339 accountable: false,
20340 }),
20341 );
20342
20343 test_commitment_with_zero_fee!(
20344 "3044022034f22696dd7501d65fc117af3edcfed535eb301317fe35eef08658b571fca4d0022030ff6276cff9e22968f8b08f92a1d4f2c37fe4da29de095df4841d32bdaa501b",
20345 "30450221009c820c376715329110045b3cf90f59838fd2f86b16774cb5ccccbd6a62830d9602205f2d970bef2589a5e37035937ab7db0461223e429b943b38ecf577e32b7b4572",
20346 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8003b4000000000000000451024e7344841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea88117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400473044022034f22696dd7501d65fc117af3edcfed535eb301317fe35eef08658b571fca4d0022030ff6276cff9e22968f8b08f92a1d4f2c37fe4da29de095df4841d32bdaa501b014830450221009c820c376715329110045b3cf90f59838fd2f86b16774cb5ccccbd6a62830d9602205f2d970bef2589a5e37035937ab7db0461223e429b943b38ecf577e32b7b457201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20347
20348 chan.context.holder_dust_limit_satoshis = 330;
20350 chan.context.pending_inbound_htlcs.clear();
20351 chan.context.pending_outbound_htlcs.clear();
20352
20353 chan.context.pending_inbound_htlcs.extend([(0, htlc_0_in_hash)].map(
20354 |(htlc_id, payment_hash)| InboundHTLCOutput {
20355 htlc_id,
20356 amount_msat: 29525,
20357 payment_hash,
20358 cltv_expiry: 920125,
20359 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20360 },
20361 ));
20362
20363 chan.context.pending_outbound_htlcs.extend(
20364 [(0, "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf")].map(
20365 |(id, hash)| OutboundHTLCOutput {
20366 htlc_id: id,
20367 amount_msat: 21474,
20368 cltv_expiry: 920125,
20369 payment_hash: payment_hash_from_hex(hash),
20370 state: OutboundHTLCState::Committed,
20371 source: HTLCSource::dummy(),
20372 skimmed_fee_msat: None,
20373 blinding_point: None,
20374 send_timestamp: None,
20375 hold_htlc: None,
20376 accountable: false,
20377 },
20378 ),
20379 );
20380
20381 test_commitment_with_zero_fee!(
20382 "304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177",
20383 "30440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d",
20384 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20385
20386 chan.context.holder_dust_limit_satoshis = 330;
20388 chan.context.pending_inbound_htlcs.clear();
20389 chan.context.pending_outbound_htlcs.clear();
20390
20391 chan.context.pending_inbound_htlcs.extend([(0, htlc_0_in_hash)].map(
20392 |(htlc_id, payment_hash)| InboundHTLCOutput {
20393 htlc_id,
20394 amount_msat: 29525,
20395 payment_hash,
20396 cltv_expiry: 920125,
20397 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20398 },
20399 ));
20400
20401 chan.context.pending_outbound_htlcs.extend(
20402 [(0, "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf")].map(
20403 |(id, hash)| OutboundHTLCOutput {
20404 htlc_id: id,
20405 amount_msat: 21475,
20406 cltv_expiry: 920125,
20407 payment_hash: payment_hash_from_hex(hash),
20408 state: OutboundHTLCState::Committed,
20409 source: HTLCSource::dummy(),
20410 skimmed_fee_msat: None,
20411 blinding_point: None,
20412 send_timestamp: None,
20413 hold_htlc: None,
20414 accountable: false,
20415 },
20416 ),
20417 );
20418
20419 test_commitment_with_zero_fee!(
20420 "304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177",
20421 "30440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d",
20422 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20423
20424 chan.context.holder_dust_limit_satoshis = 330;
20426 chan.context.pending_inbound_htlcs.clear();
20427 chan.context.pending_outbound_htlcs.clear();
20428
20429 chan.context.pending_inbound_htlcs.extend([(0, htlc_0_in_hash)].map(
20430 |(htlc_id, payment_hash)| InboundHTLCOutput {
20431 htlc_id,
20432 amount_msat: 29753,
20433 payment_hash,
20434 cltv_expiry: 920125,
20435 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20436 },
20437 ));
20438
20439 chan.context.pending_outbound_htlcs.extend(
20440 [(0, "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf")].map(
20441 |(id, hash)| OutboundHTLCOutput {
20442 htlc_id: id,
20443 amount_msat: 21712,
20444 cltv_expiry: 920125,
20445 payment_hash: payment_hash_from_hex(hash),
20446 state: OutboundHTLCState::Committed,
20447 source: HTLCSource::dummy(),
20448 skimmed_fee_msat: None,
20449 blinding_point: None,
20450 send_timestamp: None,
20451 hold_htlc: None,
20452 accountable: false,
20453 },
20454 ),
20455 );
20456
20457 test_commitment_with_zero_fee!(
20458 "304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177",
20459 "30440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d",
20460 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800334000000000000000451024e7362841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152eaea117a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a040047304402201368dc415e11647edbfc1faaaccbe4717e5fdb88c4220a0bb19969781c9f757f02203fad3a7578fcfdc428b527b97f918b639ff07941b3b42c44f58b1364fdc57177014730440220338a338e0d477b63d2a7a00baca06c45b74bdd63d02e7d198cd8435180e9317e022014d0b95c9fde3409678417ee1a71d1d4d755f28db66a83eb10bea56de83d628d01475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20461
20462 chan.context.holder_dust_limit_satoshis = 2500;
20464 chan.funding.value_to_self_msat = 8000000000;
20465 chan.context.pending_inbound_htlcs.clear();
20466 chan.context.pending_outbound_htlcs.clear();
20467
20468 let htlc_2_in_preimage =
20469 preimage_from_hex("108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa");
20470 let htlc_2_in_hash = PaymentHash::from(htlc_2_in_preimage);
20471 assert_eq!(
20472 payment_hash_from_hex(
20473 "23877c9093799487a8d49c7d6aaff7e06b9831c547400605252e7b07f7ae638a",
20474 ),
20475 htlc_2_in_hash,
20476 );
20477 chan.context.pending_inbound_htlcs.extend(
20478 [
20479 (0, 2000000, 920125, htlc_0_in_hash),
20480 (1, 5000000, 920130, htlc_0_in_hash),
20481 (2, 5000000, 920130, htlc_2_in_hash),
20482 ]
20483 .map(|(id, amount_msat, cltv_expiry, payment_hash)| InboundHTLCOutput {
20484 htlc_id: id,
20485 amount_msat,
20486 cltv_expiry,
20487 payment_hash,
20488 state: InboundHTLCState::Committed { update_add_htlc: dummy_inbound_update_add() },
20489 }),
20490 );
20491
20492 let htlc_0_out_hash = "1a04764fd402b5557cba89ec3c4d8931b0225d6436923c65c079ce64a55084c4";
20493 let htlc_1_out_hash = "29a74a69c5941d402838f7e1a95c2b2ec534d79524b2582f48df7bc519ebaecf";
20494 let htlc_2_out_hash = "10b879729e8ddd44f2cfcf3cad6d62be535ca74e293c5ed4a59bd0dcbdad7ca1";
20495
20496 chan.context.pending_outbound_htlcs.extend(
20497 [
20498 (0, 1000000, 920125, htlc_0_out_hash),
20499 (1, 1000000, 920130, htlc_1_out_hash),
20500 (2, 10000000, 920130, htlc_2_out_hash),
20501 ]
20502 .map(|(id, amount_msat, cltv_expiry, hash)| OutboundHTLCOutput {
20503 htlc_id: id,
20504 amount_msat,
20505 cltv_expiry,
20506 payment_hash: payment_hash_from_hex(hash),
20507 state: OutboundHTLCState::Committed,
20508 source: HTLCSource::dummy(),
20509 skimmed_fee_msat: None,
20510 blinding_point: None,
20511 send_timestamp: None,
20512 hold_htlc: None,
20513 accountable: false,
20514 }),
20515 );
20516
20517 test_commitment_with_zero_fee!(
20518 "3045022100f706457b6f58634a64d86a403b622018d1cdf08064f08eaaf90ed47cbdfc81f002200b23d77b8151d0e907850d313b87cf53f0a1e8aef871cbb5ec3ef7f3af513261",
20519 "3045022100cf3f7201781764693b8bb2db1a703c62fe9cb992103d4d950e9d1806e2e4c49202203993f5bfcc1f91617d48f22a10f2400ca298f42499d8389d4396bcad8750e883",
20520 "03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef8006f0000000000000000451024e7388130000000000002200202cb7b4a1ac1ca2aa06918f6933a9bf3a6ab777abfca18ac22fb4eeec587faf048813000000000000220020fd9f3b68e5a818a53f020ab09d1c956ead78f28b3c22950dc0d73568f797c92210270000000000002200200963a1f3e47b8d2a35664f70de49d3331b4499da201004868a9104271f0cd93ba0551e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea20e3790000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100f706457b6f58634a64d86a403b622018d1cdf08064f08eaaf90ed47cbdfc81f002200b23d77b8151d0e907850d313b87cf53f0a1e8aef871cbb5ec3ef7f3af51326101483045022100cf3f7201781764693b8bb2db1a703c62fe9cb992103d4d950e9d1806e2e4c49202203993f5bfcc1f91617d48f22a10f2400ca298f42499d8389d4396bcad8750e88301475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {
20521 {0,
20522 "3044022072f786f54d93d9b1780bd3c605a434a2ae097852c6af75b18a23ea3e7cb995de02205608d310544bed398c406cf8f6cdeadbf119a8808c38415dbc93c82733168fc6",
20523 "3045022100e5e66a86053e6adda1b02786d9e8b9b7057026b8d81263fe5414d6b7660e70c7022055ff89300da995e2c8122e997338dac2d5ea2f526dcb243b9e7c1eb380155e10",
20524 "0300000000010142bb3321b077161ea560097e1b149edef504e00f1e2c6a77bbe4ad2aed6fde07010000000000000000018813000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500473044022072f786f54d93d9b1780bd3c605a434a2ae097852c6af75b18a23ea3e7cb995de02205608d310544bed398c406cf8f6cdeadbf119a8808c38415dbc93c82733168fc683483045022100e5e66a86053e6adda1b02786d9e8b9b7057026b8d81263fe5414d6b7660e70c7022055ff89300da995e2c8122e997338dac2d5ea2f526dcb243b9e7c1eb380155e100120d3ad493d19860e4744491cf0795c0bc96a8e2a49ebb30afadae7a7d077aa93b28b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a91416a189e9fcfe9edc8c6930da3dd87cebf44045a388527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503420a0eb175ac686800000000", Some(htlc_0_in_preimage) },
20525 {1,
20526 "30440220444371784d52a13dedec1baedd0a5f10cc78727a873614cf6981696e0ef9d28502202961336e7e0cbb530c4e5dda0a628bc21b5ce8e3f1e6274bd7ee20cf7b697421",
20527 "304402205b1693a32569a757d0928c163aae56a3986e3d53741ba0a9db5aac1289752aa3022002c8ef3e377a2461800e98cbfc40b31511d39e02473152943d959dcfd55e7c9e",
20528 "0300000000010142bb3321b077161ea560097e1b149edef504e00f1e2c6a77bbe4ad2aed6fde07020000000000000000018813000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a05004730440220444371784d52a13dedec1baedd0a5f10cc78727a873614cf6981696e0ef9d28502202961336e7e0cbb530c4e5dda0a628bc21b5ce8e3f1e6274bd7ee20cf7b6974218347304402205b1693a32569a757d0928c163aae56a3986e3d53741ba0a9db5aac1289752aa3022002c8ef3e377a2461800e98cbfc40b31511d39e02473152943d959dcfd55e7c9e0120108cd7067c8ed6f3734b7b67ec153cfa83c40755b75c65e414e934099e6993aa8b76a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c8201208763a914f4c8e88504a23ed3e390ea80300c834f0eb79a6c88527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae677503420a0eb175ac686800000000", Some(htlc_2_in_preimage) },
20529 {2,
20530 "3045022100eee7c19343ad58d9381a808fcd14af0c1e05bd56bd16c25c5ad8980af68b2df9022046acc611280afabcd82ef4a256d1f42be6618bc12d83bcd138141fb4915d256f",
20531 "3045022100e6c8d81693cd3a03db0777b31e9318f8b8eb5f275817116dce8a72064d096bee02206439ddcac93a2756e1079e955245e2ac1924d874ba8388de9d497e4286cc20cb",
20532 "0300000000010142bb3321b077161ea560097e1b149edef504e00f1e2c6a77bbe4ad2aed6fde07030000000000000000011027000000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0500483045022100eee7c19343ad58d9381a808fcd14af0c1e05bd56bd16c25c5ad8980af68b2df9022046acc611280afabcd82ef4a256d1f42be6618bc12d83bcd138141fb4915d256f83483045022100e6c8d81693cd3a03db0777b31e9318f8b8eb5f275817116dce8a72064d096bee02206439ddcac93a2756e1079e955245e2ac1924d874ba8388de9d497e4286cc20cb01008576a914ef8968bbfe34ad740642784d7b1efaebfd5b23ec8763ac672103d8507a026fb30bcd48ee9c765c7346470d0d397661d43dd2eb601f661ab92a0b7c820120876475527c2103c26117339025855b87deda5e138d438b2098881a5e6f81f72a60310faef473c652ae67a914504170790db95d43716b136806e6a0fdf06e39e488ac6868420a0e00", None::<PaymentPreimage>}
20533 });
20534 }
20535
20536 #[test]
20537 #[rustfmt::skip]
20538 fn test_per_commitment_secret_gen() {
20539 let mut seed = [0; 32];
20542 seed[0..32].clone_from_slice(&<Vec<u8>>::from_hex("0000000000000000000000000000000000000000000000000000000000000000").unwrap());
20543 assert_eq!(chan_utils::build_commitment_secret(&seed, 281474976710655),
20544 <Vec<u8>>::from_hex("02a40c85b6f28da08dfdbe0926c53fab2de6d28c10301f8f7c4073d5e42e3148").unwrap()[..]);
20545
20546 seed[0..32].clone_from_slice(&<Vec<u8>>::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").unwrap());
20547 assert_eq!(chan_utils::build_commitment_secret(&seed, 281474976710655),
20548 <Vec<u8>>::from_hex("7cc854b54e3e0dcdb010d7a3fee464a9687be6e8db3be6854c475621e007a5dc").unwrap()[..]);
20549
20550 assert_eq!(chan_utils::build_commitment_secret(&seed, 0xaaaaaaaaaaa),
20551 <Vec<u8>>::from_hex("56f4008fb007ca9acf0e15b054d5c9fd12ee06cea347914ddbaed70d1c13a528").unwrap()[..]);
20552
20553 assert_eq!(chan_utils::build_commitment_secret(&seed, 0x555555555555),
20554 <Vec<u8>>::from_hex("9015daaeb06dba4ccc05b91b2f73bd54405f2be9f217fbacd3c5ac2e62327d31").unwrap()[..]);
20555
20556 seed[0..32].clone_from_slice(&<Vec<u8>>::from_hex("0101010101010101010101010101010101010101010101010101010101010101").unwrap());
20557 assert_eq!(chan_utils::build_commitment_secret(&seed, 1),
20558 <Vec<u8>>::from_hex("915c75942a26bb3a433a8ce2cb0427c29ec6c1775cfc78328b57f6ba7bfeaa9c").unwrap()[..]);
20559 }
20560
20561 #[test]
20562 #[rustfmt::skip]
20563 fn test_key_derivation() {
20564 let secp_ctx = Secp256k1::new();
20566
20567 let base_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap()[..]).unwrap();
20568 let per_commitment_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex("1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100").unwrap()[..]).unwrap();
20569
20570 let base_point = PublicKey::from_secret_key(&secp_ctx, &base_secret);
20571 assert_eq!(base_point.serialize()[..], <Vec<u8>>::from_hex("036d6caac248af96f6afa7f904f550253a0f3ef3f5aa2fe6838a95b216691468e2").unwrap()[..]);
20572
20573 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &per_commitment_secret);
20574 assert_eq!(per_commitment_point.serialize()[..], <Vec<u8>>::from_hex("025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486").unwrap()[..]);
20575
20576 assert_eq!(chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &base_secret),
20577 SecretKey::from_slice(&<Vec<u8>>::from_hex("cbced912d3b21bf196a766651e436aff192362621ce317704ea2f75d87e7be0f").unwrap()[..]).unwrap());
20578
20579 assert_eq!(RevocationKey::from_basepoint(&secp_ctx, &RevocationBasepoint::from(base_point), &per_commitment_point).to_public_key().serialize()[..],
20580 <Vec<u8>>::from_hex("02916e326636d19c33f13e8c0c3a03dd157f332f3e99c317c141dd865eb01f8ff0").unwrap()[..]);
20581
20582 assert_eq!(chan_utils::derive_private_revocation_key(&secp_ctx, &per_commitment_secret, &base_secret),
20583 SecretKey::from_slice(&<Vec<u8>>::from_hex("d09ffff62ddb2297ab000cc85bcb4283fdeb6aa052affbc9dddcf33b61078110").unwrap()[..]).unwrap());
20584 }
20585
20586 #[test]
20587 #[rustfmt::skip]
20588 fn test_waiting_for_batch() {
20589 let test_est = TestFeeEstimator::new(15000);
20590 let feeest = LowerBoundedFeeEstimator::new(&test_est);
20591 let logger = TestLogger::new();
20592 let secp_ctx = Secp256k1::new();
20593 let seed = [42; 32];
20594 let network = Network::Testnet;
20595 let best_block = BlockLocator::from_network(network);
20596 let chain_hash = ChainHash::using_genesis_block(network);
20597 let keys_provider = TestKeysInterface::new(&seed, network);
20598
20599 let mut config = UserConfig::default();
20600 config.channel_handshake_limits.trust_own_funding_0conf = true;
20603
20604 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
20606 let mut node_a_chan = OutboundV1Channel::<&TestKeysInterface>::new(
20607 &feeest,
20608 &&keys_provider,
20609 &&keys_provider,
20610 node_b_node_id,
20611 &channelmanager::provided_init_features(&config),
20612 10000000,
20613 100000,
20614 42,
20615 &config,
20616 0,
20617 42,
20618 None,
20619 &logger,
20620 None,
20621 ).unwrap();
20622
20623 let open_channel_msg = node_a_chan.get_open_channel(ChainHash::using_genesis_block(network), &&logger).unwrap();
20624 let node_b_node_id = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[7; 32]).unwrap());
20625 let mut node_b_chan = InboundV1Channel::<&TestKeysInterface>::new(
20626 &feeest,
20627 &&keys_provider,
20628 &&keys_provider,
20629 node_b_node_id,
20630 &channelmanager::provided_channel_type_features(&config),
20631 &channelmanager::provided_init_features(&config),
20632 &open_channel_msg,
20633 7,
20634 &config,
20635 0,
20636 &&logger,
20637 Some(TrustedChannelFeatures::ZeroConf),
20639 ).unwrap();
20640
20641 let accept_channel_msg = node_b_chan.accept_inbound_channel(&&logger).unwrap();
20642 node_a_chan.accept_channel(
20643 &accept_channel_msg,
20644 &config.channel_handshake_limits,
20645 &channelmanager::provided_init_features(&config),
20646 ).unwrap();
20647
20648 let output_script = node_a_chan.funding.get_funding_redeemscript();
20650 let tx = Transaction {
20651 version: Version::ONE,
20652 lock_time: LockTime::ZERO,
20653 input: Vec::new(),
20654 output: vec![
20655 TxOut {
20656 value: Amount::from_sat(10000000), script_pubkey: output_script.clone(),
20657 },
20658 TxOut {
20659 value: Amount::from_sat(10000000), script_pubkey: Builder::new().into_script(),
20660 },
20661 ]};
20662 let funding_outpoint = OutPoint{ txid: tx.compute_txid(), index: 0 };
20663 let funding_created_msg = node_a_chan.get_funding_created(
20664 tx.clone(), funding_outpoint, true, &&logger,
20665 ).map_err(|_| ()).unwrap();
20666 let (mut node_b_chan, funding_signed_msg, _) = node_b_chan.funding_created(
20667 &funding_created_msg.unwrap(),
20668 best_block,
20669 &&keys_provider,
20670 &&logger,
20671 ).map_err(|_| ()).unwrap();
20672 let node_b_updates = node_b_chan.monitor_updating_restored(
20673 &WithChannelContext::from(&logger, &node_b_chan.context, None),
20674 &&keys_provider,
20675 chain_hash,
20676 &config,
20677 0,
20678 |_| unreachable!()
20679 );
20680
20681 let res = node_a_chan.funding_signed(
20684 &funding_signed_msg.unwrap(), best_block, &&keys_provider, &&logger,
20685 );
20686 let (mut node_a_chan, _) = if let Ok(res) = res { res } else { panic!(); };
20687 let node_a_updates = node_a_chan.monitor_updating_restored(
20688 &WithChannelContext::from(&logger, &node_a_chan.context, None),
20689 &&keys_provider,
20690 chain_hash,
20691 &config,
20692 0,
20693 |_| unreachable!()
20694 );
20695 assert!(node_a_updates.channel_ready.is_none());
20698 assert!(node_a_updates.funding_broadcastable.is_none());
20699 assert_eq!(node_a_chan.context.channel_state, ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::WAITING_FOR_BATCH));
20700
20701 node_a_chan.channel_ready(
20703 &node_b_updates.channel_ready.unwrap(),
20704 &&keys_provider,
20705 chain_hash,
20706 &config,
20707 &best_block,
20708 &&logger,
20709 ).unwrap();
20710 assert_eq!(
20711 node_a_chan.context.channel_state,
20712 ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::WAITING_FOR_BATCH | AwaitingChannelReadyFlags::THEIR_CHANNEL_READY)
20713 );
20714
20715 node_a_chan.set_batch_ready();
20717 assert_eq!(node_a_chan.context.channel_state, ChannelState::AwaitingChannelReady(AwaitingChannelReadyFlags::THEIR_CHANNEL_READY));
20718 assert!(node_a_chan.check_get_channel_ready(0, &&logger).is_some());
20719 }
20720}