Skip to main content

lightning/ln/
channel.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
4// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7// You may not use this file except in accordance with one or both of these
8// licenses.
9
10use 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, // outgoing
118	pub counterparty_dust_limit_msat: u64,
119}
120
121pub struct AvailableBalances {
122	/// Total amount available for our counterparty to send to us.
123	pub inbound_capacity_msat: u64,
124	/// Total amount available for us to send to our counterparty.
125	pub outbound_capacity_msat: u64,
126	/// The maximum value we can assign to the next outbound HTLC
127	pub next_outbound_htlc_limit_msat: u64,
128	/// The minimum value we can assign to the next outbound HTLC
129	pub next_outbound_htlc_minimum_msat: u64,
130	/// The current total dust exposure on this channel, in millisatoshis.
131	///
132	/// This is the maximum of the dust exposure on the holder and counterparty commitment
133	/// transactions, and includes both the value of all pending HTLCs that are below the dust
134	/// threshold as well as any excess commitment transaction fees that contribute to dust
135	/// exposure.
136	///
137	/// See [`ChannelConfig::max_dust_htlc_exposure`] for more information on the dust calculation and to configure a limit.
138	pub dust_exposure_msat: u64,
139	/// The maximum value of the next splice-out
140	pub next_splice_out_maximum_sat: u64,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq)]
144enum FeeUpdateState {
145	// Inbound states mirroring InboundHTLCState
146	RemoteAnnounced,
147	AwaitingRemoteRevokeToAnnounce,
148	// Note that we do not have a AwaitingAnnouncedRemoteRevoke variant here as it is universally
149	// handled the same as `Committed`, with the only exception in `InboundHTLCState` being the
150	// distinction of when we allow ourselves to forward the HTLC. Because we aren't "forwarding"
151	// the fee update anywhere, we can simply consider the fee update `Committed` immediately
152	// instead of setting it to AwaitingAnnouncedRemoteRevoke.
153
154	// Outbound state can only be `LocalAnnounced` or `Committed`
155	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/// Represents the resolution status of an inbound HTLC.
177#[cfg_attr(test, derive(Debug))]
178#[derive(Clone)]
179enum InboundHTLCResolution {
180	/// Resolved implies the action we must take with the inbound HTLC has already been determined,
181	/// i.e., we already know whether it must be failed back or forwarded.
182	//
183	// TODO: Once this variant is removed, we should also clean up
184	// [`MonitorRestoreUpdates::accepted_htlcs`] as the path will be unreachable.
185	Resolved { pending_htlc_status: PendingHTLCStatus },
186	/// Pending implies we will attempt to resolve the inbound HTLC once it has been fully committed
187	/// to by both sides of the channel, i.e., once a `revoke_and_ack` has been processed by both
188	/// nodes for the state update in which it was proposed.
189	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	/// Offered by remote, to be included in next local commitment tx. I.e., the remote sent an
204	/// update_add_htlc message for this HTLC.
205	RemoteAnnounced(InboundHTLCResolution),
206	/// Included in a received commitment_signed message (implying we've
207	/// revoke_and_ack'd it), but the remote hasn't yet revoked their previous
208	/// state (see the example below). We have not yet included this HTLC in a
209	/// commitment_signed message because we are waiting on the remote's
210	/// aforementioned state revocation. One reason this missing remote RAA
211	/// (revoke_and_ack) blocks us from constructing a commitment_signed message
212	/// is because every time we create a new "state", i.e. every time we sign a
213	/// new commitment tx (see [BOLT #2]), we need a new per_commitment_point,
214	/// which are provided one-at-a-time in each RAA. E.g., the last RAA they
215	/// sent provided the per_commitment_point for our current commitment tx.
216	/// The other reason we should not send a commitment_signed without their RAA
217	/// is because their RAA serves to ACK our previous commitment_signed.
218	///
219	/// Here's an example of how an HTLC could come to be in this state:
220	/// remote --> update_add_htlc(prev_htlc)   --> local
221	/// remote --> commitment_signed(prev_htlc) --> local
222	/// remote <-- revoke_and_ack               <-- local
223	/// remote <-- commitment_signed(prev_htlc) <-- local
224	/// [note that here, the remote does not respond with a RAA]
225	/// remote --> update_add_htlc(this_htlc)   --> local
226	/// remote --> commitment_signed(prev_htlc, this_htlc) --> local
227	/// Now `this_htlc` will be assigned this state. It's unable to be officially
228	/// accepted, i.e. included in a commitment_signed, because we're missing the
229	/// RAA that provides our next per_commitment_point. The per_commitment_point
230	/// is used to derive commitment keys, which are used to construct the
231	/// signatures in a commitment_signed message.
232	/// Implies AwaitingRemoteRevoke.
233	///
234	/// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
235	AwaitingRemoteRevokeToAnnounce(InboundHTLCResolution),
236	/// Included in a received commitment_signed message (implying we've revoke_and_ack'd it).
237	/// We have also included this HTLC in our latest commitment_signed and are now just waiting
238	/// on the remote's revoke_and_ack to make this HTLC an irrevocable part of the state of the
239	/// channel (before it can then get forwarded and/or removed).
240	/// Implies AwaitingRemoteRevoke.
241	AwaitingAnnouncedRemoteRevoke(InboundHTLCResolution),
242	/// An HTLC irrevocably committed in the latest commitment transaction, ready to be forwarded or
243	/// removed.
244	Committed {
245		/// Used to rebuild `ChannelManager` HTLC state on restart. Previously the manager would track
246		/// and persist all HTLC forwards and receives itself, but newer LDK versions avoid relying on
247		/// its persistence and instead reconstruct state based on `Channel` and `ChannelMonitor` data.
248		update_add_htlc: InboundUpdateAdd,
249	},
250	/// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we
251	/// created it we would have put it in the holding cell instead). When they next revoke_and_ack
252	/// we'll drop it.
253	/// Note that we have to keep an eye on the HTLC until we've received a broadcastable
254	/// commitment transaction without it as otherwise we'll have to force-close the channel to
255	/// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim
256	/// anyway). That said, ChannelMonitor does this for us (see
257	/// ChannelMonitor::should_broadcast_holder_commitment_txn) so we actually remove the HTLC from
258	/// our own local state before then, once we're sure that the next commitment_signed and
259	/// ChannelMonitor::provide_latest_local_commitment_tx will not include this HTLC.
260	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	/// Whether we need to hold onto this HTLC until receipt of a corresponding [`ReleaseHeldHtlc`]
321	/// onion message.
322	///
323	/// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc
324	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/// Information about the outbound hop for a forwarded HTLC. Useful for generating an accurate
340/// [`Event::PaymentForwarded`] if we need to claim this HTLC post-restart.
341///
342/// [`Event::PaymentForwarded`]: crate::events::Event::PaymentForwarded
343#[derive(Debug, Copy, Clone)]
344pub(super) struct OutboundHop {
345	/// The amount forwarded outbound.
346	pub(super) amt_msat: u64,
347	/// The outbound channel this HTLC was forwarded over.
348	pub(super) channel_id: ChannelId,
349	/// The next-hop recipient of this HTLC.
350	pub(super) node_id: PublicKey,
351	/// The outbound channel's funding outpoint.
352	pub(super) funding_txo: OutPoint,
353	/// The outbound channel's user channel ID.
354	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/// A field of `InboundHTLCState::Committed` containing the HTLC's `update_add_htlc` message. If
366/// the HTLC is a forward and gets irrevocably committed to the outbound edge, we convert to
367/// `InboundUpdateAdd::Forwarded`, thus pruning the onion and not persisting it on every
368/// `ChannelManager` persist.
369///
370/// Useful for reconstructing the pending HTLC set on startup.
371#[derive(Debug, Clone)]
372enum InboundUpdateAdd {
373	/// The inbound committed HTLC's update_add_htlc message.
374	WithOnion { update_add_htlc: msgs::UpdateAddHTLC },
375	/// This inbound HTLC is a forward that was irrevocably committed to the outbound edge, allowing
376	/// its onion to be pruned and no longer persisted.
377	///
378	/// Contains data that is useful if we need to fail or claim this HTLC backwards after a restart
379	/// and it's missing in the outbound edge.
380	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	/// This HTLC was received before we started persisting the onion for inbound committed HTLCs.
388	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	/// Added by us and included in a commitment_signed (if we were AwaitingRemoteRevoke when we
421	/// created it we would have put it in the holding cell instead). When they next revoke_and_ack
422	/// we will promote to Committed (note that they may not accept it until the next time we
423	/// revoke, but we don't really care about that:
424	///  * they've revoked, so worst case we can announce an old state and get our (option on)
425	///    money back (though we won't), and,
426	///  * we'll send them a revoke when they send a commitment_signed, and since only they're
427	///    allowed to remove it, the "can only be removed once committed on both sides" requirement
428	///    doesn't matter to us and it's up to them to enforce it, worst-case they jump ahead but
429	///    we'll never get out of sync).
430	/// Note that we Box the OnionPacket as it's rather large and we don't want to blow up
431	/// OutboundHTLCOutput's size just for a temporary bit
432	LocalAnnounced(Box<msgs::OnionPacket>),
433	Committed,
434	/// Remote removed this (outbound) HTLC. We're waiting on their commitment_signed to finalize
435	/// the change (though they'll need to revoke before we fail the payment).
436	RemoteRemoved(OutboundHTLCOutcome),
437	/// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but
438	/// the remote side hasn't yet revoked their previous state, which we need them to do before we
439	/// can do any backwards failing. Implies AwaitingRemoteRevoke.
440	/// We also have not yet removed this HTLC in a commitment_signed message, and are waiting on a
441	/// remote revoke_and_ack on a previous state before we can do so.
442	AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome),
443	/// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but
444	/// the remote side hasn't yet revoked their previous state, which we need them to do before we
445	/// can do any backwards failing. Implies AwaitingRemoteRevoke.
446	/// We have removed this HTLC in our latest commitment_signed and are now just waiting on a
447	/// revoke_and_ack to drop completely.
448	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			// RemoteRemoved states are ignored as the state is transient and the remote has not committed to
459			// the state yet.
460			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	/// We started always filling in the preimages here in 0.0.105, and the requirement
521	/// that the preimages always be filled in was added in 0.2.
522	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/// See AwaitingRemoteRevoke ChannelState for more info
555#[derive(Debug)]
556#[cfg_attr(test, derive(Clone, PartialEq))]
557enum HTLCUpdateAwaitingACK {
558	AddHTLC {
559		// TODO: Time out if we're getting close to cltv_expiry
560		// always outbound
561		amount_msat: u64,
562		cltv_expiry: u32,
563		payment_hash: PaymentHash,
564		source: HTLCSource,
565		onion_routing_packet: msgs::OnionPacket,
566		// The extra fee we're skimming off the top of this HTLC.
567		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			/// All flags that apply to the specified [`ChannelState`] variant.
601			#[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
693/// We declare all the states/flags here together to help determine which bits are still available
694/// to choose.
695mod 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// Note that the order of this enum is implicitly defined by where each variant is placed. Take this
797// into account when introducing new states and update `test_channel_state_order` accordingly.
798#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq)]
799enum ChannelState {
800	/// We are negotiating the parameters required for the channel prior to funding it.
801	NegotiatingFunding(NegotiatingFundingFlags),
802	/// We have sent `funding_created` and are awaiting a `funding_signed` to advance to
803	/// `AwaitingChannelReady`. Note that this is nonsense for an inbound channel as we immediately generate
804	/// `funding_signed` upon receipt of `funding_created`, so simply skip this state.
805	///
806	/// For inbound and outbound interactively funded channels (dual-funding), this state indicates
807	/// that interactive transaction construction has been completed and we are now interactively
808	/// signing the initial funding transaction.
809	FundingNegotiated(FundingNegotiatedFlags),
810	/// We've received/sent `funding_created` and `funding_signed` and are thus now waiting on the
811	/// funding transaction to confirm.
812	AwaitingChannelReady(AwaitingChannelReadyFlags),
813	/// Both we and our counterparty consider the funding transaction confirmed and the channel is
814	/// now operational.
815	ChannelReady(ChannelReadyFlags),
816	/// We've successfully negotiated a `closing_signed` dance. At this point, the `ChannelManager`
817	/// is about to drop us, but we store this anyway.
818	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
991/// The percentage of the channel value `holder_max_htlc_value_in_flight_msat` used to be set to,
992/// before this was made configurable. The percentage was made configurable in LDK 0.0.107,
993/// although LDK 0.0.104+ enabled serialization of channels with a different value set for
994/// `holder_max_htlc_value_in_flight_msat`.
995pub const MAX_IN_FLIGHT_PERCENT_LEGACY: u8 = 10;
996
997/// Maximum `funding_satoshis` value according to the BOLT #2 specification, if
998/// `option_support_large_channel` (aka wumbo channels) is not supported.
999/// It's 2^24 - 1.
1000pub const MAX_FUNDING_SATOSHIS_NO_WUMBO: u64 = (1 << 24) - 1;
1001
1002/// Total bitcoin supply in satoshis.
1003pub const TOTAL_BITCOIN_SUPPLY_SATOSHIS: u64 = 21_000_000 * 1_0000_0000;
1004
1005/// The maximum network dust limit for standard script formats. This currently represents the
1006/// minimum output value for a P2SH output before Bitcoin Core 22 considers the entire
1007/// transaction non-standard and thus refuses to relay it.
1008/// We also use this as the maximum counterparty `dust_limit_satoshis` allowed, given many
1009/// implementations use this value for their dust limit today.
1010pub const MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS: u64 = 546;
1011
1012/// The maximum channel dust limit we will accept from our counterparty for non-anchor channels.
1013pub const MAX_LEGACY_CHAN_DUST_LIMIT_SATOSHIS: u64 = MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS;
1014
1015/// The maximum channel dust limit we will accept from our counterparty.
1016pub const MAX_CHAN_DUST_LIMIT_SATOSHIS: u64 = 10_000;
1017
1018/// The dust limit is used for both the commitment transaction outputs as well as the closing
1019/// transactions. For cooperative closing transactions, we require segwit outputs, though accept
1020/// *any* segwit scripts, which are allowed to be up to 42 bytes in length.
1021/// In order to avoid having to concern ourselves with standardness during the closing process, we
1022/// simply require our counterparty to use a dust limit which will leave any segwit output
1023/// standard.
1024/// See <https://github.com/lightning/bolts/issues/905> for more details.
1025pub const MIN_CHAN_DUST_LIMIT_SATOSHIS: u64 = 354;
1026
1027// Just a reasonable implementation-specific safe lower bound, higher than the dust limit.
1028pub const MIN_THEIR_CHAN_RESERVE_SATOSHIS: u64 = 1000;
1029
1030// Just a reasonable implementation-specific safe lower bound.
1031pub const MIN_CHANNEL_VALUE_SATOSHIS: u64 = 1000;
1032
1033/// Used to return a simple Error back to ChannelManager. Will get converted to a
1034/// msgs::ErrorAction::SendErrorMessage or msgs::ErrorAction::IgnoreError as appropriate with our
1035/// channel_id in ChannelManager.
1036pub(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/// The "channel disabled" bit in channel_update must be set based on whether we are connected to
1118/// our counterparty or not. However, we don't want to announce updates right away to avoid
1119/// spamming the network with updates if the connection is flapping. Instead, we "stage" updates to
1120/// our channel_update message and track the current state here.
1121/// See implementation at [`super::channelmanager::ChannelManager::timer_tick_occurred`].
1122#[derive(Clone, Copy, PartialEq, Debug)]
1123pub(super) enum ChannelUpdateStatus {
1124	/// We've announced the channel as enabled and are connected to our peer.
1125	Enabled,
1126	/// Our channel is no longer live, but we haven't announced the channel as disabled yet.
1127	DisabledStaged(u8),
1128	/// Our channel is live again, but we haven't announced the channel as enabled yet.
1129	EnabledStaged(u8),
1130	/// We've announced the channel as disabled.
1131	Disabled,
1132}
1133
1134/// We track when we sent an `AnnouncementSignatures` to our peer in a few states, described here.
1135#[cfg_attr(test, derive(Debug))]
1136#[derive(PartialEq)]
1137pub enum AnnouncementSigsState {
1138	/// We have not sent our peer an `AnnouncementSignatures` yet, or our peer disconnected since
1139	/// we sent the last `AnnouncementSignatures`.
1140	NotSent,
1141	/// We sent an `AnnouncementSignatures` to our peer since the last time our peer disconnected.
1142	/// This state never appears on disk - instead we write `NotSent`.
1143	MessageSent,
1144	/// We sent a `CommitmentSigned` after the last `AnnouncementSignatures` we sent. Because we
1145	/// only ever have a single `CommitmentSigned` pending at once, if we sent one after sending
1146	/// `AnnouncementSignatures` then we know the peer received our `AnnouncementSignatures` if
1147	/// they send back a `RevokeAndACK`.
1148	/// This state never appears on disk - instead we write `NotSent`.
1149	Committed,
1150	/// We received a `RevokeAndACK`, effectively ack-ing our `AnnouncementSignatures`, at this
1151	/// point we no longer need to re-send our `AnnouncementSignatures` again on reconnect.
1152	PeerReceived,
1153}
1154
1155/// A struct gathering data on a commitment, either local or remote.
1156struct CommitmentData<'a> {
1157	tx: CommitmentTransaction,
1158	htlcs_included: Vec<(HTLCOutputInCommitment, Option<&'a HTLCSource>)>, // the list of HTLCs (dust HTLCs *included*) which were not ignored when building the transaction
1159	outbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful offered HTLCs since last commitment
1160	inbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful received HTLCs since last commitment
1161}
1162
1163/// A struct gathering stats on a commitment transaction, either local or remote.
1164#[derive(Debug, PartialEq)]
1165pub(crate) struct CommitmentStats {
1166	/// The total fee included in the commitment transaction
1167	pub commit_tx_fee_sat: u64,
1168	/// The local balance before fees *not* considering dust limits
1169	pub local_balance_before_fee_msat: u64,
1170	/// The remote balance before fees *not* considering dust limits
1171	pub remote_balance_before_fee_msat: u64,
1172}
1173
1174/// A return value enum for get_update_fulfill_htlc. See UpdateFulfillCommitFetch variants for
1175/// description
1176enum UpdateFulfillFetch {
1177	NewClaim { monitor_update: ChannelMonitorUpdate, htlc_value_msat: u64, update_blocked: bool },
1178	DuplicateClaim {},
1179}
1180
1181/// The return type of get_update_fulfill_htlc_and_commit.
1182pub enum UpdateFulfillCommitFetch {
1183	/// Indicates the HTLC fulfill is new, and either generated an update_fulfill message, placed
1184	/// it in the holding cell, or re-generated the update_fulfill message after the same claim was
1185	/// previously placed in the holding cell (and has since been removed).
1186	NewClaim {
1187		/// The ChannelMonitorUpdate which places the new payment preimage in the channel monitor
1188		monitor_update: ChannelMonitorUpdate,
1189		/// The value of the HTLC which was claimed, in msat.
1190		htlc_value_msat: u64,
1191	},
1192	/// Indicates the HTLC fulfill is duplicative and already existed either in the holding cell
1193	/// or has been forgotten (presumably previously claimed).
1194	DuplicateClaim {},
1195}
1196
1197/// Error returned when processing an invalid interactive-tx message from our counterparty.
1198pub(super) struct InteractiveTxMsgError {
1199	/// The underlying error.
1200	pub(super) err: ChannelError,
1201	/// If a splice was in progress when processing the message, this contains the splice funding
1202	/// information for emitting a `SpliceNegotiationFailed` event.
1203	pub(super) splice_funding_failed: Option<SpliceFundingFailed>,
1204	/// The event reason to use if this error causes a `SpliceNegotiationFailed` event.
1205	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
1235/// The return value of `monitor_updating_restored`
1236pub(super) struct MonitorRestoreUpdates {
1237	pub raa: Option<msgs::RevokeAndACK>,
1238	/// A `CommitmentUpdate` to be sent to our channel peer.
1239	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	/// Inbound update_adds that are now irrevocably committed to this channel and are ready for the
1245	/// onion to be processed in order to forward or receive the HTLC.
1246	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	/// The sources of outbound HTLCs that were forwarded and irrevocably committed on this channel
1253	/// (the outbound edge), along with their outbound amounts. Useful to store in the inbound HTLC
1254	/// to ensure it gets resolved.
1255	pub committed_outbound_htlc_sources: Vec<(HTLCPreviousHopData, u64)>,
1256	/// Whether the restoration changed serialized channel state that needs ChannelManager
1257	/// persistence.
1258	pub requires_channel_manager_persistence: bool,
1259}
1260
1261/// The return value of `signer_maybe_unblocked`
1262pub(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
1277/// The return value of `channel_reestablish`
1278pub(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
1292/// The first message we send to our peer after connection
1293pub(super) enum ReconnectionMsg {
1294	Reestablish(msgs::ChannelReestablish),
1295	Open(OpenChannelMessage),
1296	None,
1297}
1298
1299/// The result of a shutdown that should be handled.
1300#[must_use]
1301pub(crate) struct ShutdownResult {
1302	pub(crate) closure_reason: ClosureReason,
1303	/// A channel monitor update to apply.
1304	pub(crate) monitor_update: Option<(PublicKey, OutPoint, ChannelId, ChannelMonitorUpdate)>,
1305	/// A list of dropped outbound HTLCs that can safely be failed backwards immediately.
1306	pub(crate) dropped_outbound_htlcs: Vec<(HTLCSource, PaymentHash, PublicKey, ChannelId)>,
1307	/// An unbroadcasted batch funding transaction id. The closure of this channel should be
1308	/// propagated to the remainder of the batch.
1309	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	/// If any splices were in progress when the channel was shut down, this contains
1319	/// the splice funding information for emitting SpliceNegotiationFailed events. Both an
1320	/// active negotiation round and a contribution queued for a later round may fail at once.
1321	pub(crate) splice_funding_failed: Vec<SpliceFundingFailed>,
1322	/// A splice pending at closure because our funding signatures are ready to send.
1323	pub(crate) splice_funding_negotiated: Option<SpliceFundingNegotiated>,
1324}
1325
1326/// The result of a peer disconnection.
1327pub(crate) struct DisconnectResult {
1328	pub(crate) is_resumable: bool,
1329	/// If a splice was in progress when the channel was shut down, this contains
1330	/// the splice funding information for emitting a SpliceNegotiationFailed event.
1331	pub(crate) splice_funding_failed: Option<SpliceFundingFailed>,
1332}
1333
1334/// Tracks the transaction number, along with current and next commitment points.
1335/// This consolidates the logic to advance our commitment number and request new
1336/// commitment points from our signer.
1337#[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	// Track the two latest revoked points such that we no longer need to reach a potentially async
1345	// signer on channel reestablish. We would otherwise need to retrieve one or both of these
1346	// points from the signer to verify the received
1347	// [`msgs::ChannelReestablish::your_last_per_commitment_secret`].
1348	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	/// If we are pending advancing the next commitment point, this method tries asking the signer
1394	/// again.
1395	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	/// If we are not pending the next commitment point, this method advances the commitment number
1419	/// and requests the next commitment point from the signer. Returns `Ok` if we were able to
1420	/// advance our commitment number (even if we are still pending the next commitment point).
1421	///
1422	/// If our signer is not ready to provide the next commitment point, we will advance but won't
1423	/// be able to advance again immediately. Instead, this hould be tried again later in
1424	/// `signer_unblocked` via `try_resolve_pending`.
1425	///
1426	/// If our signer is ready to provide the next commitment point, the next call to `advance` will
1427	/// succeed.
1428	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/// If the majority of the channels funds are to the fundee and the initiator holds only just
1449/// enough funds to cover their reserve value, channels are at risk of getting "stuck". Because the
1450/// initiator controls the feerate, if they then go to increase the channel fee, they may have no
1451/// balance but the fundee is unable to send a payment as the increase in fee more than drains
1452/// their reserve value. Thus, neither side can send a new HTLC and the channel becomes useless.
1453/// Thus, before sending an HTLC when we are the initiator, we check that the feerate can increase
1454/// by this multiple without hitting this case, before sending.
1455/// This multiple is effectively the maximum feerate "jump" we expect until more HTLCs flow over
1456/// the channel. Sadly, there isn't really a good number for this - if we expect to have no new
1457/// HTLCs for days we may need this to suffice for feerate increases across days, but that may
1458/// leave the channel less usable as we hold a bigger reserve.
1459#[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
1464/// If we fail to see a funding transaction confirmed on-chain within this many blocks after the
1465/// channel creation on an inbound channel, we simply force-close and move on.
1466/// This constant is the one suggested in BOLT 2.
1467pub(crate) const FUNDING_CONF_DEADLINE_BLOCKS: u32 = 2016;
1468
1469/// In case of a concurrent update_add_htlc proposed by our counterparty, we might
1470/// not have enough balance value remaining to cover the onchain cost of this new
1471/// HTLC weight. If this happens, our counterparty fails the reception of our
1472/// commitment_signed including this new HTLC due to infringement on the channel
1473/// reserve.
1474/// To prevent this case, we compute our outbound update_fee with an HTLC buffer of
1475/// size 2. However, if the number of concurrent update_add_htlc is higher, this still
1476/// leads to a channel force-close. Ultimately, this is an issue coming from the
1477/// design of LN state machines, allowing asynchronous updates.
1478pub(crate) const CONCURRENT_INBOUND_HTLC_FEE_BUFFER: u32 = 2;
1479
1480/// When a channel is opened, we check that the funding amount is enough to pay for relevant
1481/// commitment transaction fees, with at least this many HTLCs present on the commitment
1482/// transaction (not counting the value of the HTLCs themselves).
1483pub(crate) const MIN_AFFORDABLE_HTLC_COUNT: usize = 4;
1484
1485/// When a [`FundedChannel`] has its [`ChannelConfig`] updated, its existing one is stashed for up
1486/// to this number of ticks to allow forwarding HTLCs by nodes that have yet to receive the new
1487/// ChannelUpdate prompted by the config update. This value was determined as follows:
1488///
1489///   * The expected interval between ticks (1 minute).
1490///   * The average convergence delay of updates across the network, i.e., ~300 seconds on average
1491///    for a node to see an update as seen on `<https://arxiv.org/pdf/2205.12737.pdf>`.
1492///   * `EXPIRE_PREV_CONFIG_TICKS` = convergence_delay / tick_interval
1493pub(crate) const EXPIRE_PREV_CONFIG_TICKS: usize = 5;
1494
1495/// The number of ticks that may elapse while we're waiting for a response before we attempt to
1496/// disconnect them.
1497///
1498/// See [`ChannelContext::sent_message_awaiting_response`] for more information.
1499pub(crate) const DISCONNECT_PEER_AWAITING_RESPONSE_TICKS: usize = 2;
1500
1501/// The number of ticks that may elapse while we're waiting for an unfunded outbound/inbound channel
1502/// to be promoted to a [`FundedChannel`] since the unfunded channel was created. An unfunded channel
1503/// exceeding this age limit will be force-closed and purged from memory.
1504pub(crate) const UNFUNDED_CHANNEL_AGE_LIMIT_TICKS: usize = 60;
1505
1506/// Number of blocks needed for an output from a coinbase transaction to be spendable.
1507pub(crate) const COINBASE_MATURITY: u32 = 100;
1508
1509/// The number of blocks to wait for a channel_announcement to propagate such that payments using an
1510/// older SCID can still be relayed. Once the spend of the previous funding transaction has reached
1511/// this number of confirmations, the corresponding SCID will be forgotten.
1512///
1513/// Because HTLCs added prior to 0.1 which were waiting to be failed may reference a channel's
1514/// pre-splice SCID, we need to ensure this is at least the maximum number of blocks before an HTLC
1515/// gets failed-back due to a time-out. Luckily, in LDK prior to 0.2, this is enforced directly
1516/// when checking the incoming HTLC, and compared against `CLTV_FAR_FAR_AWAY` (which prior to LDK
1517/// 0.2, and still at the time of writing, is 14 * 24 * 6, i.e. two weeks).
1518///
1519/// Here we use four times that value to give us more time to fail an HTLC back (which does require
1520/// the user call [`ChannelManager::process_pending_htlc_forwards`]) just in case (if an HTLC has
1521/// been expired for 3 * 2 weeks our counterparty really should have closed the channel by now).
1522/// Holding on to stale SCIDs doesn't really cost us much as each one costs an on-chain splice to
1523/// generate anyway, so we might as well make this nearly arbitrarily long.
1524///
1525/// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1526#[cfg(not(test))]
1527pub(crate) const CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY: u32 = 14 * 24 * 6 * 4;
1528
1529/// In test (not `_test_utils`, though, since that tests actual upgrading), we deliberately break
1530/// the above condition so that we can ensure that HTLCs forwarded in 0.2 or later are handled
1531/// correctly even if this constant is reduced and an HTLC can outlive the original channel's SCID.
1532#[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
1544/// A payment channel with a counterparty throughout its life-cycle, encapsulating negotiation and
1545/// funding phases.
1546pub(super) struct Channel<SP: SignerProvider> {
1547	phase: ChannelPhase<SP>,
1548}
1549
1550/// The `ChannelPhase` enum describes the current phase in life of a lightning channel with each of
1551/// its variants containing an appropriate channel struct.
1552enum 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	/// Returns true if this channel is waiting on a (batch) funding transaction to be provided.
1665	///
1666	/// If this method returns true, [`Self::into_unfunded_outbound_v1`] will also succeed.
1667	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	/// Should be called when the peer is disconnected. Returns true if the channel can be resumed
1750	/// when the peer reconnects (via [`Self::peer_connected_get_handshake`]). If not, the channel
1751	/// must be immediately closed.
1752	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			// If we get disconnected and haven't yet committed to a funding
1759			// transaction, we can replay the `open_channel` on reconnection, so don't
1760			// bother dropping the channel here. However, if we already committed to
1761			// the funding transaction we don't yet support replaying the funding
1762			// handshake (and bailing if the peer rejects it), so we force-close in
1763			// that case.
1764			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			// Reset any quiescence-related state as it is implicitly terminated once disconnected.
1771			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					// If there was a pending splice negotiation that failed due to disconnecting, we
1776					// also take the opportunity to clean up our state.
1777					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					// We shouldn't be quiescent anymore upon reconnecting if:
1784					// - We were in quiescence but a splice/RBF was never negotiated or
1785					// - We were in quiescence but the splice negotiation failed due to disconnecting
1786					//
1787					// NOTE: While `exit_quiescence` clears the disconnect timer, it should already
1788					// have been cleared by `remove_uncommitted_htlcs_and_mark_paused`.
1789					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	/// Should be called when the peer re-connects, returning an initial message which we should
1815	/// send our peer to begin the channel reconnection process.
1816	#[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				// Since unfunded inbound channel maps are cleared upon disconnecting a peer,
1831				// they are not persisted and won't be recovered after a crash.
1832				// Therefore, they shouldn't exist at this point.
1833				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					// Since unfunded inbound channel maps are cleared upon disconnecting a peer,
1843					// they are not persisted and won't be recovered after a crash.
1844					// Therefore, they shouldn't exist at this point.
1845					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		// If we have not sent a `tx_abort` message for this negotiation previously, we need to echo
2037		// back a tx_abort message according to the spec:
2038		//   https://github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L560-L561
2039		// For rationale why we echo back `tx_abort`:
2040		//   https://github.com/lightning/bolts/blob/247e83d/02-peer-protocol.md?plain=1#L578-L580
2041		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					// We only force close once the counterparty tries to abort after committing to
2062					// the splice via their initial `commitment_signed`. This is because our monitor
2063					// state is updated with the post-splice commitment transaction upon receiving
2064					// their `commitment_signed`, so we would need another monitor update to abandon
2065					// it, which we don't currently support.
2066					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					// We were not tracking the pending funding negotiation state anymore, likely
2083					// due to a disconnection or already having sent our own `tx_abort`.
2084					(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						// Replace the taken state for later error handling
2181						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				// We may be handling a duplicate call and the funding was already locked so we
2254				// no longer have the signing session present.
2255				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		// If we have a pending splice with a buffered initial commitment signed from our
2330		// counterparty, process it now that we have provided our signatures.
2331		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		// For zero conf channels, we don't expect the funding transaction to be ready for broadcast
2358		// yet as, according to the spec, our counterparty shouldn't have sent their `tx_signatures`
2359		// without us having sent our initial commitment signed to them first. However, in the event
2360		// they do, we choose to handle it anyway. Note that because of this behavior not being
2361		// spec-compliant, we're not able to test this without custom logic.
2362		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						// TODO(dual_funding): Add async signing support.
2395						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					// TODO: Change to `inspect_err` when MSRV is high enough.
2410					.map_err(|err| {
2411						// We always expect a `ChannelError` close.
2412						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					// Not having a signing session implies they've already sent `splice_locked`,
2432					// which must always come after the initial commitment signed is sent.
2433					.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					// We delay processing this until the user manually approves the splice via
2443					// [`Channel::funding_transaction_signed`], as otherwise, it would prevent the
2444					// user from canceling their contribution if they no longer wish to proceed.
2445					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	/// Gets the available balances, see [`AvailableBalances`]'s fields for more info.
2479	///
2480	/// Returns `Err` if some party cannot currently pay for the HTLCs outbound from said party, and the anchors and
2481	/// transaction fee if they are the funder.
2482	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
2541/// Contains all state common to unfunded inbound/outbound channels.
2542pub(super) struct UnfundedChannelContext {
2543	/// A counter tracking how many ticks have elapsed since this unfunded channel was
2544	/// created. If this unfunded channel reaches peer has yet to respond after reaching
2545	/// `UNFUNDED_CHANNEL_AGE_LIMIT_TICKS`, it will be force-closed and purged from memory.
2546	///
2547	/// This is so that we don't keep channels around that haven't progressed to a funded state
2548	/// in a timely manner.
2549	unfunded_channel_age_ticks: usize,
2550	/// Tracks the commitment number and commitment point before the channel is funded.
2551	holder_commitment_point: Option<HolderCommitmentPoint>,
2552}
2553
2554impl UnfundedChannelContext {
2555	/// Determines whether we should force-close and purge this unfunded channel from memory due to it
2556	/// having reached the unfunded channel age limit.
2557	///
2558	/// This should be called on every [`super::channelmanager::ChannelManager::timer_tick_occurred`].
2559	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/// Information pertaining to an attempt at funding the channel. This is typically constructed
2573/// during channel establishment and may be replaced during channel splicing or if the attempted
2574/// funding transaction is replaced using tx_init_rbf.
2575#[derive(Debug)]
2576pub(super) struct FundingScope {
2577	value_to_self_msat: u64, // Excluding all pending_htlcs, fees, and anchor outputs
2578
2579	/// minimum channel reserve for self to maintain - set by them.
2580	#[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	/// Max to_local and to_remote outputs in a locally-generated commitment transaction
2592	holder_prev_commitment_tx_balance: Mutex<(u64, u64)>,
2593	#[cfg(debug_assertions)]
2594	/// Max to_local and to_remote outputs in a remote-generated commitment transaction
2595	counterparty_prev_commitment_tx_balance: Mutex<(u64, u64)>,
2596
2597	// We save these values so we can make sure validation of channel updates properly predicts
2598	// what the next commitment transaction fee will be, by comparing the cached values to the
2599	// fee of the transaction generated by `build_commitment_transaction`.
2600	#[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	/// The transaction which funds this channel. Note that for manually-funded channels (i.e.,
2608	/// [`ChannelContext::is_manual_broadcast`] is true) this will be a dummy empty transaction.
2609	funding_transaction: Option<Transaction>,
2610	/// The hash of the block in which the funding transaction was included.
2611	funding_tx_confirmed_in: Option<BlockHash>,
2612	funding_tx_confirmation_height: u32,
2613	short_channel_id: Option<u64>,
2614
2615	/// The minimum number of confirmations before the funding is locked. If set, this will override
2616	/// [`ChannelContext::minimum_depth`].
2617	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	/// Returns the funding_txo we either got from our peer, or were given by
2715	/// get_funding_created.
2716	pub fn get_funding_txo(&self) -> Option<OutPoint> {
2717		self.channel_transaction_parameters.funding_outpoint
2718	}
2719
2720	/// Gets the funding output for this channel, if available.
2721	///
2722	/// When a channel is spliced, this continues to refer to the original funding output (which
2723	/// was spent by the splice transaction) until the splice transaction reaches sufficient
2724	/// confirmations to be locked (and we exchange `splice_locked` messages with our peer).
2725	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	/// Gets the redeemscript for the funding transaction output (ie the funding transaction output
2756	/// pays to get_funding_redeemscript().to_p2wsh()).
2757	/// Panics if called before accept_channel/InboundV1Channel::new
2758	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	/// Gets the channel's type
2771	pub fn get_channel_type(&self) -> &ChannelTypeFeatures {
2772		&self.channel_transaction_parameters.channel_type_features
2773	}
2774
2775	/// Returns the height in which our funding transaction was confirmed.
2776	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	/// Returns the current number of confirmations on the funding transaction.
2786	pub fn get_funding_tx_confirmations(&self, height: u32) -> u32 {
2787		if self.funding_tx_confirmation_height == 0 {
2788			// We either haven't seen any confirmation yet, or observed a reorg.
2789			return 0;
2790		}
2791
2792		height.checked_sub(self.funding_tx_confirmation_height).map_or(0, |c| c + 1)
2793	}
2794
2795	/// Gets the channel's `short_channel_id`.
2796	///
2797	/// Will return `None` if the funding hasn't been confirmed yet.
2798	pub fn get_short_channel_id(&self) -> Option<u64> {
2799		self.short_channel_id
2800	}
2801
2802	/// Constructs a `FundingScope` for splicing a channel.
2803	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			// The 'outbound' attribute doesn't change, even if the splice initiator is the other node
2874			is_outbound_from_holder: channel_parameters.is_outbound_from_holder,
2875			counterparty_parameters: channel_parameters.counterparty_parameters.clone(),
2876			funding_outpoint: None, // filled later
2877			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		// New reserve values are based on the new channel value and are v2-specific
2889		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	/// Returns a `SharedOwnedInput` for using this `FundingScope` as the input to a new splice.
2955	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/// Information about pending attempts at funding a channel. This includes funding currently under
2984/// negotiation and any negotiated attempts waiting enough on-chain confirmations. More than one
2985/// such attempt indicates use of RBF to increase the chances of confirmation.
2986#[derive(Debug)]
2987struct PendingFunding {
2988	funding_negotiation: Option<FundingNegotiation>,
2989
2990	/// Our contribution to the funding negotiation round currently in progress, if we are
2991	/// contributing to it. Set when the round starts, moved into the [`NegotiatedCandidate`]
2992	/// when negotiation completes, and dropped in
2993	/// [`FundedChannel::reset_pending_splice_state`] if the round is abandoned.
2994	///
2995	/// When the counterparty initiates an RBF and a prior round included our contribution, this
2996	/// is set to that contribution adjusted to the new feerate (or the RBF is rejected if the
2997	/// adjustment fails, in which case no round starts). This ensures a splice we contributed to
2998	/// never loses our contribution in subsequent rounds.
2999	negotiation_contribution: Option<FundingContribution>,
3000
3001	/// Funding candidates that have been negotiated but have not reached enough confirmations
3002	/// by both counterparties to have exchanged `splice_locked` and be promoted.
3003	negotiated_candidates: Vec<NegotiatedCandidate>,
3004
3005	/// The funding txid used in the `splice_locked` sent to the counterparty.
3006	sent_funding_txid: Option<Txid>,
3007
3008	/// The funding txid used in the `splice_locked` received from the counterparty.
3009	received_funding_txid: Option<Txid>,
3010
3011	/// The feerate used in the last successfully negotiated funding transaction.
3012	/// Used for validating the minimum feerate increase rule on RBF attempts.
3013	last_funding_feerate_sat_per_1000_weight: Option<u32>,
3014}
3015
3016/// A funding candidate that has been negotiated, together with our contribution, if any, to the
3017/// negotiation round that produced it.
3018#[derive(Debug)]
3019struct NegotiatedCandidate {
3020	funding: FundingScope,
3021
3022	/// Our contribution to the negotiation round that produced this candidate, or `None` if only
3023	/// the counterparty contributed. Once a candidate includes our contribution, every later
3024	/// candidate does as well: RBF rounds carry the contribution forward (possibly adjusted to a
3025	/// new feerate) rather than dropping it, preserving the splice intention.
3026	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		/// The initial [`msgs::CommitmentSigned`] message received for the [`FundingScope`] above.
3050		/// We delay processing this until the user manually approves the splice via
3051		/// [`Channel::funding_transaction_signed`], as otherwise, there would be a
3052		/// [`ChannelMonitorUpdateStep::RenegotiatedFunding`] committed that we would need to undo
3053		/// if they no longer wish to proceed.
3054		///
3055		/// Note that this doesn't need to be done with dual-funded channels as there is no
3056		/// equivalent monitor update for them, and we can just force close the channel.
3057		///
3058		/// This field is not persisted as the message should be resent on reconnections.
3059		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		// The in-flight round's contribution is only written if its negotiation survives
3093		// serialization round trips. It goes in an odd TLV that LDK 0.2 skips (0.2 never tracked
3094		// contributions), so a single in-flight splice we contributed to stays loadable there.
3095		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		// TLV 3 exposes only the first candidate's funding: the single-splice view LDK 0.2
3105		// understands. The authoritative candidate list -- each funding bundled with its
3106		// contribution -- goes in the odd TLV 11, which current reads and 0.2 skips. A single
3107		// non-contributory splice is fully captured by TLV 3 alone, so the bundle is then omitted.
3108		// When a single splice does carry a contribution, 0.2 skips it (and operates the splice
3109		// without it), so it need not block 0.2 from loading.
3110		//
3111		// The even TLV 14 is the only thing that makes 0.2 refuse, and it's written exactly when
3112		// there is more than one negotiation round (RBF) -- the one thing 0.2 cannot operate. The
3113		// odd contribution fields are safe despite being load-bearing for RBF: this gate makes 0.2
3114		// refuse the whole channel in that case, so no reader ever skips them when they matter.
3115		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		// TLV 11 (the candidate list, each funding bundled with its contribution) is authoritative
3158		// when present. It is omitted for a single non-contributory splice (TLV 3 holds its
3159		// funding) and for data written by LDK 0.2 (which only ever wrote TLV 3 and tracked no
3160		// contributions); in both cases the candidates carry no contribution.
3161		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		// An in-flight contribution is only written alongside a surviving negotiation round, so a
3169		// contribution without one is invalid.
3170		if funding_negotiation.is_none() && negotiation_contribution.is_some() {
3171			return Err(DecodeError::InvalidValue);
3172		}
3173		// TLV 14 (the RBF gate) is written exactly when there is more than one negotiation round, so
3174		// pre-RBF readers (LDK 0.2) refuse an RBF they cannot operate. Current reconstructs RBF state
3175		// from the candidate list, but a gate inconsistent with that state is invalid.
3176		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	/// Whether our contributions form a suffix of the negotiated candidates: once a round includes
3292	/// our contribution, every later round carries it forward (so the splice intention is never
3293	/// lost).
3294	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	/// Returns the minimum feerate for RBF attempts given a previous feerate.
3339	///
3340	/// The spec (tx_init_rbf) requires the new feerate to be >= the maximum of 25/24 of the
3341	/// previous feerate and the previous feerate + 25 sat/kwu. The flat +25 sat/kwu increment
3342	/// ensures BIP125's relay requirement of an absolute fee increase is satisfied at low feerates
3343	/// where the multiplicative 25/24 rule alone would be insufficient.
3344	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	/// The minimum feerate a new contribution must pay to replace the pending splice via RBF,
3351	/// derived from the most recent round's feerate:
3352	/// - `last_funding_feerate_sat_per_1000_weight`: from a completed but unlocked negotiation
3353	/// - the `funding_negotiation` feerate: from an in-progress negotiation
3354	///
3355	/// Returns `None` when neither feerate is known. The feerate is only persisted by LDK 0.3+,
3356	/// so its absence means the splice was last written by an older version (negotiated there, or
3357	/// round-tripped 0.3 -> 0.2 -> 0.3), in which case the pending splice cannot be RBF'd.
3358	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	/// After several RBF attempts, checks that the feerate is high enough to confirm. Returns
3367	/// `true` if the feerate is sufficient or the threshold hasn't been reached.
3368	///
3369	/// The spec requires: "MUST set a high enough feerate to ensure quick confirmation."
3370	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	/// The inputs and output scripts committed to this splice's live attempts: the negotiated
3383	/// candidates and any contribution of ours in the round still under negotiation. Every part of
3384	/// a candidate's transaction counts when it stores no contribution of ours.
3385	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					// A candidate stores no contribution of ours when only the counterparty
3396					// contributed, but also when it was read from 0.2 data, which did not record
3397					// contributions. Every part of its transaction counts to cover the latter. Once
3398					// upgrading from 0.2 is no longer supported, only the stored contributions need
3399					// to be consulted.
3400					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	/// Whether `contribution` can wait for the pending candidate to lock and then start a fresh
3420	/// splice. It must not reuse anything committed to the attempts that may confirm first.
3421	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	/// Our most recent contribution across rounds, including any round still under negotiation.
3430	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		// The round currently under negotiation, if any, follows the negotiated candidates.
3455		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		// At most one candidate can confirm, as they all double-spend the same input. A zero-conf
3488		// splice is locked (we send `splice_locked`) before it has any confirmations, so also report
3489		// a candidate we have locked even at zero confirmations.
3490		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			// The `splice_locked` we sent always refers to the confirmed candidate, as it is
3497			// cleared if that candidate is ever unconfirmed by a reorg.
3498			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		// While quiescent, defer locking any candidate. We may be quiescent due to an ongoing
3524		// splice RBF negotiation that is mid-signing. Once its `tx_signatures` is exchanged and
3525		// quiescence terminates, our `splice_locked` is sent on a timer tick.
3526		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
3579/// Wrapper around a [`Transaction`] useful for caching the result of [`Transaction::compute_txid`].
3580struct ConfirmedTransaction<'a> {
3581	tx: &'a Transaction,
3582	txid: Option<Txid>,
3583}
3584
3585impl<'a> ConfirmedTransaction<'a> {
3586	/// Returns the underlying [`Transaction`].
3587	pub fn tx(&self) -> &'a Transaction {
3588		self.tx
3589	}
3590
3591	/// Returns the [`Txid`], computing and caching it if necessary.
3592	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
3603/// Contains everything about the channel including state, and various flags.
3604pub(super) struct ChannelContext<SP: SignerProvider> {
3605	config: LegacyChannelConfig,
3606
3607	// Track the previous `ChannelConfig` so that we can continue forwarding HTLCs that were
3608	// constructed using it. The second element in the tuple corresponds to the number of ticks that
3609	// have elapsed since the update occurred.
3610	prev_config: Option<(ChannelConfig, usize)>,
3611
3612	inbound_handshake_limits_override: Option<ChannelHandshakeLimits>,
3613
3614	user_id: u128,
3615
3616	/// The current channel ID.
3617	channel_id: ChannelId,
3618	/// The temporary channel ID used during channel setup. Value kept even after transitioning to a final channel ID.
3619	/// Will be `None` for channels created prior to 0.0.115.
3620	temporary_channel_id: Option<ChannelId>,
3621	channel_state: ChannelState,
3622
3623	// When we reach max(6 blocks, minimum_depth), we need to send an AnnouncementSigs message to
3624	// our peer. However, we want to make sure they received it, or else rebroadcast it when we
3625	// next connect.
3626	// We do so here, see `AnnouncementSigsSent` for more details on the state(s).
3627	// Note that a number of our tests were written prior to the behavior here which retransmits
3628	// AnnouncementSignatures until after an RAA completes, so the behavior is short-circuited in
3629	// many tests.
3630	#[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	// Our commitment numbers start at 2^48-1 and count down, whereas the ones used in transaction
3644	// generation start at 0 and count up...this simplifies some parts of implementation at the
3645	// cost of others, but should really just be changed.
3646	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	/// When resending CS/RAA messages on channel monitor restoration or on reconnect, we always
3652	/// need to ensure we resend them in the order we originally generated them. Note that because
3653	/// there can only ever be one in-flight CS and/or one in-flight RAA at any time, it is
3654	/// sufficient to simply set this to the opposite of any message we are generating as we
3655	/// generate it. ie when we generate a CS, we set this to RAAFirst as, if there is a pending
3656	/// in-flight RAA to resend, it will have been the first thing we generated, and thus we should
3657	/// send it first.
3658	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	// TODO: If a channel is drop'd, we don't know whether the `ChannelMonitor` is ultimately
3666	// responsible for some of the HTLCs here or not - we don't know whether the update in question
3667	// completed or not. Other than `monitor_pending_failures`, which are handed to the
3668	// `ChannelMonitor` when force-closing, we currently ignore these fields entirely when
3669	// force-closing a channel, but need to handle this somehow or we run the risk of losing HTLCs!
3670	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	/// If we went to send a revoke_and_ack but our signer was unable to give us a signature,
3676	/// we should retry at some point in the future when the signer indicates it may have a
3677	/// signature for us.
3678	///
3679	/// This may also be used to make sure we send a `revoke_and_ack` after a `commitment_signed`
3680	/// if we need to maintain ordering of messages, but are pending the signer on a previous
3681	/// message.
3682	signer_pending_revoke_and_ack: bool,
3683	/// If we went to send a commitment update (ie some messages then [`msgs::CommitmentSigned`])
3684	/// but our signer (initially) refused to give us a signature, we should retry at some point in
3685	/// the future when the signer indicates it may have a signature for us.
3686	///
3687	/// This flag is set in such a case. Note that we don't need to persist this as we'll end up
3688	/// setting it again as a side-effect of [`FundedChannel::channel_reestablish`].
3689	signer_pending_commitment_update: bool,
3690	/// Similar to [`Self::signer_pending_commitment_update`] but we're waiting to send either a
3691	/// [`msgs::FundingCreated`] for an outbound V1 channel, [`msgs::FundingSigned`] for an inbound
3692	/// V1 channel, or [`msgs::CommitmentSigned`] for a V2 channel (dual-funded) or a funded channel
3693	/// with a pending splice.
3694	signer_pending_funding: bool,
3695	/// If we attempted to sign a cooperative close transaction but the signer wasn't ready, then this
3696	/// will be set to `true`.
3697	signer_pending_closing: bool,
3698	/// Similar to [`Self::signer_pending_commitment_update`] but we're waiting to send a
3699	/// [`msgs::ChannelReady`].
3700	signer_pending_channel_ready: bool,
3701	// Upon receiving a [`msgs::ChannelReestablish`] message with a `next_remote_commitment_number`
3702	// indicating that our state may be stale, we set this to the received last-revoked commitment
3703	// number and secret to perform the verification when the signer is ready.
3704	signer_pending_stale_state_verification: Option<(u64, SecretKey)>,
3705
3706	// pending_update_fee is filled when sending and receiving update_fee.
3707	//
3708	// Because it follows the same commitment flow as HTLCs, `FeeUpdateState` is either `Outbound`
3709	// or matches a subset of the `InboundHTLCOutput` variants. It is then updated/used when
3710	// generating new commitment transactions with exactly the same criteria as inbound/outbound
3711	// HTLCs with similar state.
3712	pending_update_fee: Option<(u32, FeeUpdateState)>,
3713	// If a `send_update_fee()` call is made with ChannelState::AwaitingRemoteRevoke set, we place
3714	// it here instead of `pending_update_fee` in the same way as we place outbound HTLC updates in
3715	// `holding_cell_htlc_updates` instead of `pending_outbound_htlcs`. It is released into
3716	// `pending_update_fee` with the same criteria as outbound HTLC updates but can be updated by
3717	// further `send_update_fee` calls, dropping the previous holding cell update entirely.
3718	#[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	/// The timestamp set on our latest `channel_update` message for this channel. It is updated
3727	/// when the channel is updated in ways which may impact the `channel_update` message or when a
3728	/// new block is received, ensuring it's always at least moderately close to the current real
3729	/// time.
3730	update_time_counter: u32,
3731
3732	// (fee_sats, skip_remote_output, fee_range, holder_sig)
3733	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	/// If our counterparty sent us a closing_signed while we were waiting for a `ChannelMonitor`
3738	/// update, we need to delay processing it until later. We do that here by simply storing the
3739	/// closing_signed message and handling it in `maybe_propose_closing_signed`.
3740	pending_counterparty_closing_signed: Option<msgs::ClosingSigned>,
3741
3742	/// The minimum and maximum absolute fee, in satoshis, we are willing to place on the closing
3743	/// transaction. These are set once we reach `closing_negotiation_ready`.
3744	#[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	/// If we remove an HTLC (or fee update), commit, and receive our counterparty's
3750	/// `revoke_and_ack`, we remove all knowledge of said HTLC (or fee update). However, the latest
3751	/// local commitment transaction that we can broadcast still contains the HTLC (or old fee)
3752	/// until we receive a further `commitment_signed`. Thus we are not eligible for initiating the
3753	/// `closing_signed` negotiation if we're expecting a counterparty `commitment_signed`.
3754	///
3755	/// To ensure we don't send a `closing_signed` too early, we track this state here, waiting
3756	/// until we see a `commitment_signed` before doing so.
3757	///
3758	/// We don't bother to persist this - we anticipate this state won't last longer than a few
3759	/// milliseconds, so any accidental force-closes here should be exceedingly rare.
3760	expecting_peer_commitment_signed: bool,
3761
3762	/// Either the height at which this channel was created or the height at which it was last
3763	/// serialized if it was serialized by versions prior to 0.0.103.
3764	/// We use this to close if funding is never broadcasted.
3765	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	/// This flag indicates that it is the user's responsibility to validated and broadcast the
3799	/// funding transaction.
3800	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	/// Once we reach `closing_negotiation_ready`, we set this, indicating if closing_signed does
3813	/// not complete within a single timer tick (one minute), we should force-close the channel.
3814	/// This prevents us from keeping unusable channels around forever if our counterparty wishes
3815	/// to DoS us.
3816	/// Note that this field is reset to false on deserialization to give us a chance to connect to
3817	/// our peer and start the closing_signed negotiation fresh.
3818	closing_signed_in_flight: bool,
3819
3820	/// Our counterparty's channel_announcement signatures provided in announcement_signatures.
3821	/// This can be used to rebroadcast the channel_announcement message later.
3822	announcement_sigs: Option<(Signature, Signature)>,
3823
3824	/// lnd has a long-standing bug where, upon reconnection, if the channel is not yet confirmed
3825	/// they will not send a channel_reestablish until the channel locks in. Then, they will send a
3826	/// channel_ready *before* sending the channel_reestablish (which is clearly a violation of
3827	/// the BOLT specs). We copy c-lightning's workaround here and simply store the channel_ready
3828	/// message until we receive a channel_reestablish.
3829	///
3830	/// See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3831	pub workaround_lnd_bug_4006: Option<msgs::ChannelReady>,
3832
3833	/// The `my_current_funding_locked` txid included in our `channel_reestablish` for the current
3834	/// reconnect, if any. We track this as we cannot tell what was included after we've already
3835	/// sent it, as it's possible it was unconfirmed at the time we sent it, but confirmed shortly
3836	/// after.
3837	funding_locked_txid_sent_in_reestablish: Option<Txid>,
3838
3839	/// An option set when we wish to track how many ticks have elapsed while waiting for a response
3840	/// from our counterparty after entering specific states. If the peer has yet to respond after
3841	/// reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`, a reconnection should be attempted to
3842	/// try to unblock the state machine.
3843	///
3844	/// This behavior was initially motivated by a lnd bug in which we don't receive a message we
3845	/// expect to in a timely manner, which may lead to channels becoming unusable and/or
3846	/// force-closed. An example of such can be found at
3847	/// <https://github.com/lightningnetwork/lnd/issues/7682>.
3848	sent_message_awaiting_response: Option<usize>,
3849
3850	// Our counterparty can offer us SCID aliases which they will map to this channel when routing
3851	// outbound payments. These can be used in invoice route hints to avoid explicitly revealing
3852	// the channel's funding UTXO.
3853	//
3854	// We also use this when sending our peer a channel_update that isn't to be broadcasted
3855	// publicly - allowing them to re-use their map of SCID -> channel for channel_update ->
3856	// associated channel mapping.
3857	//
3858	// We only bother storing the most recent SCID alias at any time, though our counterparty has
3859	// to store all of them.
3860	latest_inbound_scid_alias: Option<u64>,
3861
3862	// We always offer our counterparty a static SCID alias, which we recognize as for this channel
3863	// if we see it in HTLC forwarding instructions. We don't bother rotating the alias given we
3864	// don't currently support node id aliases and eventually privacy should be provided with
3865	// blinded paths instead of simple scid+node_id aliases.
3866	outbound_scid_alias: u64,
3867
3868	/// Short channel ids used by any prior FundingScope. These are maintained such that
3869	/// ChannelManager can look up the channel for any pending HTLCs.
3870	historical_scids: Vec<u64>,
3871
3872	// We track whether we already emitted a `ChannelPending` event.
3873	channel_pending_event_emitted: bool,
3874
3875	// We track whether we already emitted a `FundingTxBroadcastSafe` event.
3876	funding_tx_broadcast_safe_event_emitted: bool,
3877
3878	// We track whether we already emitted an initial `ChannelReady` event.
3879	initial_channel_ready_event_emitted: bool,
3880
3881	/// Some if we initiated to shut down the channel.
3882	local_initiated_shutdown: Option<()>,
3883
3884	/// The unique identifier used to re-derive the private key material for the channel through
3885	/// [`SignerProvider::derive_channel_signer`].
3886	#[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	/// If we can't release a [`ChannelMonitorUpdate`] until some external action completes, we
3892	/// store it here and only release it to the `ChannelManager` once it asks for it.
3893	blocked_monitor_updates: Vec<PendingChannelMonitorUpdate>,
3894
3895	/// The signing session for the current interactive tx construction, if any.
3896	///
3897	/// This is populated when the interactive tx construction phase completes (i.e., upon receiving
3898	/// a consecutive `tx_complete`) and the channel enters the signing phase.
3899	///
3900	/// This field is cleared once our counterparty sends a `channel_ready` or upon splice funding
3901	/// promotion.
3902	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
3912/// A channel struct implementing this trait can receive an initial counterparty commitment
3913/// transaction signature.
3914trait 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		// They sign the holder commitment transaction...
3939		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				// TODO(dual_funding): Update for V2 established channels.
3957				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				// The only error we know how to handle is ChannelError::Close, so we fall over here
3964				// to make sure we don't continue with an inconsistent state.
3965				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		// Now that we're past error-generating stuff, update our local state:
3992
3993		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()); // We have not had any monitor(s) yet to fail update!
3998		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			// We only fail to advance our commitment point/number if we're currently
4007			// waiting for our signer to unblock and provide a commitment point.
4008			// We cannot send accept_channel/open_channel before this has occurred, so if we
4009			// err here by the time we receive funding_created/funding_signed, something has gone wrong.
4010			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		// TODO(RBF): When implementing RBF, the funding_txo passed here must only update
4020		// ChannelMonitorImp::first_confirmed_funding_txo during channel establishment, not splicing
4021		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		// This will return false if `counterparty_parameters` is `None`, but for a `FundedChannel`, it
4116		// should never be `None`.
4117		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		// Now check against optional parameters as set by config...
4233		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		// Convert things into internal flags and prep our state:
4296
4297		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			// Protocol level safety check in place, although it should never happen because
4309			// of `MIN_THEIR_CHAN_RESERVE_SATOSHIS` and `MIN_CHANNEL_VALUE_SATOSHIS`
4310			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		// v1 channel opens set `our_funding_satoshis` to 0, and v2 channel opens set `msg_push_msat` to 0.
4336		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						// Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything
4344						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					// Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel
4356					&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		// TODO(dual_funding): Checks for `funding_feerate_sat_per_1000_weight`?
4405
4406		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		// check if the funder's amount for the initial commitment tx is sufficient
4584		// for full fee payment plus a few HTLCs to ensure the channel will be useful.
4585		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		// While it's reasonable for us to not meet the channel reserve initially (if they don't
4609		// want to push much to us), our counterparty should always have more than our reserve.
4610		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		// This will be updated with the counterparty contribution if this is a dual-funded channel
4631		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, // Filled in in accept_channel
4727			holder_selected_channel_reserve_satoshis,
4728
4729			// We'll add our counterparty's `funding_satoshis` to these max commitment output assertions
4730			// when we receive `accept_channel2`.
4731			#[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				// We'll add our counterparty's `funding_satoshis` when we receive `accept_channel2`.
4756				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			// We'll adjust this to include our counterparty's `funding_satoshis` when we
4834			// receive `accept_channel2`.
4835			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, // Filled in in accept_channel
4853
4854			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	/// Allowed in any state (including after shutdown)
4917	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	/// Gets the fee we'd want to charge for adding an HTLC output to this Channel
4937	/// Allowed in any state (including after shutdown)
4938	pub fn get_outbound_forwarding_fee_base_msat(&self) -> u32 {
4939		self.config.options.forwarding_fee_base_msat
4940	}
4941
4942	/// Returns true if we've ever received a message from the remote end for this Channel
4943	pub fn have_received_message(&self) -> bool {
4944		self.channel_state
4945			> ChannelState::NegotiatingFunding(NegotiatingFundingFlags::OUR_INIT_SENT)
4946	}
4947
4948	/// Returns true if this channel is fully established and not known to be closing.
4949	/// Allowed in any state (including after shutdown)
4950	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	/// shutdown state returns the state of the channel in its various stages of shutdown
4958	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	/// Returns true if this channel is currently available for use. This is a superset of
5005	/// is_usable() and considers things like the channel being temporarily disabled.
5006	/// Allowed in any state (including after shutdown)
5007	pub fn is_live(&self) -> bool {
5008		self.is_usable() && !self.channel_state.is_peer_disconnected()
5009	}
5010
5011	/// Returns true if the peer for this channel is currently connected and we're not waiting on
5012	/// `channel_reestablish` messages to re-init the channel.
5013	pub fn is_connected(&self) -> bool {
5014		!self.channel_state.is_peer_disconnected()
5015	}
5016
5017	/// Returns false if our last broadcasted channel_update message has the "channel disabled" bit set
5018	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	/// Checks whether the channel has any HTLC additions, HTLC removals, or fee updates that have
5027	/// been sent by either side but not yet irrevocably committed on both commitments because we're
5028	/// waiting on a pending monitor update or signer request.
5029	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	/// Checks whether the channel has any HTLC additions, HTLC removals, or fee updates that have
5036	/// been sent by either side but not yet irrevocably committed on both commitments. Holding cell
5037	/// updates are not considered because they haven't been sent to the peer yet.
5038	///
5039	/// This can be used to satisfy quiescence's requirement when sending `stfu`:
5040	///  - MUST NOT send `stfu` if any of the sender's htlc additions, htlc removals
5041	///    or fee updates are pending for either peer.
5042	///
5043	/// Note that it is still possible for an update to be pending that's not captured here due to a
5044	/// pending monitor update or signer request. `is_monitor_or_signer_pending_channel_update`
5045	/// should also be checked in such cases.
5046	#[rustfmt::skip]
5047	fn is_waiting_on_peer_pending_channel_update(&self) -> bool {
5048		// An update from the local/remote node may be pending on the remote/local commitment since
5049		// they are not tracked within our state, so we rely on whether any `commitment_signed` or
5050		// `revoke_and_ack` messages are owed.
5051		//
5052		// We check these flags first as they are more likely to be set.
5053		if self.channel_state.is_awaiting_remote_revoke() || self.expecting_peer_commitment_signed {
5054			return true;
5055		}
5056
5057		// A fee update is pending on either commitment.
5058		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				// An HTLC removal from the local node is pending on the remote commitment.
5066				InboundHTLCState::LocalRemoved(_) => true,
5067				// An HTLC add from the remote node is pending on the local commitment.
5068				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				// An HTLC add from the local node is pending on the remote commitment.
5080				OutboundHTLCState::LocalAnnounced(_) => true,
5081				// An HTLC removal from the remote node is pending on the local commitment.
5082				OutboundHTLCState::RemoteRemoved(_)
5083					| OutboundHTLCState::AwaitingRemoteRevokeToRemove(_)
5084					| OutboundHTLCState::AwaitingRemovedRemoteRevoke(_) => true,
5085			})
5086	}
5087
5088	// Public utilities:
5089
5090	pub fn channel_id(&self) -> ChannelId {
5091		self.channel_id
5092	}
5093
5094	// Return the `temporary_channel_id` used during channel establishment.
5095	//
5096	// Will return `None` for channels created prior to LDK version 0.0.115.
5097	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	/// Gets the "user_id" value passed into the construction of this channel. It has no special
5106	/// meaning and exists only to allow users to have a persistent identifier of a channel.
5107	pub fn get_user_id(&self) -> u128 {
5108		self.user_id
5109	}
5110
5111	/// Allowed in any state (including after shutdown)
5112	pub fn latest_inbound_scid_alias(&self) -> Option<u64> {
5113		self.latest_inbound_scid_alias
5114	}
5115
5116	/// Allowed in any state (including after shutdown)
5117	pub fn outbound_scid_alias(&self) -> u64 {
5118		self.outbound_scid_alias
5119	}
5120
5121	/// Returns the holder signer for this channel.
5122	#[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	/// Only allowed immediately after deserialization if get_outbound_scid_alias returns 0,
5128	/// indicating we were written by LDK prior to 0.0.106 which did not set outbound SCID aliases
5129	/// or prior to any channel actions during `Channel` initialization.
5130	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	/// Performs checks against necessary constraints after receiving either an `accept_channel` or
5136	/// `accept_channel2` message.
5137	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		// Check sanity of message fields:
5149		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		// Now check against optional parameters as set by config...
5239		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						// Peer is signaling upfront_shutdown and has opt-out with a 0-length script. We don't enforce anything
5298						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					// Peer is signaling upfront shutdown but don't opt-out with correct mechanism (a.k.a 0-length script). Peer looks buggy, we fail the channel
5310					&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; // We're done enforcing limits on our peer's handshake now.
5358
5359		Ok(())
5360	}
5361
5362	/// Allowed in any state (including after shutdown)
5363	pub fn get_counterparty_node_id(&self) -> PublicKey {
5364		self.counterparty_node_id
5365	}
5366
5367	/// Allowed in any state (including after shutdown)
5368	pub fn get_holder_htlc_minimum_msat(&self) -> u64 {
5369		self.holder_htlc_minimum_msat
5370	}
5371
5372	/// Allowed in any state (including after shutdown), but will return none before TheirInitSent
5373	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	/// Allowed in any state (including after shutdown)
5378	pub fn get_counterparty_htlc_minimum_msat(&self) -> u64 {
5379		self.counterparty_htlc_minimum_msat
5380	}
5381
5382	/// Allowed in any state (including after shutdown), but will return none before TheirInitSent
5383	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	/// Returns a maximum "sane" fee rate used to reason about our dust exposure.
5400	/// Will be Some if the `channel_type`'s dust exposure depends on its commitment fee rate, and
5401	/// None otherwise.
5402	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	/// Returns the maximum configured dust exposure.
5413	///
5414	/// Uses a default of 1 sat/vbyte if `limiting_feerate_sat_per_kw` is `None` and the dust
5415	/// exposure policy depends on fee rate.
5416	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	/// Returns the previous [`ChannelConfig`] applied to this channel, if any.
5426	pub fn prev_config(&self) -> Option<ChannelConfig> {
5427		self.prev_config.map(|prev_config| prev_config.0)
5428	}
5429
5430	// Checks whether we should emit a `ChannelPending` event.
5431	pub(crate) fn should_emit_channel_pending_event(&mut self) -> bool {
5432		self.is_funding_broadcastable() && !self.channel_pending_event_emitted
5433	}
5434
5435	// Returns whether we already emitted a `ChannelPending` event.
5436	pub(crate) fn channel_pending_event_emitted(&self) -> bool {
5437		self.channel_pending_event_emitted
5438	}
5439
5440	// Returns whether we already emitted a `FundingTxBroadcastSafe` event.
5441	pub(crate) fn funding_tx_broadcast_safe_event_emitted(&self) -> bool {
5442		self.funding_tx_broadcast_safe_event_emitted
5443	}
5444
5445	// Remembers that we already emitted a `ChannelPending` event.
5446	pub(crate) fn set_channel_pending_event_emitted(&mut self) {
5447		self.channel_pending_event_emitted = true;
5448	}
5449
5450	// Checks whether we should emit an initial `ChannelReady` event.
5451	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	// Remembers that we already emitted a `ChannelReady` event.
5456	pub(crate) fn set_initial_channel_ready_event_emitted(&mut self) {
5457		self.initial_channel_ready_event_emitted = true;
5458	}
5459
5460	// Remembers that we already emitted a `FundingTxBroadcastSafe` event.
5461	pub(crate) fn set_funding_tx_broadcast_safe_event_emitted(&mut self) {
5462		self.funding_tx_broadcast_safe_event_emitted = true;
5463	}
5464
5465	/// Tracks the number of ticks elapsed since the previous [`ChannelConfig`] was updated. Once
5466	/// [`EXPIRE_PREV_CONFIG_TICKS`] is reached, the previous config is considered expired and will
5467	/// no longer be considered when forwarding HTLCs.
5468	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	/// Returns the current [`ChannelConfig`] applied to the channel.
5480	pub fn config(&self) -> ChannelConfig {
5481		self.config.options
5482	}
5483
5484	/// Updates the channel's config. A bool is returned indicating whether the config update
5485	/// applied resulted in a new ChannelUpdate message.
5486	#[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			// Update the counter, which backs the ChannelUpdate timestamp, to allow the relay
5495			// policy change to propagate throughout the network.
5496			self.update_time_counter += 1;
5497		}
5498		self.config.options = *config;
5499		did_channel_update
5500	}
5501
5502	/// Marking the channel as manual broadcast is used in order to prevent LDK from automatically
5503	/// broadcasting the funding transaction.
5504	///
5505	/// This is useful if you wish to get hold of the funding transaction before it is broadcasted
5506	/// via [`Event::FundingTxBroadcastSafe`] event.
5507	///
5508	/// [`Event::FundingTxBroadcastSafe`]: crate::events::Event::FundingTxBroadcastSafe
5509	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	/// Returns true if this channel can be resume after a restart, implying its past the initial
5522	/// funding negotiation stages (and any assocated batch channels are similarly past initial
5523	/// funding negotiation).
5524	///
5525	/// This is equivalent to saying the channel can be persisted to disk.
5526	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	/// Returns true if funding_signed was sent/received and the
5535	/// funding transaction has been broadcast if necessary.
5536	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	/// Returns the HTLCs and balance used to evaluate the next local or remote commitment,
5559	/// accounting for when pending peer updates will be acknowledged. Successful HTLC removals
5560	/// excluded from the projection are reflected in the balance.
5561	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		// TODO: HTLC removals are released from the holding cell at the same time
5614		// as HTLC additions, so if HTLC additions are applied here, so should HTLC removals.
5615		// This would allow us to make better use of channel liquidity.
5616		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		// Don't include outbound update_add_htlc's in the holding cell, or those which haven't yet been ACK'ed
5795		// by the counterparty (ie. LocalAnnounced HTLCs)
5796		// Don't include the extra fee spike buffer HTLC in calculations
5797		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		// Check that the remote can afford to pay for this HTLC on-chain at the current
5832		// feerate_per_kw, while maintaining their channel reserve (as required by the spec).
5833		//
5834		// We check holder_selected_channel_reserve_satoshis (we're getting paid, so they have to at least meet
5835		// the reserve_satoshis we told them to always have as direct payment so that they lose
5836		// something if we punish them for broadcasting an old state).
5837		// Note that we don't really care about having a small/no to_remote output in our local
5838		// commitment transactions, as the purpose of the channel reserve is to ensure we can
5839		// punish *them* if they misbehave, so we discount any outbound HTLCs which will not be
5840		// present in the next commitment transaction we send them (at least for fulfilled ones,
5841		// failed ones won't modify value_to_self).
5842		// Note that we will send HTLCs which another instance of rust-lightning would think
5843		// violate the reserve value if we do not do this (as we forget inbound HTLCs from the
5844		// Channel state once they will not be present in the next received commitment
5845		// transaction).
5846		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		// Here we check two things 1) that our local commitment still has at least 1 output
5855		// (particularly relevant in 0-reserve channels), and 2) that the counterparty can
5856		// still afford the fee on our commitment if they are the funder.
5857		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		// Check that we won't be pushed over our dust exposure limit by the feerate increase.
5879		let dust_exposure_limiting_feerate =
5880			self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
5881		// Do not include outbound update_add_htlc's in the holding cell, or those which haven't yet been ACK'ed
5882		// by the counterparty (ie. LocalAnnounced HTLCs)
5883		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 our counterparty updated the channel fee in this commitment transaction, check that
5991		// they can actually afford the new fee now.
5992		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		// Before proposing a feerate update, check that we can actually afford the new fee.
6081		let dust_exposure_limiting_feerate =
6082			self.get_dust_exposure_limiting_feerate(&fee_estimator, funding.get_channel_type());
6083		// Include outbound update_add_htlc's in the holding cell, and those which haven't yet been ACK'ed by
6084		// the counterparty (ie. LocalAnnounced HTLCs)
6085		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		// Note that `stats.commit_tx_fee_sat` accounts for any HTLCs that transition from non-dust to dust
6104		// under a higher feerate (in the case where HTLC-transactions pay endogenous fees).
6105		if remote_stats.commitment_stats.holder_balance_msat
6106			< funding.counterparty_selected_channel_reserve_satoshis.unwrap() * 1000
6107		{
6108			//TODO: auto-close after a number of failures?
6109			log_debug!(logger, "Cannot afford to send new feerate at {}", feerate_per_kw);
6110			return false;
6111		}
6112
6113		// Note, we evaluate pending htlc "preemptive" trimmed-to-dust threshold at the proposed
6114		// `feerate_per_kw`.
6115		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		// The fee spike buffer (an additional nondust HTLC) we keep for the remote if the channel
6159		// is not zero fee. This deviates from the spec because the fee spike buffer requirement
6160		// doesn't exist on the receiver's side, only on the sender's.
6161		let fee_spike_buffer_htlc =
6162			if funding.get_channel_type().supports_anchor_zero_fee_commitments() { 0 } else { 1 };
6163		// While these HTLCs may currently be unknown to our counterparty, they can
6164		// end up in commitments soon. Moreover, we are considering failing a
6165		// single HTLC here, not the entire channel, so we opt to be conservative
6166		// in what we accept to forward.
6167		// Similar reasoning as above
6168		let feerate =
6169			cmp::max(self.feerate_per_kw, self.pending_update_fee.map(|(fee, _)| fee).unwrap_or(0));
6170		// A `None` `HTLCCandidate` is used as in this case because we're already accounting for
6171		// the incoming HTLC as it has been fully committed by both sides.
6172		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			// Note that the total dust exposure includes both the dust HTLCs and the excess mining fees of
6211			// the counterparty commitment transaction
6212			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			// Note that with anchor outputs we are no longer as sensitive to fee spikes, so we don't need
6232			// to account for them.
6233			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				// Note that these match the inclusion criteria when scanning
6272				// pending_inbound_htlcs below.
6273				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	/// Transaction nomenclature is somewhat confusing here as there are many different cases - a
6285	/// transaction is referred to as "a's transaction" implying that a will be able to broadcast
6286	/// the transaction. Thus, b will generally be sending a signature over such a transaction to
6287	/// a, and a can revoke the transaction by providing b the relevant per_commitment_secret. As
6288	/// such, a transaction is generally the result of b increasing the amount paid to a (or adding
6289	/// an HTLC to a).
6290	/// @local is used only to convert relevant internal structures which refer to remote vs local
6291	/// to decide value of outputs and direction of HTLCs.
6292	/// @generated_by_local is used to determine *which* HTLCs to include - noting that the HTLC
6293	/// state may indicate that one peer has informed the other that they'd like to add an HTLC but
6294	/// have not yet committed it. Such HTLCs will only be included in transactions which are being
6295	/// generated by the peer which proposed adding the HTLCs, and thus we need to understand both
6296	/// which peer generated this transaction and "to whom" this transaction flows.
6297	#[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		// # Panics
6365		//
6366		// After all HTLC claims have been accounted for, the local balance MUST remain greater than or equal to 0.
6367
6368		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			// Make sure that the to_self/to_remote is always either past the appropriate
6392			// channel_reserve *or* it is making progress towards it.
6393			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			// This assumes that once our balance rises above the counterparty selected
6400			// reserve, it never drops below again. But we allow our counterparty to
6401			// push us under our reserve when we are the funder and they add a HTLC, as
6402			// this is really their problem. Hence, we only run this assert in tests.
6403			#[cfg(test)]
6404			if _stats.local_balance_before_fee_msat / 1000 < funding.counterparty_selected_channel_reserve_satoshis.unwrap() {
6405				// If the local balance is below the reserve on this new commitment, it MUST be
6406				// greater than or equal to the one on the previous commitment.
6407				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				// If the remote balance is below the reserve on this new commitment, it MUST be
6413				// greater than or equal to the one on the previous commitment.
6414				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		// This populates the HTLC-source table with the indices from the HTLCs in the commitment
6420		// transaction.
6421		//
6422		// This brute-force search is O(n^2) over ~1k HTLCs in the worst case. This case is very
6423		// rare at the moment.
6424		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		// This places the non-dust HTLC-source pairs first, in the order they appear in the
6440		// commitment transaction, followed by the dust HTLC-source pairs.
6441		htlcs_included.sort_unstable_by(|(htlc_a, _), (htlc_b, _)| {
6442			match (htlc_a.transaction_output_index, htlc_b.transaction_output_index) {
6443				// `None` is smaller than `Some`, but we want `Some` ordered before `None` in the vector
6444				(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		// When calculating our exposure to dust HTLCs, we assume that the channel feerate
6464		// may, at any point, increase by at least 10 sat/vB (i.e 2530 sat/kWU) or 25%,
6465		// whichever is higher. This ensures that we aren't suddenly exposed to significantly
6466		// more dust balance if the feerate increases when we have several HTLCs pending
6467		// which are near the dust limit.
6468		let mut feerate_per_kw = self.feerate_per_kw;
6469		// If there's a pending update fee, use it to ensure we aren't under-estimating
6470		// potential feerate updates coming soon.
6471		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	/// Get forwarding information for the counterparty.
6482	pub fn counterparty_forwarding_info(&self) -> Option<CounterpartyForwardingInfo> {
6483		self.counterparty_forwarding_info.clone()
6484	}
6485
6486	/// Returns information on all pending inbound HTLCs.
6487	#[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				// Outbound HTLC.
6511				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	/// Returns information on all pending outbound HTLCs.
6537	#[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						// Note that this likely creates a non-dust HTLC, we could add a check for the
6609						// biggest dust HTLC to make sure we still have a broadcastable commitment in
6610						// that case.
6611						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	/// Returns the transaction if there is a pending funding transaction that is yet to be
6646	/// broadcast.
6647	///
6648	/// Note that if [`Self::is_manual_broadcast`] is true the transaction will be a dummy
6649	/// transaction.
6650	pub fn unbroadcasted_funding(&self, funding: &FundingScope) -> Option<Transaction> {
6651		self.if_unbroadcasted_funding(|| funding.funding_transaction.clone())
6652	}
6653
6654	/// Returns the transaction ID if there is a pending funding transaction that is yet to be
6655	/// broadcast.
6656	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	/// Returns whether the channel is funded in a batch.
6663	pub fn is_batch_funding(&self) -> bool {
6664		self.is_batch_funding.is_some()
6665	}
6666
6667	/// Returns the transaction ID if there is a pending batch funding transaction that is yet to be
6668	/// broadcast.
6669	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	/// Shuts down this Channel (no more calls into this Channel may be made afterwards except
6674	/// those explicitly stated to be alowed after shutdown, e.g. some simple getters).
6675	fn force_shutdown(
6676		&mut self, funding: &FundingScope, mut closure_reason: ClosureReason,
6677	) -> ShutdownResult {
6678		// Note that we MUST only generate a monitor update that indicates force-closure - we're
6679		// called during initialization prior to the chain_monitor in the encompassing ChannelManager
6680		// being fully configured in some cases. Thus, its likely any monitor events we generate will
6681		// be delayed in being processed! See the docs for `ChannelManagerReadArgs` for more.
6682		assert!(!matches!(self.channel_state, ChannelState::ShutdownComplete));
6683
6684		let broadcast = self.is_funding_broadcastable();
6685
6686		// We go ahead and "free" any holding cell HTLCs or HTLCs we haven't yet committed to and
6687		// return them to fail the payment.
6688		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		// Once we're closed, the `ChannelMonitor` is responsible for resolving any remaining
6705		// HTLCs. However, in the specific case of us pushing new HTLC(s) to the counterparty in
6706		// the latest commitment transaction that we haven't actually sent due to a block
6707		// `ChannelMonitorUpdate`, we may have some HTLCs that the `ChannelMonitor` won't know
6708		// about and thus really need to be included in `dropped_outbound_htlcs`.
6709		'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			// We should only generate a closing `ChannelMonitorUpdate` if we already have a
6749			// `ChannelMonitor` for the disk (i.e. `counterparty_next_commitment_transaction_number`
6750			// has been decremented once, which hapens when we generate the initial
6751			// `ChannelMonitor`).  Otherwise, that would imply a channel monitor update before we
6752			// even registered the channel monitor to begin with, which is invalid.
6753			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				// HTLC failures are held until the `ChannelMonitorUpdate` for the counterparty's
6757				// `revoke_and_ack` completes. As they can no longer be released, hand them to the
6758				// `ChannelMonitor` to fail. It may already have been given the revocation, in
6759				// which case it no longer tracks the HTLCs and wouldn't resolve them otherwise.
6760				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	/// Only allowed after [`FundingScope::channel_transaction_parameters`] is set.
6810	#[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		// We sign "counterparty" commitment transaction, allowing them to broadcast the tx if they wish.
6821		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	/// If we receive an error message when attempting to open a channel, it may only be a rejection
6847	/// of the channel type we tried, not of our ability to open any channel at all. We can see if a
6848	/// downgrade of channel features would be possible so that we can still open the channel.
6849	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			// We've exhausted our options
6862			return Err(());
6863		}
6864
6865		// We should never have negotiated `anchors_nonzero_fee_htlc_tx` because it can result in a
6866		// loss of funds.
6867		let channel_type = &funding.channel_transaction_parameters.channel_type_features;
6868		assert!(!channel_type.supports_anchors_nonzero_fee_htlc_tx());
6869
6870		// We support opening a few different types of channels. Try removing our additional
6871		// features one by one until we've either arrived at our default or the counterparty has
6872		// accepted one. Features are un-set for the current channel type or any that come before
6873		// it in our order of preference, allowing us to negotiate the "next best" based on the
6874		// counterparty's remaining features per our ranking in `get_initial_channel_type`.
6875		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			// 0-reserve is not allowed on legacy channels
6893			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	/// Asserts that the commitment tx numbers have not advanced from their initial number.
6904	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		// Use the previous commitment number and point when splicing since they shouldn't change.
6926		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				// We shouldn't expect any HTLCs before `ChannelReady`.
6960				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		// Zero-conf channels always meet the minimum depth.
6985		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		// Check if the transaction is the expected funding transaction, and if it is,
7016		// check that it pays the right amount to the right script.
7017		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						// If we generated the funding transaction and it doesn't match what it
7025						// should, the client is really broken and we should just panic and
7026						// tell them off. That said, because hash collisions happen with high
7027						// probability in fuzzing mode, if we're fuzzing we just close the
7028						// channel and move on.
7029						#[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									// We generated a malleable funding transaction, implying we've
7041									// just exposed ourselves to funds loss to our counterparty.
7042									#[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	/// Returns SCIDs that have been associated with the channel's funding transactions.
7073	pub fn historical_scids(&self) -> &[u64] {
7074		&self.historical_scids[..]
7075	}
7076}
7077
7078// Internal utility functions for channels
7079
7080/// Returns the value to use for `holder_max_htlc_value_in_flight_msat` as a percentage of the
7081/// `channel_value_satoshis` in msat, set through
7082/// [`ChannelHandshakeConfig::announced_channel_max_inbound_htlc_value_in_flight_percentage`]
7083/// or [`ChannelHandshakeConfig::unannounced_channel_max_inbound_htlc_value_in_flight_percentage`]
7084/// depending on the value of [`ChannelHandshakeConfig::announce_for_forwarding`].
7085///
7086/// The effective percentage is lower bounded by 1% and upper bounded by 100%.
7087///
7088/// [`ChannelHandshakeConfig::announced_channel_max_inbound_htlc_value_in_flight_percentage`]: crate::util::config::ChannelHandshakeConfig::announced_channel_max_inbound_htlc_value_in_flight_percentage
7089/// [`ChannelHandshakeConfig::unannounced_channel_max_inbound_htlc_value_in_flight_percentage`]: crate::util::config::ChannelHandshakeConfig::unannounced_channel_max_inbound_htlc_value_in_flight_percentage
7090/// [`ChannelHandshakeConfig::announce_for_forwarding`]: crate::util::config::ChannelHandshakeConfig::announce_for_forwarding
7091fn 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
7109/// This is for legacy reasons, present for forward-compatibility.
7110/// LDK versions older than 0.0.104 don't know how read/handle values other than the legacy
7111/// percentage from storage. Hence, we use this function to not persist legacy values of
7112/// `holder_max_htlc_value_in_flight_msat` for channels into storage.
7113fn 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
7117/// Returns a minimum channel reserve value the remote needs to maintain,
7118/// required by us according to the configured or default
7119/// [`ChannelHandshakeConfig::their_channel_reserve_proportional_millionths`]
7120///
7121/// Guaranteed to return a value no larger than channel_value_satoshis
7122///
7123/// This is used both for outbound and inbound channels and has lower bound
7124/// of `MIN_THEIR_CHAN_RESERVE_SATOSHIS`, and the `dust_limit_satoshis` of
7125/// the counterparty.
7126///
7127/// Returns `Err` if `channel_value_satoshis` is smaller than
7128/// `MIN_THEIR_CHAN_RESERVE_SATOSHIS` or the `dust_limit_satoshis` of the
7129/// counterparty.
7130pub(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	// As described in the `ChannelHandshakeConfig` docs, we cap this value at 1_000_000.
7143	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
7154/// This is for legacy reasons, present for forward-compatibility.
7155/// LDK versions older than 0.0.104 don't know how read/handle values other than default
7156/// from storage. Hence, we use this function to not persist default values of
7157/// `holder_selected_channel_reserve_satoshis` for channels into storage.
7158pub(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
7165/// Returns a minimum channel reserve value each party needs to maintain, fixed in the spec to a
7166/// default of 1% of the total channel value.
7167///
7168/// Guaranteed to return a value no larger than `channel_value_satoshis`
7169///
7170/// This is used both for outbound and inbound channels and has lower bound
7171/// of `dust_limit_satoshis`.
7172///
7173/// Returns `Err` if `channel_value_satoshis` is smaller than `dust_limit_satoshis`.
7174pub(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	// Fixed at 1% of channel value by spec.
7184	let (q, _) = channel_value_satoshis.overflowing_div(100);
7185	Ok(cmp::max(q, dust_limit_satoshis))
7186}
7187
7188/// Context for negotiating channels (dual-funded V2 open, splicing)
7189#[derive(Debug)]
7190pub(super) struct FundingNegotiationContext {
7191	/// Whether we initiated the funding negotiation.
7192	pub is_initiator: bool,
7193	/// The amount in satoshis we will be contributing to the channel.
7194	pub our_funding_contribution: SignedAmount,
7195	/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
7196	/// to the current block height to align incentives against fee-sniping.
7197	pub funding_tx_locktime: LockTime,
7198	/// The feerate set by the initiator to be used for the funding transaction.
7199	#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
7200	pub funding_feerate_sat_per_1000_weight: u32,
7201	/// The input spending the previous funding output, if this is a splice.
7202	#[allow(dead_code)] // TODO(splicing): Remove once splicing is enabled.
7203	pub shared_funding_input: Option<SharedOwnedInput>,
7204	/// The funding inputs we will be contributing to the channel.
7205	#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
7206	pub our_funding_inputs: Vec<ConfirmedUtxo>,
7207	/// The funding outputs we will be contributing to the channel.
7208	#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
7209	pub our_funding_outputs: Vec<TxOut>,
7210}
7211
7212impl FundingNegotiationContext {
7213	/// Prepare and start interactive transaction negotiation.
7214	/// If error occurs, it is caused by our side, not the counterparty.
7215	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// Holder designates channel data owned for the benefit of the user client.
7267// Counterparty designates channel data owned by the another channel participant entity.
7268#[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	/// Information about any pending splice candidates, including RBF attempts.
7275	pending_splice: Option<PendingFunding>,
7276
7277	/// Once we become quiescent, if we're the initiator, there's some action we'll want to take.
7278	/// This keeps track of that action. Note that if we become quiescent and we're not the
7279	/// initiator we may be able to merge this action into what the counterparty wanted to do (e.g.
7280	/// in the case of splicing).
7281	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
7292/// Contents of a wire message that fails an HTLC backwards. Useful for [`FundedChannel::fail_htlc`] to
7293/// fail with either [`msgs::UpdateFailMalformedHTLC`] or [`msgs::UpdateFailHTLC`] as needed.
7294trait 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
7363/// The result of handling a `tx_complete` message during interactive transaction construction.
7364pub(super) struct TxCompleteResult {
7365	/// The message to send to the counterparty, if any.
7366	pub interactive_tx_msg_send: Option<InteractiveTxMessageSend>,
7367
7368	/// If the negotiation completed and the holder has local contributions, this contains the
7369	/// unsigned funding transaction for the `FundingTransactionReadyForSigning` event.
7370	pub event_unsigned_tx: Option<Transaction>,
7371
7372	/// If the negotiation completed and the holder has no local contributions, this contains
7373	/// the result of automatically calling `funding_transaction_signed` with empty witnesses.
7374	pub funding_tx_signed: Option<FundingTxSigned>,
7375}
7376
7377/// The result of signing a funding transaction negotiated using the interactive-tx protocol.
7378#[derive(Default)]
7379pub(super) struct FundingTxSigned {
7380	/// The initial `commitment_signed` message to send to the counterparty, if necessary.
7381	pub commitment_signed: Option<msgs::CommitmentSigned>,
7382
7383	/// The result of processing a buffered initial commitment signed from our counterparty,
7384	/// if any.
7385	pub counterparty_initial_commitment_signed_result:
7386		Option<Result<Option<ChannelMonitorUpdate>, ChannelError>>,
7387
7388	/// Signatures that should be sent to the counterparty, if necessary.
7389	pub tx_signatures: Option<msgs::TxSignatures>,
7390
7391	/// The fully-signed funding transaction to be broadcast, along with the transaction type.
7392	pub funding_tx: Option<(Transaction, TransactionType)>,
7393
7394	/// Information about the completed funding negotiation.
7395	pub splice_negotiated: Option<SpliceFundingNegotiated>,
7396
7397	/// A `splice_locked` to send to the counterparty when the splice requires 0 confirmations.
7398	pub splice_locked: Option<msgs::SpliceLocked>,
7399}
7400
7401/// Information about a splice funding negotiation that has been completed.
7402pub struct SpliceFundingNegotiated {
7403	/// The outpoint of the channel's splice funding transaction.
7404	pub funding_txo: bitcoin::OutPoint,
7405
7406	/// Whether the holder contributed local inputs or outputs to the negotiated splice.
7407	pub has_local_contribution: bool,
7408
7409	/// The features that this channel will operate with.
7410	pub channel_type: ChannelTypeFeatures,
7411
7412	/// The redeem script of the funding output.
7413	pub funding_redeem_script: ScriptBuf,
7414}
7415
7416/// Information about a splice funding negotiation that has failed.
7417pub struct SpliceFundingFailed {
7418	/// UTXOs released by the failure. Excludes inputs the contribution recorded as committed to
7419	/// another splice attempt, which may still be included in `contribution`.
7420	contributed_inputs: Vec<bitcoin::OutPoint>,
7421
7422	/// Outputs released by the failure. Excludes outputs the contribution recorded as committed to
7423	/// another splice attempt, which may still be included in `contribution`.
7424	contributed_outputs: Vec<TxOut>,
7425
7426	/// The funding contribution from the failed round.
7427	contribution: FundingContribution,
7428}
7429
7430/// Information about an active RBF negotiation aborted after a prior splice candidate confirmed.
7431pub(super) struct SpliceRbfAbort {
7432	pub tx_abort: msgs::TxAbort,
7433	pub splice_funding_failed: Option<SpliceFundingFailed>,
7434}
7435
7436impl SpliceFundingFailed {
7437	/// Builds a failure for `contribution` that releases its [`FundingContribution::reserved_inputs`]
7438	/// and [`FundingContribution::reserved_outputs`]. Inputs and outputs it inherited from a pending
7439	/// splice attempt are not released, as that attempt's transaction may still confirm.
7440	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	/// Splits into the funding info for `DiscardFunding` (if there are inputs or outputs to
7449	/// discard) and the contribution for `SpliceNegotiationFailed`.
7450	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		// A contribution queued for a later round (e.g., behind a counterparty-initiated
7507		// negotiation) fails independently of the active round and must also be reported.
7508		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	/// Returns details about any pending splice attempts for inclusion in
7554	/// [`crate::ln::channel_state::ChannelDetails`].
7555	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		// A contribution committed via `funding_contributed` sits in `quiescent_action` until
7562		// quiescence is reached and it begins negotiating; surface it as the last candidate, in a
7563		// `WaitingOn*` status describing what it is waiting on.
7564		if let Some(contribution) = self.queued_funding_contribution() {
7565			// It begins negotiating at the next quiescence if there is no pending candidate or it can
7566			// replace one via RBF; otherwise its outcome must wait for the pending candidate to lock.
7567			// It can then proceed as a fresh splice only if it does not reuse any inputs or outputs
7568			// from the promote splice transaction.
7569			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				// No `PendingFunding` yet (a first splice still awaiting quiescence), but the queued
7581				// contribution is still worth surfacing.
7582				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	/// Returns a boolean indicating whether we should reset the splice's
7606	/// [`PendingFunding::funding_negotiation`].
7607	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							// If we want to resume the negotiation after reconnecting, we must be
7621							// in [`FundingNegotiation::AwaitingSignatures`] to not reset our state.
7622							!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	/// Resets splice negotiation and quiescence state, returning a failed local contribution or
7644	/// a pending splice whose funding signatures are ready to send.
7645	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							// Committed funding remains reserved until the closing transaction has
7690							// enough confirmations to safely discard it.
7691							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			// Only clear the signing session if the current round is mid-signing. When an earlier
7713			// round completed signing and a later RBF round is in `AwaitingAck` or
7714			// `ConstructingTransaction`, the session belongs to the prior round and must be
7715			// preserved.
7716			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		// Before the current round reaches AwaitingSignatures, the retained signing session belongs
7739		// to the prior candidate and must not prevent aborting the new RBF.
7740		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			// Once signing has advanced this far, leave the negotiation active and allow the
7749			// signature exchange to continue. If the confirmed candidate reaches lock-in first,
7750			// normal promotion will discard the conflicting RBF attempt.
7751			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	/// Returns a [`SpliceFundingFailed`] for each splice contribution which a restart drops
7769	/// because it is not persisted: one in a funding negotiation which is not written, and one
7770	/// still queued waiting on quiescence.
7771	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		// A contribution queued for a later round (e.g., behind a counterparty-initiated
7789		// negotiation) fails independently of the active round and must also be reported.
7790		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		// The shutdown scriptpubkey is set on channel opening when option_upfront_shutdown_script
7838		// is signaled. Otherwise, it is set when sending a shutdown message. Calling this method
7839		// outside of those situations will fail.
7840		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 +                                                   // version
7848		 1 +                                                   // input count
7849		 36 +                                                  // prevout
7850		 1 +                                                   // script length (0)
7851		 4 +                                                   // sequence
7852		 1 +                                                   // output count
7853		 4                                                     // lock time
7854		 )*4 +                                                 // * 4 for non-witness parts
7855		2 +                                                    // witness marker and flag
7856		1 +                                                    // witness element count
7857		4 +                                                    // 4 element lengths (2 sigs, multisig dummy, and witness script)
7858		self.funding.get_funding_redeemscript().len() as u64 + // funding witness script
7859		2*(1 + 71); // two signatures + sighash type flags
7860		if let Some(spk) = a_scriptpubkey {
7861			ret += ((8+1) +                                    // output values and script length
7862				spk.len() as u64)                              // scriptpubkey
7863				* 4; // witness multiplier
7864		}
7865		if let Some(spk) = b_scriptpubkey {
7866			ret += ((8+1) +                                    // output values and script length
7867				spk.len() as u64)                              // scriptpubkey
7868				* 4; // witness multiplier
7869		}
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	/// Claims an HTLC while we're disconnected from a peer, dropping the [`ChannelMonitorUpdate`]
7941	/// entirely.
7942	///
7943	/// This is only used for payments received prior to LDK 0.1.
7944	///
7945	/// The [`ChannelMonitor`] for this channel MUST be updated out-of-band with the preimage
7946	/// provided (i.e. without calling [`crate::chain::Watch::update_channel`]).
7947	///
7948	/// The HTLC claim will end up in the holding cell (because the caller must ensure the peer is
7949	/// disconnected).
7950	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 that we'll add the HTLC claim to the holding cell in `get_update_fulfill_htlc`
7954		// (see equivalent if condition there).
7955		assert!(!self.context.channel_state.can_generate_new_commitment());
7956		let mon_update_id = self.context.latest_monitor_update_id; // Forget the ChannelMonitor update
7957		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); // The HTLC must have ended up in the holding cell.
7962		}
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		// Either ChannelReady got set (which means it won't be unset) or there is no way any
7971		// caller thought we could have something claimed (cause we wouldn't have accepted in an
7972		// incoming HTLC anyway). If we got to ShutdownComplete, callers aren't allowed to call us,
7973		// either.
7974		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		// ChannelManager may generate duplicate claims/fails due to HTLC update events from
7979		// on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop
7980		// these, but for now we just have to treat them as normal.
7981
7982		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						// Don't return in release mode here so that we can update channel_monitor
8012					},
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		// Now update local state:
8024		//
8025		// We have to put the payment_preimage in the channel_monitor right away here to ensure we
8026		// can claim it even if the channel hits the chain before we see their next commitment.
8027		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			// Note that this condition is the same as the assertion in
8039			// `claim_htlc_while_disconnected_dropping_mon_update` and must match exactly -
8040			// `claim_htlc_while_disconnected_dropping_mon_update` would not work correctly if we
8041			// do not not get into this branch.
8042			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							// Make sure we don't leave latest_monitor_update_id incremented here:
8047							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							// TODO: We may actually be able to switch to a fulfill here, though its
8056							// rare enough it may not be worth the complexity burden.
8057							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				// Even if we aren't supposed to let new monitor updates with commitment state
8135				// updates run, we still need to push the preimage ChannelMonitorUpdateStep no
8136				// matter what. Sadly, to push a new monitor update which flies before others
8137				// already queued, we have to insert it into the pending queue and update the
8138				// update_ids of all the following monitors.
8139				if release_cs_monitor && !update_blocked {
8140					let mut additional_update = self.build_commitment_no_status_check(logger);
8141					// build_commitment_no_status_check may bump latest_monitor_id but we want them
8142					// to be strictly increasing by one, so decrement it here.
8143					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	/// Returns `Err` (always with [`ChannelError::Ignore`]) if the HTLC could not be failed (e.g.
8179	/// if it was already resolved). Otherwise returns `Ok`.
8180	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	/// Used for failing back with [`msgs::UpdateFailMalformedHTLC`]. For now, this is used when we
8188	/// want to fail blinded HTLCs where we are not the intro node.
8189	///
8190	/// See [`Self::queue_fail_htlc`] for more info.
8191	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	/// Returns `Err` (always with [`ChannelError::Ignore`]) if the HTLC could not be failed (e.g.
8199	/// if it was already resolved). Otherwise returns `Ok`.
8200	#[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		// ChannelManager may generate duplicate claims/fails due to HTLC update events from
8210		// on-chain ChannelsMonitors during block rescan. Ideally we'd figure out a way to drop
8211		// these, but for now we just have to treat them as normal.
8212
8213		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		// Now update local state:
8239		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	// Message handlers:
8273	/// Updates the state of the channel to indicate that all channels in the batch have received
8274	/// funding_signed and persisted their monitors.
8275	/// The funding transaction is consequently allowed to be broadcast, and the channel can be
8276	/// treated as a non-batch channel going forward.
8277	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	/// Unsets the existing funding information for V1 funded channels.
8283	///
8284	/// This must only be used if the channel has not yet completed funding and has not been used.
8285	///
8286	/// Further, the channel must be immediately shut down after this with a call to
8287	/// [`ChannelContext::force_shutdown`].
8288	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	/// Handles a channel_ready message from our peer. If we've already sent our channel_ready
8308	/// and the channel is now usable (and public), this may generate an announcement_signatures to
8309	/// reply with.
8310	#[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				// The scid alias provided can be used to route payments *from* our counterparty,
8323				// i.e. can be used for inbound payments and provided in invoices, but is not used
8324				// when routing outbound payments.
8325				self.context.latest_inbound_scid_alias = Some(scid_alias);
8326			}
8327		}
8328
8329		// Our channel_ready shouldn't have been sent if we are waiting for other channels in the
8330		// batch, but we can receive channel_ready messages.
8331		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					// If we reconnected before sending our `channel_ready` they may still resend theirs.
8338					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					// We're in `WAITING_FOR_BATCH`, so we should wait until we're ready.
8346					debug_assert!(flags.is_set(AwaitingChannelReadyFlags::WAITING_FOR_BATCH));
8347				}
8348			}
8349			// If we reconnected before sending our `channel_ready` they may still resend theirs.
8350			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			// They probably disconnected/reconnected and re-sent the channel_ready, which is
8355			// required, or they're sending a fresh SCID alias.
8356			let expected_point =
8357				if self.context.counterparty_next_commitment_transaction_number == INITIAL_COMMITMENT_NUMBER - 1 {
8358					// If they haven't ever sent an updated point, the point they send should match
8359					// the next one.
8360					self.context.counterparty_next_commitment_point
8361				} else if self.context.counterparty_next_commitment_transaction_number == INITIAL_COMMITMENT_NUMBER - 2 {
8362					// If we've advanced the commitment number once, the second commitment point is
8363					// at `counterparty_current_commitment_point`, which is not yet revoked.
8364					debug_assert!(self.context.counterparty_current_commitment_point.is_some());
8365					self.context.counterparty_current_commitment_point
8366				} else {
8367					// If they have sent updated points, channel_ready is always supposed to match
8368					// their "first" point, which we re-derive here.
8369					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 the remote has sent a shutdown prior to adding this HTLC, then they are in violation of the spec.
8399		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		// Now update local state:
8423		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	/// Returns true if any committed inbound HTLCs were received before we started serializing
8437	/// inbound committed payment onions in `Channel` and cannot be used during `ChannelManager`
8438	/// deserialization to reconstruct the set of pending HTLCs.
8439	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	/// Returns committed inbound HTLCs whose onion has not yet been decoded and processed. Useful
8449	/// for reconstructing the set of pending HTLCs when deserializing the `ChannelManager`.
8450	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	/// Returns committed inbound HTLCs that have been forwarded but not yet fully resolved. Useful
8462	/// when reconstructing the set of pending HTLCs when deserializing the `ChannelManager`.
8463	pub(super) fn inbound_forwarded_htlcs(
8464		&self,
8465	) -> impl Iterator<Item = (PaymentHash, HTLCPreviousHopData, OutboundHop)> + '_ {
8466		// We don't want to return an HTLC as needing processing if it already has a resolution that's
8467		// pending in the holding cell.
8468		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				// The reconstructed `HTLCPreviousHopData` is used to fail or claim the HTLC backwards
8500				// post-restart, if it is missing in the outbound edge.
8501				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	/// Useful when reconstructing the set of pending HTLC forwards when deserializing the
8522	/// `ChannelManager`. We don't want to cache an HTLC as needing to be forwarded if it's already
8523	/// present in the outbound edge, or else we'll double-forward.
8524	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	/// This inbound HTLC was irrevocably forwarded to the outbound edge, so we no longer need to
8563	/// persist its onion.
8564	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	/// Clears the `hold_htlc` flag for a pending inbound HTLC, returning `true` if the HTLC was
8586	/// successfully released. Useful when a [`ReleaseHeldHtlc`] onion message arrives before the
8587	/// HTLC has been fully committed.
8588	///
8589	/// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc
8590	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				// Clearing `hold_htlc` here directly affects the copy that will be cloned into the decode
8603				// pipeline when RAA promotes the HTLC.
8604				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	/// Useful for testing crash scenarios where the holding cell is not persisted.
8623	#[cfg(test)]
8624	pub(super) fn test_clear_holding_cell(&mut self) {
8625		self.context.holding_cell_htlc_updates.clear()
8626	}
8627
8628	/// Marks an outbound HTLC which we have received update_fail/fulfill/malformed
8629	#[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	/// Handles an incoming `commitment_signed` message for the first commitment transaction of the
8777	/// channel's new funding transaction. This assumes our `commitment_signed` was already sent
8778	/// when the [`InteractiveTxSigningSession`] was initialized, so we do not need to send one in
8779	/// response. As a result, a single [`ChannelMonitorUpdate`] will get queued that tracks the new
8780	/// set of channel parameters, as well as the initial holder and counterparty commitment
8781	/// transactions. We hold back sending our `tx_signatures` until the monitor update is
8782	/// persisted, such that we're able to enforce the holder commitment transaction onchain once
8783	/// the new funding transaction is signed and broadcast.
8784	///
8785	/// Note that our `commitment_signed` send did not include a monitor update. This is due to:
8786	///   1. Updates cannot be made since the state machine is paused until `tx_signatures`.
8787	///   2. We're still able to abort negotiation until `tx_signatures`.
8788	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		// This corresponds to the same `commitment_signed` we sent earlier, which we know to be the
8825		// same since the state machine is paused until `tx_signatures` are exchanged.
8826		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			// We may have aborted a pending funding negotiation while the counterparty's initial
8917			// `commitment_signed` was in flight.
8918			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		// Any commitment_signed not associated with a FundingScope is ignored below if a
8993		// pending splice transaction has confirmed since receiving the batch.
8994		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			// We only fail to advance our commitment point/number if we're currently
9072			// waiting for our signer to unblock and provide a commitment point.
9073			// During post-funding channel operation, we only advance our point upon
9074			// receiving a commitment_signed, and our counterparty cannot send us
9075			// another commitment signed until we've provided a new commitment point
9076			// in revoke_and_ack, which requires unblocking our signer and completing
9077			// the advance to the next point. This should be unreachable since
9078			// a new commitment_signed should fail at our signature checks in
9079			// validate_commitment_signed.
9080			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		// Update state now that we've passed all the can-fail calls...
9085		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				// Swap against a dummy variant to avoid a potentially expensive clone of `OutboundHTLCOutcome::Failure(HTLCFailReason)`
9108				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					// If a user (a) receives an HTLC claim using LDK 0.0.104 or before, then (b)
9115					// upgrades to LDK 0.0.114 or later before the HTLC is fully resolved, we could
9116					// have a `Success(None)` reason. In this case we could forget some HTLC
9117					// claims, but such an upgrade is unlikely and including claimed HTLCs here
9118					// fixes a bug which the user was exposed to on 0.0.104 when they started the
9119					// claim anyway.
9120					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		// Note that if we need_commitment & !AwaitingRemoteRevoke we'll call
9154		// build_commitment_no_status_check() next which will reset this to RAAFirst.
9155		self.context.resend_order = RAACommitmentOrder::CommitmentFirst;
9156
9157		if self.context.channel_state.is_monitor_update_in_progress() {
9158			// In case we initially failed monitor updating without requiring a response, we need
9159			// to make sure the RAA gets sent first.
9160			self.context.monitor_pending_revoke_and_ack = true;
9161			if need_commitment && !self.context.channel_state.is_awaiting_remote_revoke() {
9162				// If we were going to send a commitment_signed after the RAA, go ahead and do all
9163				// the corresponding HTLC status updates so that
9164				// get_last_commitment_update_for_send includes the right HTLCs.
9165				self.context.monitor_pending_commitment_signed = true;
9166				let mut additional_update = self.build_commitment_no_status_check(logger);
9167				// build_commitment_no_status_check may bump latest_monitor_id but we want them to be
9168				// strictly increasing by one, so decrement it here.
9169				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				// If we're AwaitingRemoteRevoke we can't send a new commitment here, but that's ok -
9180				// we'll send one right away when we get the revoke_and_ack when we
9181				// free_holding_cell_htlcs().
9182				let mut additional_update = self.build_commitment_no_status_check(logger);
9183				// build_commitment_no_status_check may bump latest_monitor_id but we want them to be
9184				// strictly increasing by one, so decrement it here.
9185				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	/// Public version of the below, checking relevant preconditions first.
9207	/// If we're not in a state where freeing the holding cell makes sense, this is a no-op and
9208	/// returns `(None, Vec::new())`.
9209	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	/// Frees any pending commitment updates in the holding cell, generating the relevant messages
9222	/// for our counterparty.
9223	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, // We don't increment this yet!
9245				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				// Note that this *can* fail, though it should be due to rather-rare conditions on
9257				// fee races with adding too many outputs which push our total payments just over
9258				// the limit. In case it's less rare than I anticipate, we may want to revisit
9259				// handling this case better and maybe fulfilling some of the HTLCs while attempting
9260				// to rebalance channels.
9261				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								// `send_htlc` only returns `Ok(false)`, when an update goes into
9289								// the holding cell, but since we're currently freeing it, we should
9290								// always expect to see the htlc added.
9291								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								// If we fail to send here, then this HTLC should be failed
9305								// backwards. Failing to send here indicates that this HTLC may
9306								// keep being put back into the holding cell without ever being
9307								// successfully forwarded/failed/fulfilled, causing our
9308								// counterparty to eventually close on us.
9309								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						// If an HTLC claim was previously added to the holding cell (via
9320						// `get_update_fulfill_htlc`, then generating the claim message itself must
9321						// not fail - any in between attempts to claim the HTLC will have resulted
9322						// in it hitting the holding cell again and we cannot change the state of a
9323						// holding cell HTLC from fulfill to anything else.
9324						//
9325						// Note that we should have already provided a preimage-containing
9326						// `ChannelMonitorUpdate` to the user, making this one redundant, however
9327						// there's no harm in including the extra `ChannelMonitorUpdateStep` here.
9328						// We do not bother to track and include `payment_info` here, however.
9329						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							// If an HTLC failure was previously added to the holding cell (via
9363							// `queue_fail_{malformed_}htlc`) then generating the fail message itself must
9364							// not fail - we should never end up in a state where we double-fail
9365							// an HTLC or fail-then-claim an HTLC as it indicates we didn't wait
9366							// for a full revocation before failing.
9367							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			// build_commitment_no_status_check and get_update_fulfill_htlc may bump latest_monitor_id
9392			// but we want them to be strictly increasing by one, so reset it here.
9393			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	/// Handles receiving a remote's revoke_and_ack. Note that we may return a new
9416	/// commitment_signed message here in case we had pending outbound HTLCs to add which were
9417	/// waiting on this revoke_and_ack. The generation of this new commitment_signed may also fail,
9418	/// generating an appropriate error *after* the channel state has been updated based on the
9419	/// revoke_and_ack message.
9420	///
9421	/// The static invoices will be used by us as an async sender to enqueue [`HeldHtlcAvailable`]
9422	/// onion messages for the often-offline recipient, and the blinded reply paths the invoices are
9423	/// paired with were created by our channel counterparty and will be used as reply paths for
9424	/// corresponding [`ReleaseHeldHtlc`] messages.
9425	///
9426	/// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
9427	/// [`ReleaseHeldHtlc`]: crate::onion_message::async_payments::ReleaseHeldHtlc
9428	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			// Our counterparty seems to have burned their coins to us (by revoking a state when we
9479			// haven't given them a new commitment transaction to broadcast). We should probably
9480			// take advantage of this by updating our channel monitor, sending them an error, and
9481			// waiting for them to broadcast their latest (now-revoked claim). But, that would be a
9482			// lot of work, and there's some chance this is all a misunderstanding anyway.
9483			// We have to do *something*, though, since our signer may get mad at us for otherwise
9484			// jumping a remote commitment number, so best to just force-close and move on.
9485			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		// Update state now that we've passed all the can-fail calls...
9518		// (note that we may still fail to generate the new commitment_signed message, but that's
9519		// OK, we step the channel here and *then* if the new generation fails we can fail the
9520		// channel based on that, but stepping stuff here should be safe either way.
9521		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			// Take references explicitly so that we can hold multiple references to self.context.
9545			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			// We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug)
9551			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					// We really want take() here, but, again, non-mut ref :(
9571					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							// Even though a fast track was taken for fulfilled HTLCs to the incoming side, we still
9580							// pass along attribution data here so that we can include hold time information in the
9581							// final PaymentPathSuccessful events.
9582							finalized_claimed_htlcs.push((htlc.source.clone(), attribution_data));
9583							// They fulfilled, so we sent them money
9584							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											// HTLCs will only be in state `InboundHTLCResolution::Resolved` if they were
9644											// received on LDK 0.1-.
9645											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							// We should only be using our counterparty's release_htlc_message_path if we
9672							// originally configured the HTLC to be held with them until the recipient comes
9673							// online. Otherwise, our counterparty could include paths for all of our HTLCs and
9674							// use the responses sent to their paths to determine which of our HTLCs are async
9675							// payments.
9676							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					// Swap against a dummy variant to avoid a potentially expensive clone of `OutboundHTLCOutcome::Failure(HTLCFailReason)`
9696					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				// free_holding_cell_htlcs may bump latest_monitor_id multiple times but we want them to be
9764				// strictly increasing by one, so decrement it here.
9765				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					// We can't generate a new commitment transaction yet so we just return what we
9785					// have. When the monitor updating is restored we'll call
9786					// get_last_commitment_update_for_send(), which does not update state, but we're
9787					// definitely now awaiting a remote revoke before we can step forward any more,
9788					// so set it here.
9789					let mut additional_update = self.build_commitment_no_status_check(logger);
9790
9791					// build_commitment_no_status_check may bump latest_monitor_id but we want them to be
9792					// strictly increasing by one, so decrement it here.
9793					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			// Although the user may have already provided our `tx_signatures`, we must not send
10014			// them if we're waiting for the monitor to durably persist the counterparty's signature
10015			// for our initial commitment post-splice.
10016			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	/// Queues up an outbound update fee by placing it in the holding cell. You should call
10047	/// [`Self::maybe_free_holding_cell_htlcs`] in order to actually generate and send the
10048	/// commitment update.
10049	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	/// Adds a pending update to this channel. See the doc for send_htlc for
10057	/// further details on the optionness of the return value.
10058	/// If our balance is too low to cover the cost of the next commitment transaction at the
10059	/// new feerate, the update is cancelled.
10060	///
10061	/// You MUST call [`Self::send_commitment_no_state_update`] prior to any other calls on this
10062	/// [`FundedChannel`] if `force_holding_cell` is false.
10063	#[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		// Sending a fee update for zero fee commitments will trigger a warning and disconnect
10079		// from our peer, but does not result in a loss of funds so we do not panic here.
10080		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		// Some of the checks of `can_generate_new_commitment` have already been done above, but
10090		// it's much more brittle to not use it in favor of checking the remaining flags left, as it
10091		// gives us one less code path to update if the method changes.
10092		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	/// Removes any uncommitted inbound HTLCs and resets the state of uncommitted outbound HTLC
10111	/// updates, to be used on peer disconnection. After this, update_*_htlc messages need to be
10112	/// resent.
10113	/// No further message handling calls may be made until a channel_reestablish dance has
10114	/// completed.
10115	/// May return `Err(())`, which implies [`ChannelContext::force_shutdown`] should be called immediately.
10116	#[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		// We only clear `peer_disconnected` if we were able to reestablish the channel. We always
10124		// reset our awaiting response in case we failed reestablishment and are disconnecting.
10125		self.context.sent_message_awaiting_response = None;
10126
10127		if self.context.channel_state.is_peer_disconnected() {
10128			// While the below code should be idempotent, it's simpler to just return early, as
10129			// redundant disconnect events can fire, though they should be rare.
10130			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		// Upon reconnect we have to start the closing_signed dance over, but shutdown messages
10138		// will be retransmitted.
10139		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					// They sent us an update_add_htlc but we never got the commitment_signed.
10148					// We'll tell them what commitment_signed we're expecting next and they'll drop
10149					// this HTLC accordingly
10150					inbound_drop_count += 1;
10151					false
10152				},
10153				InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_)|InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) => {
10154					// We received a commitment_signed updating this HTLC and (at least hopefully)
10155					// sent a revoke_and_ack (which we can re-transmit) and have heard nothing
10156					// in response to it yet, so don't touch it.
10157					true
10158				},
10159				InboundHTLCState::Committed { .. } => true,
10160				InboundHTLCState::LocalRemoved(_) => {
10161					// We (hopefully) sent a commitment_signed updating this HTLC (which we can
10162					// re-transmit if needed) and they may have even sent a revoke_and_ack back
10163					// (that we missed). Keep this around for now and if they tell us they missed
10164					// the commitment_signed we can re-transmit the update then.
10165					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				// They sent us an update to remove this but haven't yet sent the corresponding
10181				// commitment_signed, we need to move it back to Committed and they can re-send
10182				// the update upon reconnection.
10183				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	/// Indicates that a ChannelMonitor update is in progress and has not yet been fully persisted.
10193	/// This must be called before we return the [`ChannelMonitorUpdate`] back to the
10194	/// [`ChannelManager`], which will call [`Self::monitor_updating_restored`] once the monitor
10195	/// update completes (potentially immediately).
10196	/// The messages which were generated with the monitor update must *not* have been sent to the
10197	/// remote end, and must instead have been dropped. They will be regenerated when
10198	/// [`Self::monitor_updating_restored`] is called.
10199	///
10200	/// [`ChannelManager`]: super::channelmanager::ChannelManager
10201	/// [`chain::Watch`]: crate::chain::Watch
10202	/// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
10203	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	/// Indicates that the latest ChannelMonitor update has been committed by the client
10221	/// successfully and we should restore normal operation. Returns messages which should be sent
10222	/// to the remote side.
10223	#[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		// Some cases below may not strictly require ChannelManager persistence, but we err on
10235		// the conservative side to avoid missing state changes.
10236		let mut requires_channel_manager_persistence = false;
10237
10238		// We want to clear that the monitor update for our `tx_signatures` has completed, but
10239		// we may still need to hold back the message until it's ready to be sent.
10240		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		// If we're past (or at) the AwaitingChannelReady stage on an outbound (or V2-established) channel,
10279		// try to (re-)broadcast the funding transaction as we may have declined to broadcast it when we
10280		// first received the funding_signed.
10281		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				// Broadcast only if not yet confirmed
10288				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		// An active interactive signing session or an awaiting channel_ready state implies that a
10296		// commitment_signed retransmission is an initial one for funding negotiation. Thus, the
10297		// signatures should be sent before channel_ready.
10298		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		// We will never broadcast the funding transaction when we're in MonitorUpdateInProgress
10307		// (and we assume the user never directly broadcasts the funding transaction and waits for
10308		// us to do it). Thus, we can only ever hit monitor_pending_channel_ready when we're
10309		// * an inbound channel that failed to persist the monitor on funding_created and we got
10310		//   the funding transaction confirmed before the monitor was persisted, or
10311		// * a 0-conf channel and intended to send the channel_ready before any broadcast at all.
10312		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			// While its possible our fee is too low for an outbound channel because we've been
10395			// unable to increase the fee, we don't try to force-close directly here.
10396			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	/// Indicates that the signer may have some signatures for us, so we should retry if we're
10443	/// blocked.
10444	#[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				// The previous transaction number (i.e., when adding 1) is used because this field
10473				// is advanced when handling funding_created, but the point is not advanced until
10474				// handling channel_ready.
10475				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		// Provide a `channel_ready` message if we need to, but only if we're _not_ still pending
10563		// funding.
10564		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			// If signer-pending state regenerated an RAA, the monitor update for that RAA was
10592			// already persisted before we set `signer_pending_revoke_and_ack`. Thus, if reconnect
10593			// also marked the same RAA monitor-pending while another monitor update was in flight,
10594			// the RAA we're returning here satisfies that monitor-pending resend.
10595			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		// Technically if HolderCommitmentPoint::can_advance is false,
10699		// we have a commitment point ready to send in an RAA, however we
10700		// choose to wait since if we send RAA now, we could get another
10701		// CS before we have any commitment point available. Blocking our
10702		// RAA here is a convenient way to make sure that post-funding
10703		// we're only ever waiting on one commitment point at a time.
10704		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	/// Gets the last commitment update for immediate sending to our peer.
10711	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	/// Gets the `Shutdown` message we should send our peer on reconnect, if any.
10813	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	/// May panic if some calls other than message-handling calls (which will all Err immediately)
10842	/// have been called between remove_uncommitted_htlcs_and_mark_paused and this call.
10843	#[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			// While BOLT 2 doesn't indicate explicitly we should error this channel here, it
10854			// almost certainly indicates we are going to end up out-of-sync in some way, so we
10855			// just close here instead of trying to recover.
10856			return Err(ChannelError::close("Peer sent a loose channel_reestablish not after reconnect".to_owned()));
10857		}
10858
10859		// A node:
10860		//   - if `next_commitment_number` is zero:
10861		//     - MUST immediately fail the channel and broadcast any relevant latest commitment
10862		//       transaction.
10863		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		// Before we change the state of the channel, we check if the peer is sending a very old
10904		// commitment transaction number, if yes we send a warning message.
10905		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		// Go ahead and unmark PeerDisconnected as various calls we may make check for it (and all
10914		// remaining cases either succeed or ErrorMessage-fail).
10915		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		// A receiving node:
10923		//   - if `my_current_funding_locked` is included with the `announcement_signatures` bit
10924		//     set in the `retransmit_flags`:
10925		//     - if `announce_channel` is set for this channel and the receiving node is ready
10926		//       to send `announcement_signatures` for the corresponding splice transaction:
10927		//       - MUST retransmit `announcement_signatures`.
10928		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		// If the counterparty's `my_current_funding_locked` matches the splice we've already
10937		// confirmed and are about to promote, any `announcement_signatures` we'd generate here
10938		// would be for the soon-to-be-superseded pre-splice funding. Skip them;
10939		// `maybe_promote_splice_funding` will emit correct post-splice sigs once
10940		// `inferred_splice_locked` is processed.
10941		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		// A receiving node:
10959		//   - if the `next_funding` TLV is set:
10960		let mut retransmit_funding_commit_sig = None;
10961		if let Some(next_funding) = &msg.next_funding {
10962			// - if `next_funding_txid` matches the latest interactive funding transaction
10963			//   or the current channel funding transaction:
10964			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 it has not received `tx_signatures` for that funding transaction:
10981					//   - if the `commitment_signed` bit is set in `retransmit_flags`:
10982					if !session.has_received_tx_signatures()
10983						&& next_funding.should_retransmit(msgs::NextFundingFlag::CommitmentSigned)
10984					{
10985						// - MUST retransmit its `commitment_signed` for that funding transaction.
10986						retransmit_funding_commit_sig = Some(next_funding.txid);
10987					}
10988
10989					// - if it has already received `commitment_signed` and it should sign first
10990					//   - MUST send its `tx_signatures` for that funding transaction.
10991					//
10992					// - if it has already received `tx_signatures` for that funding transaction:
10993					//   - MUST send its `tx_signatures` for that funding transaction.
10994					if let Some(holder_tx_signatures) = session.holder_tx_signatures() {
10995						// A completed exchange may precede an unrelated monitor update, so
10996						// retransmitting the same signatures does not depend on that update.
10997						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				// We'll just send a `tx_abort` here if we don't have a signing session for this channel
11019				// on reestablish and tell our peer to just forget about it.
11020				// Our peer is doing something strange, but it doesn't warrant closing the channel.
11021				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 we're waiting on a monitor update, we shouldn't re-send any channel_ready's.
11071			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			// We have OurChannelReady set!
11092			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			// Remote isn't waiting on any RevokeAndACK from us!
11108			// Note that if we need to repeat our ChannelReady we'll do that in the next if block.
11109			// If a stale ChannelManager replayed a completed update, the monitor-pending state may
11110			// still think we owe one; the reestablish proof is authoritative here.
11111			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		// We increment counterparty_next_commitment_transaction_number only upon receipt of
11130		// revoke_and_ack, not on sending commitment_signed, so we add one if have
11131		// AwaitingRemoteRevoke set, which indicates we sent a commitment_signed but haven't gotten
11132		// the corresponding revoke_and_ack back yet.
11133		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		// A node:
11137		//   - if `next_commitment_number` is 1 in both the `channel_reestablish` it
11138		//     sent and received, and none of those `channel_reestablish` messages
11139		//     contain `my_current_funding_locked` or `next_funding` for a splice transaction:
11140		//     - MUST retransmit `channel_ready`.
11141		//   - otherwise:
11142		//     - MUST NOT retransmit `channel_ready`, but MAY send `channel_ready` with
11143		//       a different `short_channel_id` `alias` field.
11144		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			// We should never have to worry about MonitorUpdateInProgress resending ChannelReady
11151			self.get_channel_ready(logger)
11152		} else { None };
11153
11154		// A receiving node:
11155		//   - if splice transactions are pending and `my_current_funding_locked` matches one of
11156		//     those splice transactions, for which it hasn't received `splice_locked` yet:
11157		//     - MUST process `my_current_funding_locked` as if it was receiving `splice_locked`
11158		//       for this `txid`.
11159		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					// `my_current_funding_locked` normally makes an explicit retransmission
11178					// redundant. However, if the peer is still missing our `tx_signatures` for
11179					// this splice, it cannot recognize the locked funding until those signatures
11180					// arrive, so repeat `splice_locked` immediately afterwards.
11181					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			// If a splice confirms after we've sent `channel_reestablish` but before we've received
11192			// theirs, we may promote the splice and clear `pending_splice`. We still need to send
11193			// `splice_locked` after reestablishing as it was not included in our
11194			// `channel_reestablish`.
11195			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			// If a stale ChannelManager replayed a completed update, the monitor-pending state may
11207			// still think we owe one.
11208			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			// A commitment update generated above retransmits the initial splice
11216			// `commitment_signed` and must precede its funding signatures. Otherwise a completed
11217			// exchange's retransmitted signatures must precede any `splice_locked` below.
11218			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	/// Calculates and returns our minimum and maximum closing transaction fee amounts, in whole
11312	/// satoshis. The amounts remain consistent unless a peer disconnects/reconnects or we restart,
11313	/// at which point they will be recalculated.
11314	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		// Propose a range from our current Background feerate to our Normal feerate plus our
11322		// force_close_avoidance_max_fee_satoshis.
11323		// If we fail to come to consensus, we'll have to force-close.
11324		let mut proposed_feerate =
11325			fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::ChannelCloseMinimum);
11326		// Use NonAnchorChannelFee because this should be an estimate for a channel close
11327		// that we don't expect to need fee bumping
11328		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		// The spec requires that (when the channel does not have anchors) we only send absolute
11334		// channel fees no greater than the absolute channel fee on the current commitment
11335		// transaction. It's unclear *which* commitment transaction this refers to, and there isn't
11336		// very good reason to apply such a limit in any case. We don't bother doing so, risking
11337		// some force-closure by old nodes, but we wanted to close the channel anyway.
11338
11339		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		// Note that technically we could end up with a lower minimum fee if one sides' balance is
11350		// below our dust limit, causing the output to disappear. We don't bother handling this
11351		// case, however, as this should only happen if a channel is closed before any (material)
11352		// payments have been made on it. This may cause slight fee overpayment and/or failure to
11353		// come to consensus with our counterparty on appropriate fees, however it should be a
11354		// relatively rare case. We can revisit this later, though note that in order to determine
11355		// if the funders' output is dust we have to know the absolute fee we're going to use.
11356		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			// We always add force_close_avoidance_max_fee_satoshis to our normal
11363			// feerate-calculated fee, but allow the max to be overridden if we're using a
11364			// target feerate-calculated fee.
11365			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	/// Returns true if we're ready to commence the closing_signed negotiation phase. This is true
11380	/// after both sides have exchanged a `shutdown` message and all HTLCs have been drained. At
11381	/// this point if we're the funder we should send the initial closing_signed, and in any case
11382	/// shutdown should complete within a reasonable timeframe.
11383	fn closing_negotiation_ready(&self) -> bool {
11384		self.context.closing_negotiation_ready()
11385	}
11386
11387	/// Checks if the closing_signed negotiation is making appropriate progress, possibly returning
11388	/// an Err if no progress is being made and the channel should be force-closed instead.
11389	/// Should be called on a one-minute timer.
11390	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 we're waiting on a monitor persistence, that implies we're also waiting to send some
11408		// message to our counterparty (probably a `revoke_and_ack`). In such a case, we shouldn't
11409		// initiate `closing_signed` negotiation until we're clear of all pending messages. Note
11410		// that closing_negotiation_ready checks this case (as well as a few others).
11411		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 we're waiting on a counterparty `commitment_signed` to clear some updates from our
11423		// local commitment transaction, we can't yet initiate `closing_signed` negotiation.
11424		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	/// Determines whether we should disconnect the counterparty due to not receiving a response
11452	/// within our expected timeframe.
11453	///
11454	/// This should be called for peers with an active socket on every
11455	/// [`super::channelmanager::ChannelManager::timer_tick_occurred`].
11456	#[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			// Cleared upon receiving `channel_reestablish`.
11464			self.context.channel_state.is_peer_disconnected()
11465			// Cleared upon receiving `stfu`.
11466			|| self.context.channel_state.is_local_stfu_sent()
11467			// Cleared upon receiving a message that triggers the end of quiescence.
11468			|| self.context.channel_state.is_quiescent()
11469			// Cleared upon receiving `revoke_and_ack`. Since we're not queiscent, as we just
11470			// checked above, we intentionally don't disconnect our counterparty if we're waiting on
11471			// a monitor update or signer request.
11472			|| (self.context.is_waiting_on_peer_pending_channel_update()
11473				&& !self.context.is_monitor_or_signer_pending_channel_update())
11474		{
11475			// This is the first tick we've seen after expecting to make forward progress.
11476			self.context.sent_message_awaiting_response = Some(1);
11477			debug_assert!(DISCONNECT_PEER_AWAITING_RESPONSE_TICKS > 1);
11478			false
11479		} else {
11480			// Don't disconnect when we're not waiting on a response.
11481			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					// If we're a V1 channel or we haven't yet sent our `tx_signatures` for a dual
11509					// funded channel, the funding tx couldn't be broadcasted yet, so just short-circuit
11510					// the shutdown logic.
11511					not_broadcasted_initial_funding = true;
11512				}
11513			}
11514		}
11515		if not_broadcasted_initial_funding {
11516			// Spec says we should fail the connection, not the channel, but that's nonsense, there
11517			// are plenty of reasons you may want to fail a channel pre-funding, and spec says you
11518			// can do that via error message without getting a connection fail anyway...
11519			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		// If we have any LocalAnnounced updates we'll probably just get back an update_fail_htlc
11566		// immediately after the commitment dance, but we can send a Shutdown because we won't send
11567		// any further commitment updates after we set LocalShutdownSent.
11568		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		// From here on out, we may not fail!
11600
11601		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		// We can't send our shutdown until we've committed all of our pending HTLCs, but the
11636		// remote side is unlikely to accept any new HTLCs, so we go ahead and "free" any holding
11637		// cell HTLCs and return them to fail the payment.
11638		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()); // First is the multisig dummy
11663
11664		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			// this is required to stop potential overflow in build_closing_transaction
11767			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				// The remote end may have decided to revoke their output due to inconsistent dust
11800				// limits, so check for that case by re-checking the signature here.
11801				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				// They have to pay, so pick the highest fee in the overlapping range.
11892				// We should never set an upper bound aside from their full balance
11893				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				// The proposed fee is in our acceptable range, accept it and broadcast!
11905				propose_fee!(msg.fee_satoshis);
11906			}
11907		} else {
11908			// Old fee style negotiation. We don't bother to enforce whether they are complying
11909			// with the "making progress" requirements, we just comply and hope for the best.
11910			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	/// Determines whether the parameters of an incoming HTLC to be forwarded satisfy the channel's
11957	/// [`ChannelConfig`]. This first looks at the channel's current [`ChannelConfig`], and if
11958	/// unsuccessful, falls back to the previous one if one exists.
11959	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	/// When this function is called, the HTLC is already irrevocably committed to the channel;
11983	/// this function determines whether to fail the HTLC, or forward / claim it.
11984	#[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	/// Returns true if this channel has been marked as awaiting a monitor update to move forward.
12048	/// Allowed in any state (including after shutdown)
12049	pub fn is_awaiting_monitor_update(&self) -> bool {
12050		self.context.channel_state.is_monitor_update_in_progress()
12051	}
12052
12053	/// Gets the latest [`ChannelMonitorUpdate`] ID which has been released and is in-flight.
12054	pub fn get_latest_unblocked_monitor_update_id(&self) -> u64 {
12055		self.context.get_latest_unblocked_monitor_update_id()
12056	}
12057
12058	/// Returns the next blocked monitor update, if one exists, and a bool which indicates a
12059	/// further blocked monitor update exists after the next.
12060	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	/// Pushes a new monitor update into our monitor update queue, returning it if it should be
12071	/// immediately given to the user for persisting or `None` if it should be held as blocked.
12072	#[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	/// On startup, its possible we detect some monitor updates have actually completed (and the
12087	/// ChannelManager was simply stale). In that case, we should simply drop them, which we do
12088	/// here after logging them.
12089	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	/// Returns true if the channel is awaiting the persistence of the initial ChannelMonitor.
12111	/// If the channel is outbound, this implies we have not yet broadcasted the funding
12112	/// transaction. If the channel is inbound, this implies simply that the channel has not
12113	/// advanced state.
12114	#[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			// If we're not a 0conf channel, we'll be waiting on a monitor update with only
12122			// AwaitingChannelReady set, though our peer could have sent their channel_ready.
12123			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 we're a 0-conf channel, we'll move beyond AwaitingChannelReady immediately even while
12129			// waiting for the initial monitor persistence. Thus, we check if our commitment
12130			// transaction numbers have both been iterated only exactly once (for the
12131			// funding_signed), and we're awaiting monitor update.
12132			//
12133			// If we got here, we shouldn't have yet broadcasted the funding transaction (as the
12134			// only way to get an awaiting-monitor-update state during initial funding is if the
12135			// initial monitor persistence is still pending).
12136			//
12137			// Because deciding we're awaiting initial broadcast spuriously could result in
12138			// funds-loss (as we don't have a monitor, but have the funding transaction confirmed),
12139			// we hard-assert here, even in production builds.
12140			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	/// Gets the latest inbound SCID alias from our peer, or if none exists, the channel's real
12149	/// SCID.
12150	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	/// Returns true if our channel_ready has been sent
12155	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	/// Returns true if our peer has either initiated or agreed to shut down the channel.
12161	pub fn received_shutdown(&self) -> bool {
12162		self.context.channel_state.is_remote_shutdown_sent()
12163	}
12164
12165	/// Returns true if we either initiated or agreed to shut down the channel.
12166	pub fn sent_shutdown(&self) -> bool {
12167		self.context.channel_state.is_local_shutdown_sent()
12168	}
12169
12170	/// Returns true if we initiated to shut down the channel.
12171	pub fn initiated_shutdown(&self) -> bool {
12172		self.context.local_initiated_shutdown.is_some()
12173	}
12174
12175	/// Returns true if this channel is fully shut down. True here implies that no further actions
12176	/// may/will be taken on this channel, and thus this object should be freed. Any future changes
12177	/// will be handled appropriately by the chain monitor.
12178	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		// Called:
12200		//  * always when a new block/transactions are confirmed with the new height
12201		//  * when funding is signed with a height of 0
12202		if !self.check_funding_meets_minimum_depth(&self.funding, height) {
12203			return None;
12204		}
12205
12206		// Note that we don't include ChannelState::WaitingForBatch as we don't want to send
12207		// channel_ready until the entire batch is ready.
12208		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			// We got a reorg but not enough to trigger a force close, just ignore.
12217			false
12218		} else {
12219			if self.funding.funding_tx_confirmation_height != 0 &&
12220				self.context.channel_state < ChannelState::ChannelReady(ChannelReadyFlags::new())
12221			{
12222				// We should never see a funding transaction on-chain until we've received
12223				// funding_signed (if we're an outbound channel), or seen funding_generated (if we're
12224				// an inbound channel - before that we have no known funding TXID). The fuzzer,
12225				// however, may do this and we shouldn't treat it as a bug.
12226				#[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			// We got a reorg but not enough to trigger a force close, just ignore.
12232			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	/// Returns `Some` if a splice [`FundingScope`] was promoted.
12277	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				// Like any failure, this releases what the contribution reserved for itself. Its
12337				// record covers what it inherited, so anything else it shares with the promoted
12338				// transaction was added back and is released, as it is for a round negotiated after
12339				// the promoted one.
12340				Some(SpliceFundingFailed::from_contribution(contribution))
12341			} else {
12342				// The promoted transaction uses nothing a queued contribution holds, and every
12343				// round it could have inherited from is being replaced, so it now owns all of its
12344				// reservations: a later failure must release all of them.
12345				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			// Rounds negotiated before the promoted one may have lent it the inputs and outputs
12357			// it uses, while rounds negotiated after it can only have inherited them from it.
12358			// Keep the two apart, as they release their parts differently below.
12359			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			// Each dropped contribution releases only what it reserved itself: anything it
12397			// inherited is released by the round it inherited from, and anything a surviving
12398			// queued contribution reuses now belongs to it and is released only if it fails.
12399			//
12400			// A round negotiated before the promoted one also withholds what the promoted
12401			// transaction uses, as the promoted round may have inherited it from there. A round
12402			// negotiated after it, like a negotiation still in progress, can only have inherited
12403			// such a part, which its record covers; anything else it shares with the promoted
12404			// transaction was added back, so it is released even though the promoted transaction
12405			// uses it.
12406			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	/// Generates a pending `splice_locked` once any funding negotiation has completed, along with
12474	/// the resulting funding promotion if the counterparty's lock was already received.
12475	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		// We intentionally check this early even though `check_get_splice_locked` already does to
12480		// prevent scanning splice candidates unnecessarily.
12481		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	/// When a transaction is confirmed, we check whether it is or spends the funding transaction
12515	/// In the first case, we store the confirmation height and calculating the short channel id.
12516	/// In the second, we simply return an Err indicating we need to be force-closed now.
12517	#[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		// Confirmation callbacks may arrive behind our current best block. Use the later height so
12524		// exiting quiescence below cannot release an HTLC which is already too close to expiry.
12525		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			// If we allow 1-conf funding, we may need to check for channel_ready or splice_locked here
12534			// and send it immediately instead of waiting for a best_block_updated call (which may have
12535			// already happened for this block).
12536			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 this is a coinbase transaction and not a 0-conf channel
12542				// we should update our min_depth to 100 to handle coinbase maturity
12543				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	/// When a new block is connected, we check the height of the block against outbound holding
12632	/// cell HTLCs in case we need to give up on them prematurely and time them out. Everything
12633	/// else (e.g. commitment transaction broadcasts, HTLC transaction broadcasting, etc) is
12634	/// handled by the ChannelMonitor.
12635	///
12636	/// If we return Err, the channel may have been closed, at which point the standard
12637	/// requirements apply - no calls may be made except those explicitly stated to be allowed
12638	/// post-shutdown.
12639	///
12640	/// May return some HTLCs (and their payment_hash) which have timed out and should be failed
12641	/// back.
12642	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	/// Removes outbound holding-cell HTLCs which are too close to expiry to safely send.
12655	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		// Refuse to send an HTLC when our counterparty should almost certainly just fail it for
12660		// expiring ~now.
12661		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		// Check if the funding transaction was unconfirmed
12693		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 we've sent channel_ready (or have both sent and received channel_ready), and
12714			// the funding transaction has become unconfirmed, we'll probably get a new SCID when
12715			// it re-confirms.
12716			//
12717			// Worse, if the funding has un-confirmed we could have accepted some HTLC(s) over it
12718			// and are now at risk of double-spend. While its possible, even likely, that this is
12719			// just a trivial reorg and we should wait to see the new block connected in the next
12720			// call, its also possible we've been double-spent. To avoid further loss of funds, we
12721			// need some kind of method to freeze the channel and avoid accepting further HTLCs,
12722			// but absent such a method, we just force-close.
12723			//
12724			// The one exception we make is for 0-conf channels, which we decided to trust anyway,
12725			// in which case we simply track the previous SCID as a `historical_scids` the same as
12726			// after a channel is spliced.
12727			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					// Reset the original short_channel_id so that we'll generate a closure
12735					// `channel_update` broadcast event.
12736					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			// If funding_tx_confirmed_in is unset, the channel must not be active
12746			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				// Check if the splice funding transaction was unconfirmed
12771				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							// We can only promote on blocks connected, which is when we expect
12806							// `chain_node_signer` to be `Some`.
12807							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	/// Checks if any funding transaction is no longer confirmed in the main chain. This may
12857	/// force-close the channel, but may also indicate a harmless reorganization of a block or two
12858	/// before the channel has reached channel_ready or splice_locked, and we can just wait for more
12859	/// blocks.
12860	#[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				// We handle the funding disconnection by calling best_block_updated with a height one
12871				// below where our funding was connected, implying a reorg back to conf_height - 1.
12872				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				// We never learned about the funding confirmation anyway, just ignore
12887				Ok(())
12888			}
12889		} else {
12890			Ok(())
12891		}
12892	}
12893
12894	// Methods to get unprompted messages to send to the remote end (or where we already returned
12895	// something in the handler for the message that prompted this message):
12896
12897	/// Gets an UnsignedChannelAnnouncement for this channel. The channel must be publicly
12898	/// announceable and available for use (have exchanged [`ChannelReady`] messages in both
12899	/// directions). Should be used for both broadcasted announcements and in response to an
12900	/// AnnouncementSignatures message from the remote peer.
12901	///
12902	/// Will only fail if we're not in a state where channel_announcement may be sent (including
12903	/// closing).
12904	///
12905	/// This will only return ChannelError::Ignore upon failure.
12906	///
12907	/// [`ChannelReady`]: crate::ln::msgs::ChannelReady
12908	#[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	/// Signs the given channel announcement, returning a ChannelError::Ignore if no keys are
13004	/// available.
13005	#[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	/// Processes an incoming announcement_signatures message, providing a fully-signed
13036	/// channel_announcement message which we can broadcast and storing our counterparty's
13037	/// signatures for later reconstruction/rebroadcast of the channel_announcement.
13038	#[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		// Ignore sigs signed over a `short_channel_id` other than our current one (e.g. stale
13044		// pre-splice sigs arriving after our side has promoted). Verifying them against the
13045		// current `UnsignedChannelAnnouncement` would always fail the hash check, but per BOLT #7
13046		// that's not a protocol violation warranting a force-close.
13047		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	/// Gets a signed channel_announcement for this channel, if we previously received an
13079	/// announcement_signatures from our counterparty.
13080	#[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		// The sending node:
13096		//   - if it has sent `commitment_signed` for an interactive transaction construction but
13097		//     it has not received `tx_signatures`:
13098		self.context
13099			.interactive_tx_signing_session
13100			.as_ref()
13101			.filter(|session| !session.has_received_tx_signatures())
13102			.map(|signing_session| {
13103				// - MUST include the `next_funding` TLV.
13104				// - MUST set `next_funding_txid` to the txid of that interactive transaction.
13105				let mut next_funding = msgs::NextFunding {
13106					txid: signing_session.unsigned_tx().compute_txid(),
13107					retransmit_flags: 0,
13108				};
13109
13110				// - if it has not received `commitment_signed` for this `next_funding_txid`:
13111				//   - MUST set the `commitment_signed` bit in `retransmit_flags`.
13112				if !signing_session.has_received_commitment_signed() {
13113					next_funding.retransmit(msgs::NextFundingFlag::CommitmentSigned);
13114				}
13115
13116				next_funding
13117			})
13118		//   - otherwise:
13119		//     - MUST NOT include the `next_funding` TLV.
13120	}
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 `my_current_funding_locked` is included:
13133				//   - if `announce_channel` is set for this channel:
13134				//     - if it has not received `announcement_signatures` for that transaction:
13135				//       - MUST set the `announcement_signatures` bit to `1` in `retransmit_flags`.
13136				//     - otherwise:
13137				//       - MUST set the `announcement_signatures` bit to `0` in `retransmit_flags`.
13138				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	/// May panic if called on a channel that wasn't immediately-previously
13151	/// self.remove_uncommitted_htlcs_and_mark_paused()'d
13152	#[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		// This is generally the first function which gets called on any given channel once we're
13157		// up and running normally. Thus, we take this opportunity to attempt to resolve the
13158		// `holder_commitment_point` to get any keys which we are currently missing.
13159		self.holder_commitment_point.try_resolve_pending(
13160			&self.context.holder_signer, &self.context.secp_ctx, logger,
13161		);
13162		// Prior to static_remotekey, my_current_per_commitment_point was critical to claiming
13163		// current to_remote balances. However, it no longer has any use, and thus is now simply
13164		// set to a dummy (but valid, as required by the spec) public key.
13165		// fuzzing mode marks a subset of pubkeys as invalid so that we can hit "invalid pubkey"
13166		// branches, but we unwrap it below, so we arbitrarily select a dummy pubkey which is both
13167		// valid, and valid in fuzzing mode's arbitrary validity criteria:
13168		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			// The protocol has two different commitment number concepts - the "commitment
13184			// transaction number", which starts from 0 and counts up, and the "revocation key
13185			// index" which starts at INITIAL_COMMITMENT_NUMBER and counts down. We track
13186			// commitment transaction numbers by the index which will be used to reveal the
13187			// revocation key for that commitment transaction, which means we have to convert them
13188			// to protocol-level commitment numbers here...
13189
13190			// next_local_commitment_number is the next commitment_signed number we expect to
13191			// receive (indicating if they need to resend one that we missed).
13192			next_local_commitment_number: INITIAL_COMMITMENT_NUMBER - self.holder_commitment_point.next_transaction_number(),
13193			// We have to set next_remote_commitment_number to the next revoke_and_ack we expect to
13194			// receive, however we track it by the next commitment number for a remote transaction
13195			// (which is one further, as they always revoke previous commitment transaction, not
13196			// the one we send) so we have to decrement by 1. Note that if
13197			// counterparty_next_commitment_transaction_number is INITIAL_COMMITMENT_NUMBER we will have
13198			// dropped this channel on disconnect as it hasn't yet reached AwaitingChannelReady so we can't
13199			// overflow here.
13200			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	/// Builds a [`FundingTemplate`] for splicing or RBF, if the channel state allows it.
13209	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			// Channel can never RBF (e.g., zero-conf).
13263			(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			// The pending candidate can no longer be replaced. Return a fresh template so
13269			// that any non-overlapping contribution waits for it to lock instead of being
13270			// presented as an RBF attempt. Submission separately rejects stale RBF templates
13271			// built before confirmation or receipt of `splice_locked`.
13272			(None, None)
13273		} else if let Some(pending_splice) = self.pending_splice.as_ref() {
13274			// A splice is pending — either a completed negotiation that hasn't locked yet
13275			// or an in-progress negotiation. In either case, the user's splice will need
13276			// to satisfy the minimum RBF feerate. When that feerate is unknown (the splice
13277			// was last written by an LDK version prior to 0.3, which persisted neither it nor
13278			// our contribution), the minimum RBF feerate is left unset so the new splice is
13279			// queued and begins as a fresh splice once the pending candidate locks, rather than
13280			// attempting to replace it.
13281			//
13282			// If an in-progress negotiation later fails (e.g., tx_abort), the derived
13283			// min_rbf_feerate becomes stale, causing a slightly higher feerate than
13284			// necessary. Call splice_channel again after receiving SpliceNegotiationFailed to get a
13285			// fresh template without the stale RBF constraint.
13286			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			// No pending splice — fresh splice with no RBF constraint.
13295			(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	/// Returns whether this channel can ever RBF, independent of splice state.
13316	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	/// Whether a committed-but-not-yet-negotiating contribution can replace the pending candidate
13327	/// via RBF, rather than having to wait for that candidate to lock. Used to classify a queued
13328	/// contribution's status while it awaits quiescence.
13329	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		// A zero-conf channel can never RBF, and a candidate that is already locking can no longer
13335		// be replaced.
13336		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		// The replacement must pay a higher feerate than the most recent round: the one currently
13345		// under negotiation if any (which is the candidate we would replace once it signs),
13346		// otherwise the most recently negotiated candidate. The in-flight feerate is fixed when the
13347		// round starts, so affordability is determinable even before it signs.
13348		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	/// Attempts to adjust the contribution's feerate to the minimum RBF feerate so the splice can
13408	/// proceed as an RBF immediately rather than waiting for the pending splice to lock.
13409	/// Returns the adjusted contribution on success, or the original on failure.
13410	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		// Refuse the contribution if one of ours is already queued or under negotiation. Like any
13447		// failure, the refusal releases what the contribution reserved itself.
13448		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		// Reject the contribution if its record of inherited inputs and outputs names anything no
13472		// live splice attempt still commits to: it was built against splice state that no longer
13473		// exists (a stale template), and the caller should build a new contribution from a fresh
13474		// one. The rejection releases what the contribution reserved itself.
13475		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		// If a pending splice exists with negotiated candidates, attempt to adjust the
13527		// contribution's feerate to the minimum RBF feerate so it can proceed as an RBF immediately
13528		// rather than waiting for the splice to lock. We may only queue it for a later fresh splice
13529		// if it does not reuse any inputs or outputs committed to pending rounds.
13530		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		// A queued splice never coexists with a negotiation we initiated: we return early above if
13570		// one is already in flight, and a queued action is cleared the moment it becomes our
13571		// negotiation at quiescence. It may coexist with a counterparty-initiated negotiation (e.g.
13572		// queuing our own contribution while accepting their splice), so we only rule out our own.
13573		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	/// Returns a reference to the funding contribution queued by a pending [`QuiescentAction`],
13585	/// if any.
13586	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	/// Consumes and returns the funding contribution from the pending [`QuiescentAction`], if any.
13594	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		// Rotate the funding pubkey using the prev_funding_txid as a tweak
13609		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				// If we've already sent `stfu` and haven't received the counterparty's yet, we know
13690				// it corresponds to our action.
13691				ChannelError::WarnAndDisconnect(str.into())
13692			} else {
13693				// We don't need to send `tx_abort` because our action still pending means we're not
13694				// quiescent for it.
13695				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		// We typically don't reset the pending funding negotiation when we're in
13740		// [`FundingNegotiation::AwaitingSignatures`] since we're able to resume it on
13741		// re-establishment, so we still need to handle this case separately if the user wishes to
13742		// cancel. If they've yet to call [`Channel::funding_transaction_signed`], then we can
13743		// guarantee to never have sent any signatures to the counterparty, or have processed any
13744		// signatures from them.
13745		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	/// Checks during handling splice_init
13774	pub fn validate_splice_init(&self, msg: &msgs::SpliceInit) -> Result<(), ChannelError> {
13775		// - If it has received shutdown:
13776		//   MUST send a warning and close the connection or send an error
13777		//   and fail the channel.
13778		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		// Check if a splice has been initiated already.
13789		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		// We allow parties to draw from their previous reserve, as long as they satisfy their v2 reserve
13838		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		// Rotate the pubkeys using the prev_funding_txid as a tweak
13944		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		// Adjust for the feerate and clone so we can store it for future RBF re-use.
13973		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	/// Checks during handling tx_init_rbf for an existing splice
14026	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		// Reuse funding pubkeys from the last negotiated candidate since all RBF candidates
14097		// for the same splice share the same funding output script.
14098		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		// If no queued contribution, try prior contribution from previous negotiation.
14118		// Failing here means the RBF would erase our splice — reject it.
14119		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		// Consume the appropriate contribution source.
14162		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			// The carried-forward contribution only reuses what the prior round committed to, so
14182			// record everything as inherited: a failure of the new round then releases nothing, as
14183			// the prior round's transaction may still confirm.
14184			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	/// The balances returned here should only be used to check that both parties still hold
14369	/// their respective reserves *after* a splice. This function also checks that both local
14370	/// and remote commitments still have at least one output after the splice, which is
14371	/// particularly relevant for zero-reserve channels.
14372	///
14373	/// Do NOT use this to determine how much the holder can splice out of the channel. The balance
14374	/// of the holder after a splice is not necessarily equal to the funds they can splice out
14375	/// of the channel due to the v2 reserve, and the zero-reserve-at-least-one-output
14376	/// requirements. Note you cannot simply subtract out the reserve, as splicing funds out
14377	/// of the channel changes the reserve the holder must keep in the channel.
14378	///
14379	/// See [`FundedChannel::get_next_splice_out_maximum`] for the maximum value of the next
14380	/// splice out of the holder's balance.
14381	fn get_holder_counterparty_balances_floor_incl_fee(
14382		&self, funding: &FundingScope,
14383	) -> Result<(Amount, Amount), String> {
14384		// Make sure that that the funder of the channel can pay the transaction fees for an additional
14385		// nondust HTLC on the channel.
14386		let addl_nondust_htlc_count = 1;
14387		// We are not interested in dust exposure
14388		let dust_exposure_limiting_feerate = None;
14389
14390		// Different dust limits on the local and remote commitments cause the commitment
14391		// transaction fee to be different depending on the commitment, so we grab the floor
14392		// of both balances across both commitments here.
14393		//
14394		// `get_channel_stats` also checks for at least one output on the commitment given
14395		// these parameters. This is particularly relevant for zero-reserve channels.
14396		//
14397		// This "at-least-one-output" check is why we still run both checks on
14398		// zero-fee-commitment channels, even though those channels don't suffer from the
14399		// commitment transaction fee asymmetry.
14400		let (local_stats, _local_htlcs) = self
14401			.context
14402			.get_next_local_commitment_stats(
14403				funding,
14404				None, // htlc_candidate
14405				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, // htlc_candidate
14418				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	/// Determines the maximum value that the holder can splice out of the channel, accounting
14443	/// for the updated reserves after said splice. This maximum also makes sure the local
14444	/// commitment retains at least one output after the splice, which is particularly relevant
14445	/// for zero-reserve channels.
14446	fn get_next_splice_out_maximum(&self, funding: &FundingScope) -> Result<Amount, String> {
14447		// We are not interested in dust exposure
14448		let dust_exposure_limiting_feerate = None;
14449
14450		// When reading the available balances, we take the remote's view of the pending
14451		// HTLCs, see `tx_builder` for further details
14452		let (remote_stats, _remote_htlcs) = self
14453			.context
14454			.get_next_remote_commitment_stats(
14455				funding,
14456				None, // htlc_candidate
14457				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			// After this max splice out, validation passes, accounting for the updated reserves
14473			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				// When the counterparty's contribution is non-negative, we don't validate
14479				// the post splice channel value against `min_funding_satoshis`
14480				0,
14481			)
14482			.unwrap();
14483			// Splice-out an additional satoshi, and validation fails!
14484			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				// When the counterparty's contribution is non-negative, we don't validate
14490				// the post splice channel value against `min_funding_satoshis`
14491				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	/// Queues up an outbound HTLC to send by placing it in the holding cell. You should call
14541	/// [`Self::maybe_free_holding_cell_htlcs`] in order to actually generate and send the
14542	/// commitment update.
14543	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			// This method is only called for forwarded HTLCs, which are never held at the next hop
14559			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	/// Adds a pending outbound HTLC to this channel, note that you probably want
14572	/// [`Self::send_htlc_and_commit`] instead cause you'll want both messages at once.
14573	///
14574	/// This returns a boolean indicating whether we are in a state where we can add HTLCs on the wire.
14575	/// Reasons we may not be able to add HTLCs on the wire include:
14576	///
14577	/// * In cases where we're waiting on the remote peer to send us a revoke_and_ack, we
14578	///   wouldn't be able to determine what they actually ACK'ed if we have two sets of updates
14579	///   awaiting ACK.
14580	/// * In cases where we're marked MonitorUpdateInProgress, we cannot commit to a new state as
14581	///   we may not yet have sent the previous commitment update messages and will need to
14582	///   regenerate them.
14583	///
14584	/// You MUST call [`Self::send_commitment_no_state_update`] prior to calling any other methods
14585	/// on this [`FundedChannel`] if `force_holding_cell` is false.
14586	///
14587	/// `Err`'s will always be temporary channel failures.
14588	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			// Note that this should never really happen, if we're !is_live() on receipt of an
14634			// incoming HTLC for relay will result in us rejecting the HTLC and we won't allow
14635			// the user to send directly into a !is_live() channel. However, if we
14636			// disconnected during the time the previous hop was doing the commitment dance we may
14637			// end up getting here after the forwarding delay. In any case, returning an
14638			// IgnoreError will get ChannelManager to do the right thing and fail backwards now.
14639			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		// Now update local state:
14665		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		// Record the approximate time when the HTLC is sent to the peer. This timestamp is later used to calculate the
14681		// htlc hold time for reporting back to the sender. There is some freedom to report a time including or
14682		// excluding our own processing time. What we choose here doesn't matter all that much, because it will probably
14683		// just shift sender-applied penalties between our incoming and outgoing side. So we choose measuring points
14684		// that are simple to implement, and we do it on the outgoing side because then the failure message that encodes
14685		// the hold time still needs to be built in channel manager.
14686		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	/// Gets the available balances, see [`AvailableBalances`]'s fields for more info.
14706	///
14707	/// Returns `Err` if some party cannot currently pay for the HTLCs outbound from said party, and the anchors and
14708	/// transaction fee if they are the funder.
14709	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		// We can upgrade the status of some HTLCs that are waiting on a commitment, even if we
14735		// fail to generate this, we still are at least at a position where upgrading their status
14736		// is acceptable.
14737		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				// Swap against a dummy variant to avoid a potentially expensive clone of `OutboundHTLCOutcome::Failure(HTLCFailReason)`
14757				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			// Soon, we will switch this to `LatestCounterpartyCommitment`,
14786			// and provide the full commit tx instead of the information needed to rebuild it.
14787			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							// We check !offered as this is the HTLC from the counterparty's point of view.
14814							.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	/// Only fails in case of signer rejection. Used for channel_reestablish commitment_signed
14863	/// generation when we shouldn't change HTLC/channel state.
14864	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		// Get the fee tests from `build_commitment_no_state_update`
14878		#[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	/// Adds a pending outbound HTLC to this channel, and builds a new remote commitment
14928	/// transaction and generates the corresponding [`ChannelMonitorUpdate`] in one go.
14929	///
14930	/// Shorthand for calling [`Self::send_htlc`] followed by a commitment update, see docs on
14931	/// [`Self::send_htlc`] and [`Self::build_commitment_no_state_update`] for more info.
14932	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		// All [`LocalHTLCFailureReason`] errors are temporary, so they are [`ChannelError::Ignore`].
14953		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	/// Applies the `ChannelUpdate` and returns a boolean indicating whether a change actually
14972	/// happened.
14973	#[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	/// Begins the shutdown process, getting a message for the remote peer and returning all
14989	/// holding cell HTLCs for payment failure.
14990	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				// use override shutdown script if provided
15047				let shutdown_scriptpubkey = match override_shutdown_script {
15048					Some(script) => script,
15049					None => {
15050						// otherwise, use the shutdown scriptpubkey provided by the signer
15051						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		// From here on out, we may not fail!
15072		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		// Go ahead and drop holding cell updates as we'd rather fail payments than wait to send
15105		// our shutdown until we've committed all of the pending changes.
15106		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	// Miscellaneous utilities
15128
15129	#[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			// Upper bound by capacity. We make it a bit less than full capacity to prevent attempts
15145			// to use full capacity. This is an effort to reduce routing failures, because in many cases
15146			// channel might have been used to route very small values (either by honest users or as DoS).
15147			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			// We don't check `is_waiting_on_peer_pending_channel_update` prior to setting the flag
15231			// because it considers pending updates from either node. This means we may accept a
15232			// counterparty `stfu` while they had pending updates, but that's fine as we won't send
15233			// ours until _all_ pending updates complete, allowing the channel to become quiescent
15234			// then.
15235			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		// We already sent `stfu` and are now processing theirs. It may be in response to ours, or
15242		// we happened to both send `stfu` at the same time and a tie-break is needed.
15243		let is_holder_quiescence_initiator = !msg.initiator || self.funding.is_outbound();
15244
15245		// We were expecting to receive `stfu` because we already sent ours.
15246		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			// Since we've already sent `stfu`, it should not be possible for one of our updates to
15253			// be pending, so anything pending currently must be from a counterparty update. We may
15254			// have a monitor update pending if we've processed a message from the counterparty, but
15255			// we don't consider this when becoming quiescent since the states are not mutually
15256			// exclusive.
15257			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					// We may have lost a `QuiescentAction::Splice` if we had already started the
15275					// quiescence handshake for it, but an existing pending splice became locked,
15276					// invalidating the queued splice.
15277					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					// Re-validate the contribution now that we're quiescent and
15294					// balances are stable. Outbound HTLCs may have been sent between
15295					// funding_contributed and quiescence, reducing the holder's
15296					// balance. If invalid, disconnect and return the contribution so
15297					// the user can reclaim their inputs.
15298					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					// In quiescence test we want to just hang out here, letting the test manually
15346					// leave quiescence.
15347				},
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		// We must never see both stfu flags set, we always set the quiescent flag instead.
15356		debug_assert!(
15357			!(self.context.channel_state.is_local_stfu_sent()
15358				&& self.context.channel_state.is_remote_stfu_sent())
15359		);
15360
15361		// We only need to send `stfu` when we're awaiting quiescence and haven't sent it yet, or
15362		// in response to a counterparty one.
15363		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		// We retry sending `stfu` every time pending messages are polled, so only log why we're
15373		// unable to on the first attempt, lest we spam the log.
15374		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			// Since we may have also attempted to initiate quiescence but the counterparty
15395			// initiated first, we'll retry after we're no longer quiescent.
15396			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		// Make sure we either finished the quiescence handshake and are quiescent, or we never
15431		// attempted to initiate quiescence at all.
15432		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(&current_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		// Drains the oldest historical SCIDs until reaching one without
15469		// CHANNEL_ANNOUNCEMENT_PROPAGATION_DELAY confirmations.
15470		self.context.historical_scids.drain(0..end)
15471	}
15472}
15473
15474/// A not-yet-funded outbound (from holder) channel using V1 channel establishment.
15475pub(super) struct OutboundV1Channel<SP: SignerProvider> {
15476	pub funding: FundingScope,
15477	pub context: ChannelContext<SP>,
15478	pub unfunded_context: UnfundedChannelContext,
15479	/// We tried to send an `open_channel` message but our commitment point wasn't ready.
15480	/// This flag tells us we need to send it when we are retried once the
15481	/// commitment point is ready.
15482	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)] // TODO(dual_funding): Remove once opending V2 channels is enabled.
15491	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		// At this point, we do not know what `dust_limit_satoshis` the counterparty will want for themselves,
15500		// so we set the channel reserve with no regard for their dust limit, and fail the channel if they want
15501		// a dust limit higher than our selected reserve.
15502		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			// Protocol level safety check in place, although it should never happen because
15519			// of `MIN_THEIR_CHAN_RESERVE_SATOSHIS` and `MIN_CHANNEL_VALUE_SATOSHIS`
15520			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		// We initialize `signer_pending_open_channel` to false, and leave setting the flag
15560		// for when we try to generate the open_channel message.
15561		let chan = Self { funding, context, unfunded_context, signer_pending_open_channel: false };
15562		Ok(chan)
15563	}
15564
15565	/// Only allowed after [`FundingScope::channel_transaction_parameters`] is set.
15566	#[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	/// Updates channel state with knowledge of the funding transaction's txid/index, and generates
15604	/// a funding_created message for the remote peer.
15605	/// Panics if called at some time other than immediately after initial handshake, if called twice,
15606	/// or if called on an inbound channel.
15607	/// Note that channel_id changes during this call!
15608	/// Do NOT broadcast the funding transaction until after a successful funding_signed call!
15609	/// If an Err is returned, it is a ChannelError::Close.
15610	#[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		// Now that we're past error-generating stuff, update our local state:
15627
15628		self.context.channel_state = ChannelState::FundingNegotiated(FundingNegotiatedFlags::new());
15629		self.context.channel_id = ChannelId::v1_from_funding_outpoint(funding_txo);
15630
15631		// If the funding transaction is a coinbase transaction, we need to set the minimum depth to 100.
15632		// We can skip this if it is a zero-conf channel.
15633		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	/// If we receive an error message, it may only be a rejection of the channel type we tried,
15648	/// not of our ability to open any channel at all. Thus, on error, we should first call this
15649	/// and see if we get a new `OpenChannel` message, otherwise the channel is failed.
15650	#[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	/// Returns true if we can resume the channel by sending the [`msgs::OpenChannel`] again.
15662	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	// Message handlers
15725	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	/// Handles a funding_signed message from the remote end.
15739	/// If this call is successful, broadcast the funding transaction (and not before!)
15740	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	/// Indicates that the signer may have some signatures for us, so we should retry if we're
15808	/// blocked.
15809	#[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 we were pending a commitment point, retry the signer and advance to an
15814		// available state.
15815		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	/// Unsets the existing funding information.
15835	///
15836	/// The channel must be immediately shut down after this with a call to
15837	/// [`ChannelContext::force_shutdown`].
15838	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
15847/// A not-yet-funded inbound (from counterparty) channel using V1 channel establishment.
15848pub(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
15855/// Fetches the [`ChannelTypeFeatures`] that will be used for a channel built from a given
15856/// [`msgs::CommonOpenChannelFields`].
15857pub(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	// We only support the channel types defined by the `ChannelManager` in
15871	// `provided_channel_type_features`. The channel type must always support
15872	// `static_remote_key`, either implicitly with `option_zero_fee_commitments`
15873	// or explicitly.
15874	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	// Make sure we support all of the features behind the channel type.
15889	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	/// Creates a new channel from a remote sides' request for one.
15903	/// Assumes chain_hash has already been checked and corresponds with what we expect!
15904	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		// First check the channel type is known, failing before we do anything else if we don't
15919		// support this channel type.
15920		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	/// Marks an inbound channel as accepted and generates a [`msgs::AcceptChannel`] message which
15979	/// should be sent back to the counterparty node.
15980	///
15981	/// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
15982	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	/// This function is used to explicitly generate a [`msgs::AcceptChannel`] message for an
16000	/// inbound channel. If the intention is to accept an inbound channel, use
16001	/// [`InboundV1Channel::accept_inbound_channel`] instead.
16002	///
16003	/// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
16004	#[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	/// Enables the possibility for tests to extract a [`msgs::AcceptChannel`] message for an
16047	/// inbound channel without accepting it.
16048	///
16049	/// [`msgs::AcceptChannel`]: crate::ln::msgs::AcceptChannel
16050	#[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			// BOLT 2 says that if we disconnect before we send funding_signed we SHOULD NOT
16073			// remember the channel, so it's safe to just send an error_message here and drop the
16074			// channel.
16075			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		// Promote the channel to a full-fledged one now that we have updated the state and have a
16121		// `ChannelMonitor`.
16122		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	/// Indicates that the signer may have some signatures for us, so we should retry if we're
16145	/// blocked.
16146	#[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
16165// A not-yet-funded channel using V2 channel establishment.
16166pub(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	/// The current interactive transaction construction session under negotiation.
16172	pub interactive_tx_constructor: Option<InteractiveTxConstructor>,
16173}
16174
16175impl<SP: SignerProvider> PendingV2Channel<SP> {
16176	#[allow(dead_code)] // TODO(dual_funding): Remove once creating V2 channels is enabled.
16177	#[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	/// If we receive an error message, it may only be a rejection of the channel type we tried,
16249	/// not of our ability to open any channel at all. Thus, on error, we should first call this
16250	/// and see if we get a new `OpenChannelV2` message, otherwise the channel is failed.
16251	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	/// Creates a new dual-funded channel from a remote side's request for one.
16321	/// Assumes chain_hash has already been checked and corresponds with what we expect!
16322	/// TODO(dual_funding): Allow contributions, pass intended amount and inputs
16323	#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
16324	#[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		// TODO(dual_funding): Take these as input once supported
16332		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 /* push_msat not used in dual-funding */,
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	/// Marks an inbound channel as accepted and generates a [`msgs::AcceptChannelV2`] message which
16426	/// should be sent back to the counterparty node.
16427	///
16428	/// [`msgs::AcceptChannelV2`]: crate::ln::msgs::AcceptChannelV2
16429	#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
16430	#[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	/// This function is used to explicitly generate a [`msgs::AcceptChannelV2`] message for an
16449	/// inbound dual-funded channel. If the intention is to accept a V1 established inbound channel,
16450	/// use [`InboundV1Channel::accept_inbound_channel`] instead.
16451	///
16452	/// [`msgs::AcceptChannelV2`]: crate::ln::msgs::AcceptChannelV2
16453	#[allow(dead_code)] // TODO(dual_funding): Remove once V2 channels is enabled.
16454	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	/// Enables the possibility for tests to extract a [`msgs::AcceptChannelV2`] message for an
16494	/// inbound channel without accepting it.
16495	///
16496	/// [`msgs::AcceptChannelV2`]: crate::ln::msgs::AcceptChannelV2
16497	#[cfg(test)]
16498	#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
16499	pub fn get_accept_channel_v2_message(&self) -> msgs::AcceptChannelV2 {
16500		self.generate_accept_channel_v2_message()
16501	}
16502}
16503
16504// Unfunded channel utilities
16505
16506pub(super) fn get_initial_channel_type(
16507	config: &UserConfig, their_features: &InitFeatures,
16508) -> ChannelTypeFeatures {
16509	// The default channel type (ie the first one we try) depends on whether the channel is
16510	// public - if it is, we just go with `only_static_remotekey` as it's the only option
16511	// available. If it's private, we first try `scid_privacy` as it provides better privacy
16512	// with no other changes, and fall back to `only_static_remotekey`.
16513	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	// Optionally, if the user would like to negotiate `option_zero_fee_commitments` we set it now.
16522	// If they don't understand it (or we don't want it), we check the same conditions for
16523	// `option_anchors_zero_fee_htlc_tx`. The counterparty can still refuse the channel and we'll
16524	// try to fall back (all the way to `only_static_remotekey`).
16525	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		// `option_static_remote_key` is assumed by `option_zero_fee_commitments`.
16530		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		// We only care about writing out the current state as it was announced, ie only either
16546		// Enabled or Disabled. In the case of DisabledStaged, we most recently announced the
16547		// channel as enabled, so we write 0. For EnabledStaged, we similarly write a 1.
16548		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		// We only care about writing out the current state as if we had just disconnected, at
16571		// which point we always set anything but AnnouncementSigsReceived to NotSent.
16572		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		// Note that we write out as if remove_uncommitted_htlcs_and_mark_paused had just been
16594		// called.
16595
16596		write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
16597
16598		// `user_id` used to be a single u64 value. In order to remain backwards compatible with
16599		// versions prior to 0.0.113, the u128 is serialized as two separate u64 values. We write
16600		// the low bytes now and the optional high bytes later.
16601		let user_id_low = self.context.user_id as u64;
16602		user_id_low.write(writer)?;
16603
16604		// Version 1 deserializers expected to read parts of the config object here. Version 2
16605		// deserializers (0.0.99) now read config through TLVs, and as we now require them for
16606		// `minimum_depth` we simply write dummy values here.
16607		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						// We shouldn't be quiescent anymore upon reconnecting if:
16621						// - We were in quiescence but a splice/RBF was never negotiated or
16622						// - We were in quiescence but the splice negotiation failed due to
16623						// disconnecting
16624						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		// Write out the old serialization for shutdown_pubkey for backwards compatibility, if
16639		// deserialized from that format.
16640		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; // Drop
16664			}
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		// The elements of this vector will always be `Some` starting in 0.2,
16713		// but we still serialize the option to maintain backwards compatibility
16714		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					// Treat this as a Committed because we haven't received the CS - they'll
16738					// resend the claim/fail on reconnect as we all (hopefully) the missing CS.
16739					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		// Vec of (htlc_id, failure_code, sha256_of_onion)
16778		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					// Store the attribution data for later writing.
16815					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					// Store the attribution data for later writing.
16823					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					// We don't want to break downgrading by adding a new variant, so write a dummy
16831					// `::FailHTLC` variant and write the real malformed error as an optional TLV.
16832					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					// Push 'None' attribution data for FailMalformedHTLC, because FailMalformedHTLC uses the same
16839					// type 2 and is deserialized as a FailHTLC.
16840					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			// As for inbound HTLCs, if the update was only announced and never committed in a
16877			// commitment_signed, drop it.
16878			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		// Versions prior to 0.0.100 expected to read the fields of `last_sent_closing_fee` here,
16888		// however we are supposed to restart shutdown fee negotiation on reconnect (and wipe
16889		// `last_send_closing_fee` in `remove_uncommitted_htlcs_and_mark_paused`) so we should never
16890		// consider the stale state on reload.
16891		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		// Note that this field is ignored by 0.0.99+ as the TLV Optional variant is used instead.
16902		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		// Note that this field is ignored by 0.0.99+ as the TLV Optional variant is used instead.
16909		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		// If the channel type is something other than only-static-remote-key, then we need to have
16935		// older clients fail to deserialize this channel at all. If the type is
16936		// only-static-remote-key, we simply consider it "default" and don't write the channel type
16937		// out at all.
16938		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		// The same logic applies for `holder_selected_channel_reserve_satoshis` values other than
16946		// the default, and when `holder_max_htlc_value_in_flight_msat` is configured to be set to
16947		// a different percentage of the channel value then 10%, which older versions of LDK used
16948		// to set it to before the percentage was made configurable.
16949		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		// `user_id` used to be a single u64 value. In order to remain backwards compatible with
16976		// versions prior to 0.0.113, the u128 is serialized as two separate u64 values. Therefore,
16977		// we write the high bytes as an option here.
16978		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		// We prevent downgrades from 0.3 only in the case where the holder-selected reserve
16994		// is 0, as we've had support for counterparty selected 0-reserves in prior
16995		// releases.
16996		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		// Avoid writing any negotiations that are not at the signing stage yet, as they cannot be
17007		// resumed on reestablishment, but keep any already-negotiated candidates.
17008		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			// minimum_depth and counterparty_selected_channel_reserve_satoshis used to have a
17025			// default value instead of being Option<>al. Thus, to maintain compatibility we write
17026			// them twice, once with their original default values above, and once as an option
17027			// here. On the read side, old versions will simply ignore the odd-type entries here,
17028			// and new versions map the default values to None and allow the TLV entries here to
17029			// override that.
17030			(1, self.context.minimum_depth, option),
17031			(2, chan_type, option), // We started writing the duplicative copy in channel_parameters
17032									// in 0.0.116, and support skipping writing this as of 0.3.
17033			(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), // Added in 0.0.122
17041			(11, self.context.monitor_pending_finalized_fulfills, required_vec),
17042			(12, monitor_pending_tx_signatures, option), // Added in 0.3
17043			(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), // Added in 0.0.119
17060			(45, holder_commitment_point_next, required),
17061			(47, holder_commitment_point_pending_next, option),
17062			(49, self.context.local_initiated_shutdown, option), // Added in 0.0.122
17063			(51, is_manual_broadcast, option), // Added in 0.0.124
17064			(53, funding_tx_broadcast_safe_event_emitted, option), // Added in 0.0.124
17065			(55, removed_htlc_attribution_data, optional_vec), // Added in 0.2
17066			(57, holding_cell_attribution_data, optional_vec), // Added in 0.2
17067			(58, self.context.interactive_tx_signing_session, option), // Added in 0.2
17068			(59, self.funding.minimum_depth_override, option), // Added in 0.2
17069			(60, self.context.historical_scids, optional_vec), // Added in 0.2
17070			(61, fulfill_attribution_data, optional_vec), // Added in 0.2
17071			(63, holder_commitment_point_current, option), // Added in 0.2
17072			(64, pending_splice, option), // Added in 0.2
17073			// 65 was previously used for quiescent_action
17074			(67, pending_outbound_held_htlc_flags, optional_vec), // Added in 0.2
17075			(69, holding_cell_held_htlc_flags, optional_vec), // Added in 0.2
17076			(70, has_0reserve, option), // Added in 0.3 to prevent downgrades
17077			(71, holder_commitment_point_previous_revoked, option), // Added in 0.3
17078			(73, holder_commitment_point_last_revoked, option), // Added in 0.3
17079			(75, inbound_committed_update_adds, optional_vec),
17080			(77, holding_cell_accountable_flags, optional_vec), // Added in 0.3
17081			(79, pending_outbound_accountable, optional_vec), // Added in 0.3
17082		});
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		// `user_id` used to be a single u64 value. In order to remain backwards compatible with
17101		// versions prior to 0.0.113, the u128 is serialized as two separate u64 values. We read
17102		// the low bytes now and the high bytes later.
17103		let user_id_low: u64 = Readable::read(reader)?;
17104
17105		let mut config = LegacyChannelConfig::default();
17106		{
17107			// Read the 8 bytes of backwards-compatibility ChannelConfig data.
17108			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		// Read the old serialization for shutdown_pubkey, preferring the TLV field later if set.
17119		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							// Initialize this variant with a dummy preimage, the actual preimage will be filled in further down
17209							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							// Initialize this variant with a dummy preimage, the actual preimage will be filled in further down
17221							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							// Initialize this variant with a dummy preimage, the actual preimage will be filled in further down
17233							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		// Versions prior to 0.0.100 expected to read the fields of `last_sent_closing_fee` here,
17326		// however we are supposed to restart shutdown fee negotiation on reconnect (and wipe
17327		// `last_send_closing_fee` in `remove_uncommitted_htlcs_and_mark_paused`) so we should never
17328		// consider the stale state on reload.
17329		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			// Read the 8 bytes of backwards-compatibility counterparty_selected_channel_reserve_satoshis data.
17349			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			// Read the 4 bytes of backwards-compatibility minimum_depth data.
17358			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		// Starting in 0.2, all the elements in this vector will be `Some`, but they are still
17410		// serialized as options to maintain backwards compatibility
17411		let mut preimages: Vec<Option<PaymentPreimage>> = Vec::new();
17412		let mut fulfill_attribution_data: Option<Vec<Option<AttributionData>>> = None;
17413
17414		// If we read an old Channel, for simplicity we just treat it as "we never sent an
17415		// AnnouncementSignatures" which implies we'll re-send it on reconnect, but that's fine.
17416		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), // Added in 0.0.122
17482			(11, monitor_pending_finalized_fulfills, optional_vec),
17483			(12, monitor_pending_tx_signatures, option), // Added in 0.3
17484			(13, channel_creation_height, required),
17485			(15, preimages, required_vec), // The preimages transitioned from optional to required in 0.2
17486			(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), // Added in 0.0.119
17501			(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), // Added in 0.2
17507			(57, holding_cell_attribution_data, optional_vec), // Added in 0.2
17508			(58, interactive_tx_signing_session, option), // Added in 0.2
17509			(59, minimum_depth_override, option), // Added in 0.2
17510			(60, historical_scids, optional_vec), // Added in 0.2
17511			(61, fulfill_attribution_data, optional_vec), // Added in 0.2
17512			(63, holder_commitment_point_current_opt, option), // Added in 0.2
17513			(64, pending_splice, option), // Added in 0.2
17514			// 65 quiescent_action: Added in 0.2; removed in 0.3
17515			(67, pending_outbound_held_htlc_flags_opt, optional_vec), // Added in 0.2
17516			(69, holding_cell_held_htlc_flags_opt, optional_vec), // Added in 0.2
17517			(70, _has_0reserve, option), // Added in 0.3 to prevent downgrades
17518			(71, holder_commitment_point_previous_revoked_opt, option), // Added in 0.3
17519			(73, holder_commitment_point_last_revoked_opt, option), // Added in 0.3
17520			(75, inbound_committed_update_adds_opt, optional_vec),
17521			(77, holding_cell_accountable, optional_vec), // Added in 0.3
17522			(79, pending_outbound_accountable, optional_vec), // Added in 0.3
17523		});
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					// This variant was initialized like this further above
17540					debug_assert_eq!(preimage, &PaymentPreimage([0u8; 32]));
17541					// Flatten and unwrap the preimage; they are always set starting in 0.2.
17542					*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		// We expect all preimages to be consumed above
17553		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			// If the channel was written by a new version and negotiated with features we don't
17569			// understand yet, refuse to read it.
17570			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		// `user_id` used to be a single u64 value. In order to remain backwards
17577		// compatible with versions prior to 0.0.113, the u128 is serialized as two
17578		// separate u64 values.
17579		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			// We expect all skimmed fees to be consumed above
17589			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			// We expect all skimmed fees to be consumed above
17601			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			// We expect all blinding points to be consumed above
17611			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			// We expect all blinding points to be consumed above
17623			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			// We expect all held HTLC flags to be consumed above
17633			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			// We expect all held HTLC flags to be consumed above
17645			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			// We expect all accountable HTLC signals to be consumed above
17669			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			// We expect all accountable HTLC signals to be consumed above
17679			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		// If we're restoring this channel for the first time after an upgrade, then we require that the
17756		// signer be available so that we can immediately populate the next commitment point. Channel
17757		// restoration will fail if this is not possible.
17758		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					// If the current point is not available then splicing can't be initiated
17764					// until the next point is advanced and becomes the current point.
17765					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				// Note that we don't care about serializing handshake limits as we only ever serialize
17876				// channel data after the handshake has completed.
17877				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				// Later in the ChannelManager deserialization phase we scan for channels and assign scid aliases if its missing
17964				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
18003/// Returns the time expressed in hold time units (1 unit = 100 ms) that has elapsed between send_timestamp and now. If
18004/// any of the arguments are `None`, returns `None`.
18005pub(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	// Checks only fulfillments credit the peer for adds and fee increases before our acknowledgment.
18069	// Rejects overspending and completes the commitment exchange for the accepted updates.
18070	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			// A failure returns the payment to us, so it cannot fund either peer update.
18146			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		// Stage the peer's next update directly so claim_funds batches it with the fulfillment.
18164		// The update is affordable only after accounting for the fulfillment's credit.
18165		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	// Check that, during channel creation, we use the same feerate in the open channel message
18428	// as we do in the Channel object creation itself.
18429	#[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		// Now change the fee so we can check that the fee in the open_channel message is the
18446		// same as the old fee.
18447		*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		// Test that when calculating the local and remote commitment transaction fees, the correct
18456		// dust limits are used.
18457		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		// Go through the flow of opening a channel between two nodes, making sure
18467		// they have different dust limits.
18468
18469		// Create Node A's channel pointing to Node B's pubkey
18470		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		// Create Node B's channel by receiving Node A's open_channel message
18476		// Make sure A's dust limit is as we expect.
18477		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		// Node B --> Node A: accept channel, explicitly setting B's dust limit.
18482		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		// Node A --> Node B: funding created
18488		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		// Node B --> Node A: funding signed
18497		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		// Put some inbound and outbound HTLCs in A's channel.
18501		let htlc_amount_msat = 11_092_000; // put an amount below A's effective dust limit but above B's.
18502		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, // put an amount below A's dust amount but above B's.
18513			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		// Make sure when Node A calculates their local commitment transaction, none of the HTLCs pass
18531		// the dust limit check.
18532		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		// Finally, make sure that when Node A calculates the remote's commitment transaction fees, all
18538		// of the HTLCs are seen to be above the dust limit.
18539		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		// Make sure that when `get_next_local/remote_commitment_stats`
18550		// calculate the real dust limits for HTLCs (i.e. the dust limit given by the counterparty
18551		// *plus* the fees paid for the HTLC) they don't swap `HTLC_SUCCESS_TX_WEIGHT` for
18552		// `HTLC_TIMEOUT_TX_WEIGHT`, and vice versa.
18553		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		// If HTLC_SUCCESS_TX_WEIGHT and HTLC_TIMEOUT_TX_WEIGHT were swapped: then this HTLC would be
18574		// counted as dust when it shouldn't be.
18575		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		// If swapped: this HTLC would be counted as non-dust when it shouldn't be.
18581		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		// If swapped: this HTLC would be counted as non-dust when it shouldn't be.
18589		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		// If swapped: this HTLC would be counted as dust when it shouldn't be.
18595		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		// Go through the flow of opening a channel between two nodes.
18615
18616		// Create Node A's channel pointing to Node B's pubkey
18617		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		// Create Node B's channel by receiving Node A's open_channel message
18622		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		// Node B --> Node A: accept channel
18627		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		// Node A --> Node B: funding created
18631		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		// Node B --> Node A: funding signed
18640		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		// Now disconnect the two nodes and check that the commitment point in
18644		// Node B's channel_reestablish message is sane.
18645		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); // now called next_commitment_number
18648		assert_eq!(msg.next_remote_commitment_number, 0); // now called next_revocation_number
18649		assert_eq!(msg.your_last_per_commitment_secret, [0; 32]);
18650
18651		// Check that the commitment point in Node A's channel_reestablish message
18652		// is sane.
18653		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); // now called next_commitment_number
18656		assert_eq!(msg.next_remote_commitment_number, 0); // now called next_revocation_number
18657		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		// Test that `OutboundV1Channel::new` creates a channel with the correct value for
18724		// `holder_max_htlc_value_in_flight_msat`, when configured with a valid percentage value,
18725		// which is set to the lower bound + 1 (2%) of the `channel_value`.
18726		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		// Test with the upper bound - 1 of valid values (99%).
18731		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		// Test that `InboundV1Channel::new` creates a channel with the correct value for
18738		// `holder_max_htlc_value_in_flight_msat`, when configured with a valid percentage value,
18739		// which is set to the lower bound - 1 (2%) of the `channel_value`.
18740		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		// Test with the upper bound - 1 of valid values (99%).
18745		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		// Test that `OutboundV1Channel::new` uses the lower bound of the configurable percentage values (1%)
18750		// if `(un)announced_channel_max_inbound_htlc_value_in_flight_percentage` is set to a value less than 1.
18751		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		// Test that `OutboundV1Channel::new` uses the upper bound of the configurable percentage values
18756		// (100%) if `(un)announced_channel_max_inbound_htlc_value_in_flight_percentage` is set to a larger value
18757		// than 100.
18758		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		// Test that `InboundV1Channel::new` uses the lower bound of the configurable percentage values (1%)
18763		// if `(un)announced_channel_max_inbound_htlc_value_in_flight_percentage` is set to a value less than 1.
18764		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		// Test that `InboundV1Channel::new` uses the upper bound of the configurable percentage values
18769		// (100%) if `(un)announced_channel_max_inbound_htlc_value_in_flight_percentage` is set to a larger value
18770		// than 100.
18771		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 that `OutboundV1Channel::new` and `InboundV1Channel::new` create a channel with the correct
18781		// channel reserves, when `their_channel_reserve_proportional_millionths` is configured.
18782		test_self_and_counterparty_channel_reserve(10_000_000, 0.02, 0.02);
18783
18784		// Test with valid but unreasonably high channel reserves
18785		// Requesting and accepting parties have requested for 49%-49% and 60%-30% channel reserve
18786		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 with calculated channel reserve less than lower bound
18790		// i.e `MIN_THEIR_CHAN_RESERVE_SATOSHIS`
18791		test_self_and_counterparty_channel_reserve(100_000, 0.00002, 0.30);
18792
18793		// Test with invalid channel reserves since sum of both is greater than or equal
18794		// to channel value
18795		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		// Make sure we correctly handle reserves greater than the channel value
18799		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			// Channel Negotiations failed
18848			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		// Create Node A's channel pointing to Node B's pubkey
18867		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		// Create Node B's channel by receiving Node A's open_channel message
18872		// Make sure A's dust limit is as we expect.
18873		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		// Node B --> Node A: accept channel, explicitly setting B's dust limit.
18878		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		// Node A --> Node B: funding created
18884		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		// Node B --> Node A: funding signed
18893		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		// Make sure that receiving a channel update will update the Channel as expected.
18897		let update = ChannelUpdate {
18898			contents: UnsignedChannelUpdate {
18899				chain_hash,
18900				short_channel_id: 0,
18901				timestamp: 0,
18902				message_flags: 1, // Only must_be_one
18903				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		// The counterparty can send an update with a higher minimum HTLC, but that shouldn't
18916		// change our official htlc_minimum_msat.
18917		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		// Ensure that channel blinding points, skimmed fees, and malformed HTLCs are (de)serialized
18933		// properly.
18934		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		// Encode and decode the channel and ensure that the HTLCs within are the same.
19133		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(); // Don't warn about excess mut for no-HTLC calls
19163				let mut counterparty_htlc_sigs = Vec::new();
19164				counterparty_htlc_sigs.clear(); // Don't warn about excess mut for no-HTLC calls
19165				$({
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				// ((htlc, counterparty_sig), (index, holder_sig))
19187				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					// Only HTLC success transactions for received htlcs should have a preimage supplied.
19211					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		// Test vectors from BOLT 3 Appendices C and F (anchors):
19271		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			// These aren't set in the test vectors:
19284			[
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(); // Nothing uses their network key in this test
19321		chan.context.holder_dust_limit_satoshis = 546;
19322		chan.funding.counterparty_selected_channel_reserve_satoshis = Some(0); // Filled in in accept_channel
19323
19324		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		// We can't just use build_holder_transaction_keys here as the per_commitment_secret is not
19373		// derived from a commitment_seed, so instead we copy it here and call
19374		// build_commitment_transaction.
19375		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		// anchors: simple commitment tx with no HTLCs and single anchor
19398		test_commitment_with_anchors!("30440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a8658",
19399						 "3044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778",
19400						 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b80024a010000000000002200202b1b5854183c12d3316565972c4668929d314d81c5dcdbb21cb45fe8a9a8114f10529800000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e0400473044022007cf6b405e9c9b4f527b0ecad9d8bb661fabb8b12abf7d1c0b3ad1855db3ed490220616d5c1eeadccc63bd775a131149455d62d95a42c2a1b01cc7821fc42dce7778014730440220655bf909fb6fa81d086f1336ac72c97906dce29d1b166e305c99152d810e26e1022051f577faa46412c46707aaac46b65d50053550a66334e00a44af2706f27a865801475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19401
19402		// simple commitment tx with no HTLCs
19403		chan.funding.value_to_self_msat = 7000000000;
19404
19405		test_commitment!("3045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b0",
19406						 "30440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae055647142",
19407						 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8002c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e48454a56a00000000002200204adb4e2f00643db396dd120d4e7dc17625f5f2c11a40d857accc862d6b7dd80e04004730440220616210b2cc4d3afb601013c373bbd8aac54febd9f15400379a8cb65ce7deca60022034236c010991beb7ff770510561ae8dc885b8d38d1947248c38f2ae05564714201483045022100c3127b33dcc741dd6b05b1e63cbd1a9a7d816f37af9b6756fa2376b056f032370220408b96279808fe57eb7e463710804cdf4f108388bc5cf722d8c848d2c7f9f3b001475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19408
19409		// anchors: simple commitment tx with no HTLCs
19410		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		// commitment tx with all five HTLCs untrimmed (minimum feerate)
19477		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19478		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		// commitment tx with seven outputs untrimmed (maximum feerate)
19511		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19512		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		// commitment tx with six outputs untrimmed (minimum feerate)
19545		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19546		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		// anchors: commitment tx with six outputs untrimmed (minimum dust limit)
19574		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19575		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		// commitment tx with six outputs untrimmed (maximum feerate)
19604		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19605		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		// commitment tx with five outputs untrimmed (minimum feerate)
19634		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19635		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		// commitment tx with five outputs untrimmed (maximum feerate)
19658		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19659		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		// commitment tx with four outputs untrimmed (minimum feerate)
19682		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19683		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		// anchors: commitment tx with four outputs untrimmed (minimum dust limit)
19701		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19702		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		// commitment tx with four outputs untrimmed (maximum feerate)
19724		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19725		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		// commitment tx with three outputs untrimmed (minimum feerate)
19746		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19747		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		// anchors: commitment tx with three outputs untrimmed (minimum dust limit)
19760		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19761		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		// commitment tx with three outputs untrimmed (maximum feerate)
19777		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19778		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		// commitment tx with two outputs untrimmed (minimum feerate)
19794		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19795		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		// anchors: commitment tx with two outputs untrimmed (minimum dust limit)
19803		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19804		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		// commitment tx with two outputs untrimmed (maximum feerate)
19814		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19815		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		// commitment tx with one output untrimmed (minimum feerate)
19825		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19826		chan.context.feerate_per_kw = 9651181;
19827
19828		test_commitment!("304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a2",
19829		                 "304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a379",
19830		                 "02000000000101bef67e4e2fb9ddeeb3461973cd4c62abb35050b1add772995b820b584a488489000000000038b02b8001c0c62d0000000000160014cc1b07838e387deacd0e5232e1e8b49f4c29e484040047304402207e8d51e0c570a5868a78414f4e0cbfaed1106b171b9581542c30718ee4eb95ba02203af84194c97adf98898c9afe2f2ed4a7f8dba05a2dfab28ac9d9c604aa49a3790147304402202ade0142008309eb376736575ad58d03e5b115499709c6db0b46e36ff394b492022037b63d78d66404d6504d4c4ac13be346f3d1802928a6d3ad95a6a944227161a201475221023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb21030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c152ae3e195220", {});
19831
19832		// anchors: commitment tx with one output untrimmed (minimum dust limit)
19833		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19834		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		// commitment tx with fee greater than funder amount
19844		chan.funding.value_to_self_msat = 6993000000; // 7000000000 - 7000000
19845		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		// commitment tx with 3 htlc outputs, 2 offered having the same amount and preimage
19854		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	// Test vectors from bolt03/zero_fee_commitments.json
19936	#[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); // Fee doesn't matter
19962		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		// Not set in test vectors, not required because we're signing Alice's commitment.
19974		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			// Not provided in test vectors.
19986			[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			// Not provided in test vectors.
20013			[0xff; 32],
20014			[0; 32],
20015			[0; 32],
20016		);
20017
20018		// Test vectors only provide revocation_basepoint for bob, override it here.
20019		let mut bob_pubkeys = bob_signer.pubkeys(&secp_ctx);
20020		bob_pubkeys.revocation_basepoint = RevocationBasepoint(pubkey_from_hex(
20021			"026788d019ed90149cbc9aa5ff26dd7f1a6d3cd1bee8bf36cf7d8310fbd3606b14",
20022		));
20023
20024		// Node id for alice and bob doesn't matter to our test vectors.
20025		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		// Must override alice's keys because we use a fixed revocation_basepoint.
20054		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		// Commitment transaction without HTLCs, both outputs untrimmed
20076		chan.funding.value_to_self_msat = 8000000000;
20077		test_commitment_with_zero_fee!(
20078			"3045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e",
20079			"304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb82162",
20080			"03000000000101ae1e3c841378cf9e4c383bfdd033d4b3c6945e0587ff16635a00b347eea2704b0100000000340fef800300000000000000000451024e7380841e0000000000160014f2123f1a4b67887f2e5f02eda73e6327010152ea00127a0000000000220020f2d298ffcfd6d899a3abada37bfc6f42ce0b7b66f3e39e903e8419ac97dca75a0400483045022100a05afcdfaf045a0a7b6adb194dcda430bb8e47db8c6d1536b2a94bd98fed77ed02206d580dcd5cba42aebed39515fbd00fdd90480825ae23cce87eef1f1711e2125e0148304502210094afa18972599f7a78b06467bd11d742875baf74aa9e516a775720564671fd8e02206b9ed5f48fb92a1c19543d67f29ee3bd43afee1ec1af6f7f9b4e3371beb8216201475221027eb9596a68740445fb151ff37d5422e7f65f2c497c90fda63e738eb606c15bd62103bbc16dc8851bece603322f06b3c8da329401b7be7e9fdd3f3090ad19aed0807052aec50fbb20", {});
20081
20082		// Commitment transaction without HTLCs, one output trimmed below maximum anchor amount
20083		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		// Commitment transaction without HTLCs, one output trimmed above maximum anchor amount
20091		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		// Commitment transaction with all HTLCs above dust limit
20099		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		// Commitment transaction with all HTLCs above dust limit and millisatoshi truncation
20170		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		// Commitment transaction with dust HTLCs below maximum anchor amount
20226		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		// Commitment transaction with similar dust HTLCs below maximum anchor amount
20307		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		// Commitment transaction with millisatoshi dust HTLCs adding to less than 1 satoshi"
20349		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		// Commitment transaction with millisatoshi dust HTLCs adding to 1 satoshi"
20387		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		// Commitment transaction with millisatoshi dust HTLCs adding to more than 1 satoshi"
20425		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		// Commitment transaction with dust HTLCs above maximum anchor amount
20463		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		// Test vectors from BOLT 3 Appendix D:
20540
20541		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		// Test vectors from BOLT 3 Appendix E:
20565		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		// Set trust_own_funding_0conf while ensuring we don't send channel_ready for a
20601		// channel in a batch before all channels are ready.
20602		config.channel_handshake_limits.trust_own_funding_0conf = true;
20603
20604		// Create a channel from node a to node b that will be part of batch funding.
20605		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			// Allow node b to send a 0conf channel_ready.
20638			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		// Fund the channel with a batch funding transaction.
20649		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		// Receive funding_signed, but the channel will be configured to hold sending channel_ready and
20682		// broadcasting the funding transaction until the batch is ready.
20683		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		// Our channel_ready shouldn't be sent yet, even with trust_own_funding_0conf set,
20696		// as the funding transaction depends on all channels in the batch becoming ready.
20697		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		// It is possible to receive a 0conf channel_ready from the remote node.
20702		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		// Clear the ChannelState::WaitingForBatch only when called by ChannelManager.
20716		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}