]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/channelmanager.rs
Adapt intro node process_pending_htlcs test for non-intro nodes
[rust-lightning] / lightning / src / ln / channelmanager.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
10 //! The top-level channel management and payment tracking stuff lives here.
11 //!
12 //! The [`ChannelManager`] is the main chunk of logic implementing the lightning protocol and is
13 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
14 //! upon reconnect to the relevant peer(s).
15 //!
16 //! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing
17 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
18 //! imply it needs to fail HTLCs/payments/channels it manages).
19
20 use bitcoin::blockdata::block::Header;
21 use bitcoin::blockdata::transaction::Transaction;
22 use bitcoin::blockdata::constants::ChainHash;
23 use bitcoin::key::constants::SECRET_KEY_SIZE;
24 use bitcoin::network::constants::Network;
25
26 use bitcoin::hashes::Hash;
27 use bitcoin::hashes::sha256::Hash as Sha256;
28 use bitcoin::hash_types::{BlockHash, Txid};
29
30 use bitcoin::secp256k1::{SecretKey,PublicKey};
31 use bitcoin::secp256k1::Secp256k1;
32 use bitcoin::{secp256k1, Sequence};
33
34 use crate::blinded_path::BlindedPath;
35 use crate::blinded_path::payment::{PaymentConstraints, ReceiveTlvs};
36 use crate::chain;
37 use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
38 use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
39 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, WithChannelMonitor, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
40 use crate::chain::transaction::{OutPoint, TransactionData};
41 use crate::events;
42 use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
43 // Since this struct is returned in `list_channels` methods, expose it here in case users want to
44 // construct one themselves.
45 use crate::ln::{inbound_payment, ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
46 use crate::ln::channel::{self, Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext};
47 pub use crate::ln::channel::{InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails};
48 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
49 #[cfg(any(feature = "_test_utils", test))]
50 use crate::ln::features::Bolt11InvoiceFeatures;
51 use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
52 use crate::ln::onion_payment::{check_incoming_htlc_cltv, create_recv_pending_htlc_info, create_fwd_pending_htlc_info, decode_incoming_update_add_htlc_onion, InboundHTLCErr, NextPacketDetails};
53 use crate::ln::msgs;
54 use crate::ln::onion_utils;
55 use crate::ln::onion_utils::{HTLCFailReason, INVALID_ONION_BLINDING};
56 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
57 #[cfg(test)]
58 use crate::ln::outbound_payment;
59 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs, StaleExpiration};
60 use crate::ln::wire::Encode;
61 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder};
62 use crate::offers::invoice_error::InvoiceError;
63 use crate::offers::merkle::SignError;
64 use crate::offers::offer::{DerivedMetadata, Offer, OfferBuilder};
65 use crate::offers::parse::Bolt12SemanticError;
66 use crate::offers::refund::{Refund, RefundBuilder};
67 use crate::onion_message::messenger::{Destination, MessageRouter, PendingOnionMessage, new_pending_onion_message};
68 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
69 use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
70 use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
71 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
72 use crate::util::wakers::{Future, Notifier};
73 use crate::util::scid_utils::fake_scid;
74 use crate::util::string::UntrustedString;
75 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
76 use crate::util::logger::{Level, Logger, WithContext};
77 use crate::util::errors::APIError;
78 #[cfg(not(c_bindings))]
79 use {
80         crate::routing::router::DefaultRouter,
81         crate::routing::gossip::NetworkGraph,
82         crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters},
83         crate::sign::KeysManager,
84 };
85
86 use alloc::collections::{btree_map, BTreeMap};
87
88 use crate::io;
89 use crate::prelude::*;
90 use core::{cmp, mem};
91 use core::cell::RefCell;
92 use crate::io::Read;
93 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
94 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
95 use core::time::Duration;
96 use core::ops::Deref;
97
98 // Re-export this for use in the public API.
99 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
100 use crate::ln::script::ShutdownScript;
101
102 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
103 //
104 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
105 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
106 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
107 //
108 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
109 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
110 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
111 // before we forward it.
112 //
113 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
114 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
115 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
116 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
117 // our payment, which we can use to decode errors or inform the user that the payment was sent.
118
119 /// Information about where a received HTLC('s onion) has indicated the HTLC should go.
120 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
121 #[cfg_attr(test, derive(Debug, PartialEq))]
122 pub enum PendingHTLCRouting {
123         /// An HTLC which should be forwarded on to another node.
124         Forward {
125                 /// The onion which should be included in the forwarded HTLC, telling the next hop what to
126                 /// do with the HTLC.
127                 onion_packet: msgs::OnionPacket,
128                 /// The short channel ID of the channel which we were instructed to forward this HTLC to.
129                 ///
130                 /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning
131                 /// to the receiving node, such as one returned from
132                 /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`].
133                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
134                 /// Set if this HTLC is being forwarded within a blinded path.
135                 blinded: Option<BlindedForward>,
136         },
137         /// The onion indicates that this is a payment for an invoice (supposedly) generated by us.
138         ///
139         /// Note that at this point, we have not checked that the invoice being paid was actually
140         /// generated by us, but rather it's claiming to pay an invoice of ours.
141         Receive {
142                 /// Information about the amount the sender intended to pay and (potential) proof that this
143                 /// is a payment for an invoice we generated. This proof of payment is is also used for
144                 /// linking MPP parts of a larger payment.
145                 payment_data: msgs::FinalOnionHopData,
146                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
147                 ///
148                 /// For HTLCs received by LDK, this will ultimately be exposed in
149                 /// [`Event::PaymentClaimable::onion_fields`] as
150                 /// [`RecipientOnionFields::payment_metadata`].
151                 payment_metadata: Option<Vec<u8>>,
152                 /// CLTV expiry of the received HTLC.
153                 ///
154                 /// Used to track when we should expire pending HTLCs that go unclaimed.
155                 incoming_cltv_expiry: u32,
156                 /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will
157                 /// provide the onion shared secret used to decrypt the next level of forwarding
158                 /// instructions.
159                 phantom_shared_secret: Option<[u8; 32]>,
160                 /// Custom TLVs which were set by the sender.
161                 ///
162                 /// For HTLCs received by LDK, this will ultimately be exposed in
163                 /// [`Event::PaymentClaimable::onion_fields`] as
164                 /// [`RecipientOnionFields::custom_tlvs`].
165                 custom_tlvs: Vec<(u64, Vec<u8>)>,
166                 /// Set if this HTLC is the final hop in a multi-hop blinded path.
167                 requires_blinded_error: bool,
168         },
169         /// The onion indicates that this is for payment to us but which contains the preimage for
170         /// claiming included, and is unrelated to any invoice we'd previously generated (aka a
171         /// "keysend" or "spontaneous" payment).
172         ReceiveKeysend {
173                 /// Information about the amount the sender intended to pay and possibly a token to
174                 /// associate MPP parts of a larger payment.
175                 ///
176                 /// This will only be filled in if receiving MPP keysend payments is enabled, and it being
177                 /// present will cause deserialization to fail on versions of LDK prior to 0.0.116.
178                 payment_data: Option<msgs::FinalOnionHopData>,
179                 /// Preimage for this onion payment. This preimage is provided by the sender and will be
180                 /// used to settle the spontaneous payment.
181                 payment_preimage: PaymentPreimage,
182                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
183                 ///
184                 /// For HTLCs received by LDK, this will ultimately bubble back up as
185                 /// [`RecipientOnionFields::payment_metadata`].
186                 payment_metadata: Option<Vec<u8>>,
187                 /// CLTV expiry of the received HTLC.
188                 ///
189                 /// Used to track when we should expire pending HTLCs that go unclaimed.
190                 incoming_cltv_expiry: u32,
191                 /// Custom TLVs which were set by the sender.
192                 ///
193                 /// For HTLCs received by LDK, these will ultimately bubble back up as
194                 /// [`RecipientOnionFields::custom_tlvs`].
195                 custom_tlvs: Vec<(u64, Vec<u8>)>,
196         },
197 }
198
199 /// Information used to forward or fail this HTLC that is being forwarded within a blinded path.
200 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
201 pub struct BlindedForward {
202         /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
203         /// onion payload if we're the introduction node. Useful for calculating the next hop's
204         /// [`msgs::UpdateAddHTLC::blinding_point`].
205         pub inbound_blinding_point: PublicKey,
206         /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
207         /// the introduction node.
208         pub failure: BlindedFailure,
209 }
210
211 impl PendingHTLCRouting {
212         // Used to override the onion failure code and data if the HTLC is blinded.
213         fn blinded_failure(&self) -> Option<BlindedFailure> {
214                 match self {
215                         Self::Forward { blinded: Some(BlindedForward { failure, .. }), .. } => Some(*failure),
216                         Self::Receive { requires_blinded_error: true, .. } => Some(BlindedFailure::FromBlindedNode),
217                         _ => None,
218                 }
219         }
220 }
221
222 /// Information about an incoming HTLC, including the [`PendingHTLCRouting`] describing where it
223 /// should go next.
224 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
225 #[cfg_attr(test, derive(Debug, PartialEq))]
226 pub struct PendingHTLCInfo {
227         /// Further routing details based on whether the HTLC is being forwarded or received.
228         pub routing: PendingHTLCRouting,
229         /// The onion shared secret we build with the sender used to decrypt the onion.
230         ///
231         /// This is later used to encrypt failure packets in the event that the HTLC is failed.
232         pub incoming_shared_secret: [u8; 32],
233         /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
234         pub payment_hash: PaymentHash,
235         /// Amount received in the incoming HTLC.
236         ///
237         /// This field was added in LDK 0.0.113 and will be `None` for objects written by prior
238         /// versions.
239         pub incoming_amt_msat: Option<u64>,
240         /// The amount the sender indicated should be forwarded on to the next hop or amount the sender
241         /// intended for us to receive for received payments.
242         ///
243         /// If the received amount is less than this for received payments, an intermediary hop has
244         /// attempted to steal some of our funds and we should fail the HTLC (the sender should retry
245         /// it along another path).
246         ///
247         /// Because nodes can take less than their required fees, and because senders may wish to
248         /// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for
249         /// received payments. In such cases, recipients must handle this HTLC as if it had received
250         /// [`Self::outgoing_amt_msat`].
251         pub outgoing_amt_msat: u64,
252         /// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated
253         /// should have been set on the received HTLC for received payments).
254         pub outgoing_cltv_value: u32,
255         /// The fee taken for this HTLC in addition to the standard protocol HTLC fees.
256         ///
257         /// If this is a payment for forwarding, this is the fee we are taking before forwarding the
258         /// HTLC.
259         ///
260         /// If this is a received payment, this is the fee that our counterparty took.
261         ///
262         /// This is used to allow LSPs to take fees as a part of payments, without the sender having to
263         /// shoulder them.
264         pub skimmed_fee_msat: Option<u64>,
265 }
266
267 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
268 pub(super) enum HTLCFailureMsg {
269         Relay(msgs::UpdateFailHTLC),
270         Malformed(msgs::UpdateFailMalformedHTLC),
271 }
272
273 /// Stores whether we can't forward an HTLC or relevant forwarding info
274 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
275 pub(super) enum PendingHTLCStatus {
276         Forward(PendingHTLCInfo),
277         Fail(HTLCFailureMsg),
278 }
279
280 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
281 pub(super) struct PendingAddHTLCInfo {
282         pub(super) forward_info: PendingHTLCInfo,
283
284         // These fields are produced in `forward_htlcs()` and consumed in
285         // `process_pending_htlc_forwards()` for constructing the
286         // `HTLCSource::PreviousHopData` for failed and forwarded
287         // HTLCs.
288         //
289         // Note that this may be an outbound SCID alias for the associated channel.
290         prev_short_channel_id: u64,
291         prev_htlc_id: u64,
292         prev_channel_id: ChannelId,
293         prev_funding_outpoint: OutPoint,
294         prev_user_channel_id: u128,
295 }
296
297 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
298 pub(super) enum HTLCForwardInfo {
299         AddHTLC(PendingAddHTLCInfo),
300         FailHTLC {
301                 htlc_id: u64,
302                 err_packet: msgs::OnionErrorPacket,
303         },
304         FailMalformedHTLC {
305                 htlc_id: u64,
306                 failure_code: u16,
307                 sha256_of_onion: [u8; 32],
308         },
309 }
310
311 /// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node,
312 /// which determines the failure message that should be used.
313 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
314 pub enum BlindedFailure {
315         /// This HTLC is being failed backwards by the introduction node, and thus should be failed with
316         /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`.
317         FromIntroductionNode,
318         /// This HTLC is being failed backwards by a blinded node within the path, and thus should be
319         /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`.
320         FromBlindedNode,
321 }
322
323 /// Tracks the inbound corresponding to an outbound HTLC
324 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
325 pub(crate) struct HTLCPreviousHopData {
326         // Note that this may be an outbound SCID alias for the associated channel.
327         short_channel_id: u64,
328         user_channel_id: Option<u128>,
329         htlc_id: u64,
330         incoming_packet_shared_secret: [u8; 32],
331         phantom_shared_secret: Option<[u8; 32]>,
332         blinded_failure: Option<BlindedFailure>,
333         channel_id: ChannelId,
334
335         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
336         // channel with a preimage provided by the forward channel.
337         outpoint: OutPoint,
338 }
339
340 enum OnionPayload {
341         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
342         Invoice {
343                 /// This is only here for backwards-compatibility in serialization, in the future it can be
344                 /// removed, breaking clients running 0.0.106 and earlier.
345                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
346         },
347         /// Contains the payer-provided preimage.
348         Spontaneous(PaymentPreimage),
349 }
350
351 /// HTLCs that are to us and can be failed/claimed by the user
352 struct ClaimableHTLC {
353         prev_hop: HTLCPreviousHopData,
354         cltv_expiry: u32,
355         /// The amount (in msats) of this MPP part
356         value: u64,
357         /// The amount (in msats) that the sender intended to be sent in this MPP
358         /// part (used for validating total MPP amount)
359         sender_intended_value: u64,
360         onion_payload: OnionPayload,
361         timer_ticks: u8,
362         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
363         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
364         total_value_received: Option<u64>,
365         /// The sender intended sum total of all MPP parts specified in the onion
366         total_msat: u64,
367         /// The extra fee our counterparty skimmed off the top of this HTLC.
368         counterparty_skimmed_fee_msat: Option<u64>,
369 }
370
371 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
372         fn from(val: &ClaimableHTLC) -> Self {
373                 events::ClaimedHTLC {
374                         channel_id: val.prev_hop.channel_id,
375                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
376                         cltv_expiry: val.cltv_expiry,
377                         value_msat: val.value,
378                         counterparty_skimmed_fee_msat: val.counterparty_skimmed_fee_msat.unwrap_or(0),
379                 }
380         }
381 }
382
383 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
384 /// a payment and ensure idempotency in LDK.
385 ///
386 /// This is not exported to bindings users as we just use [u8; 32] directly
387 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
388 pub struct PaymentId(pub [u8; Self::LENGTH]);
389
390 impl PaymentId {
391         /// Number of bytes in the id.
392         pub const LENGTH: usize = 32;
393 }
394
395 impl Writeable for PaymentId {
396         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
397                 self.0.write(w)
398         }
399 }
400
401 impl Readable for PaymentId {
402         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
403                 let buf: [u8; 32] = Readable::read(r)?;
404                 Ok(PaymentId(buf))
405         }
406 }
407
408 impl core::fmt::Display for PaymentId {
409         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
410                 crate::util::logger::DebugBytes(&self.0).fmt(f)
411         }
412 }
413
414 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
415 ///
416 /// This is not exported to bindings users as we just use [u8; 32] directly
417 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
418 pub struct InterceptId(pub [u8; 32]);
419
420 impl Writeable for InterceptId {
421         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
422                 self.0.write(w)
423         }
424 }
425
426 impl Readable for InterceptId {
427         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
428                 let buf: [u8; 32] = Readable::read(r)?;
429                 Ok(InterceptId(buf))
430         }
431 }
432
433 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
434 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
435 pub(crate) enum SentHTLCId {
436         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
437         OutboundRoute { session_priv: [u8; SECRET_KEY_SIZE] },
438 }
439 impl SentHTLCId {
440         pub(crate) fn from_source(source: &HTLCSource) -> Self {
441                 match source {
442                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
443                                 short_channel_id: hop_data.short_channel_id,
444                                 htlc_id: hop_data.htlc_id,
445                         },
446                         HTLCSource::OutboundRoute { session_priv, .. } =>
447                                 Self::OutboundRoute { session_priv: session_priv.secret_bytes() },
448                 }
449         }
450 }
451 impl_writeable_tlv_based_enum!(SentHTLCId,
452         (0, PreviousHopData) => {
453                 (0, short_channel_id, required),
454                 (2, htlc_id, required),
455         },
456         (2, OutboundRoute) => {
457                 (0, session_priv, required),
458         };
459 );
460
461
462 /// Tracks the inbound corresponding to an outbound HTLC
463 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
464 #[derive(Clone, Debug, PartialEq, Eq)]
465 pub(crate) enum HTLCSource {
466         PreviousHopData(HTLCPreviousHopData),
467         OutboundRoute {
468                 path: Path,
469                 session_priv: SecretKey,
470                 /// Technically we can recalculate this from the route, but we cache it here to avoid
471                 /// doing a double-pass on route when we get a failure back
472                 first_hop_htlc_msat: u64,
473                 payment_id: PaymentId,
474         },
475 }
476 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
477 impl core::hash::Hash for HTLCSource {
478         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
479                 match self {
480                         HTLCSource::PreviousHopData(prev_hop_data) => {
481                                 0u8.hash(hasher);
482                                 prev_hop_data.hash(hasher);
483                         },
484                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
485                                 1u8.hash(hasher);
486                                 path.hash(hasher);
487                                 session_priv[..].hash(hasher);
488                                 payment_id.hash(hasher);
489                                 first_hop_htlc_msat.hash(hasher);
490                         },
491                 }
492         }
493 }
494 impl HTLCSource {
495         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
496         #[cfg(test)]
497         pub fn dummy() -> Self {
498                 HTLCSource::OutboundRoute {
499                         path: Path { hops: Vec::new(), blinded_tail: None },
500                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
501                         first_hop_htlc_msat: 0,
502                         payment_id: PaymentId([2; 32]),
503                 }
504         }
505
506         #[cfg(debug_assertions)]
507         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
508         /// transaction. Useful to ensure different datastructures match up.
509         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
510                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
511                         *first_hop_htlc_msat == htlc.amount_msat
512                 } else {
513                         // There's nothing we can check for forwarded HTLCs
514                         true
515                 }
516         }
517 }
518
519 /// This enum is used to specify which error data to send to peers when failing back an HTLC
520 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
521 ///
522 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
523 #[derive(Clone, Copy)]
524 pub enum FailureCode {
525         /// We had a temporary error processing the payment. Useful if no other error codes fit
526         /// and you want to indicate that the payer may want to retry.
527         TemporaryNodeFailure,
528         /// We have a required feature which was not in this onion. For example, you may require
529         /// some additional metadata that was not provided with this payment.
530         RequiredNodeFeatureMissing,
531         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
532         /// the HTLC is too close to the current block height for safe handling.
533         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
534         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
535         IncorrectOrUnknownPaymentDetails,
536         /// We failed to process the payload after the onion was decrypted. You may wish to
537         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
538         ///
539         /// If available, the tuple data may include the type number and byte offset in the
540         /// decrypted byte stream where the failure occurred.
541         InvalidOnionPayload(Option<(u64, u16)>),
542 }
543
544 impl Into<u16> for FailureCode {
545     fn into(self) -> u16 {
546                 match self {
547                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
548                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
549                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
550                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
551                 }
552         }
553 }
554
555 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
556 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
557 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
558 /// peer_state lock. We then return the set of things that need to be done outside the lock in
559 /// this struct and call handle_error!() on it.
560
561 struct MsgHandleErrInternal {
562         err: msgs::LightningError,
563         closes_channel: bool,
564         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
565 }
566 impl MsgHandleErrInternal {
567         #[inline]
568         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
569                 Self {
570                         err: LightningError {
571                                 err: err.clone(),
572                                 action: msgs::ErrorAction::SendErrorMessage {
573                                         msg: msgs::ErrorMessage {
574                                                 channel_id,
575                                                 data: err
576                                         },
577                                 },
578                         },
579                         closes_channel: false,
580                         shutdown_finish: None,
581                 }
582         }
583         #[inline]
584         fn from_no_close(err: msgs::LightningError) -> Self {
585                 Self { err, closes_channel: false, shutdown_finish: None }
586         }
587         #[inline]
588         fn from_finish_shutdown(err: String, channel_id: ChannelId, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
589                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
590                 let action = if shutdown_res.monitor_update.is_some() {
591                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
592                         // should disconnect our peer such that we force them to broadcast their latest
593                         // commitment upon reconnecting.
594                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
595                 } else {
596                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
597                 };
598                 Self {
599                         err: LightningError { err, action },
600                         closes_channel: true,
601                         shutdown_finish: Some((shutdown_res, channel_update)),
602                 }
603         }
604         #[inline]
605         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
606                 Self {
607                         err: match err {
608                                 ChannelError::Warn(msg) =>  LightningError {
609                                         err: msg.clone(),
610                                         action: msgs::ErrorAction::SendWarningMessage {
611                                                 msg: msgs::WarningMessage {
612                                                         channel_id,
613                                                         data: msg
614                                                 },
615                                                 log_level: Level::Warn,
616                                         },
617                                 },
618                                 ChannelError::Ignore(msg) => LightningError {
619                                         err: msg,
620                                         action: msgs::ErrorAction::IgnoreError,
621                                 },
622                                 ChannelError::Close(msg) => LightningError {
623                                         err: msg.clone(),
624                                         action: msgs::ErrorAction::SendErrorMessage {
625                                                 msg: msgs::ErrorMessage {
626                                                         channel_id,
627                                                         data: msg
628                                                 },
629                                         },
630                                 },
631                         },
632                         closes_channel: false,
633                         shutdown_finish: None,
634                 }
635         }
636
637         fn closes_channel(&self) -> bool {
638                 self.closes_channel
639         }
640 }
641
642 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
643 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
644 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
645 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
646 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
647
648 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
649 /// be sent in the order they appear in the return value, however sometimes the order needs to be
650 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
651 /// they were originally sent). In those cases, this enum is also returned.
652 #[derive(Clone, PartialEq)]
653 pub(super) enum RAACommitmentOrder {
654         /// Send the CommitmentUpdate messages first
655         CommitmentFirst,
656         /// Send the RevokeAndACK message first
657         RevokeAndACKFirst,
658 }
659
660 /// Information about a payment which is currently being claimed.
661 struct ClaimingPayment {
662         amount_msat: u64,
663         payment_purpose: events::PaymentPurpose,
664         receiver_node_id: PublicKey,
665         htlcs: Vec<events::ClaimedHTLC>,
666         sender_intended_value: Option<u64>,
667 }
668 impl_writeable_tlv_based!(ClaimingPayment, {
669         (0, amount_msat, required),
670         (2, payment_purpose, required),
671         (4, receiver_node_id, required),
672         (5, htlcs, optional_vec),
673         (7, sender_intended_value, option),
674 });
675
676 struct ClaimablePayment {
677         purpose: events::PaymentPurpose,
678         onion_fields: Option<RecipientOnionFields>,
679         htlcs: Vec<ClaimableHTLC>,
680 }
681
682 /// Information about claimable or being-claimed payments
683 struct ClaimablePayments {
684         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
685         /// failed/claimed by the user.
686         ///
687         /// Note that, no consistency guarantees are made about the channels given here actually
688         /// existing anymore by the time you go to read them!
689         ///
690         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
691         /// we don't get a duplicate payment.
692         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
693
694         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
695         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
696         /// as an [`events::Event::PaymentClaimed`].
697         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
698 }
699
700 /// Events which we process internally but cannot be processed immediately at the generation site
701 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
702 /// running normally, and specifically must be processed before any other non-background
703 /// [`ChannelMonitorUpdate`]s are applied.
704 #[derive(Debug)]
705 enum BackgroundEvent {
706         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
707         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
708         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
709         /// channel has been force-closed we do not need the counterparty node_id.
710         ///
711         /// Note that any such events are lost on shutdown, so in general they must be updates which
712         /// are regenerated on startup.
713         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelId, ChannelMonitorUpdate)),
714         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
715         /// channel to continue normal operation.
716         ///
717         /// In general this should be used rather than
718         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
719         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
720         /// error the other variant is acceptable.
721         ///
722         /// Note that any such events are lost on shutdown, so in general they must be updates which
723         /// are regenerated on startup.
724         MonitorUpdateRegeneratedOnStartup {
725                 counterparty_node_id: PublicKey,
726                 funding_txo: OutPoint,
727                 channel_id: ChannelId,
728                 update: ChannelMonitorUpdate
729         },
730         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
731         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
732         /// on a channel.
733         MonitorUpdatesComplete {
734                 counterparty_node_id: PublicKey,
735                 channel_id: ChannelId,
736         },
737 }
738
739 #[derive(Debug)]
740 pub(crate) enum MonitorUpdateCompletionAction {
741         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
742         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
743         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
744         /// event can be generated.
745         PaymentClaimed { payment_hash: PaymentHash },
746         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
747         /// operation of another channel.
748         ///
749         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
750         /// from completing a monitor update which removes the payment preimage until the inbound edge
751         /// completes a monitor update containing the payment preimage. In that case, after the inbound
752         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
753         /// outbound edge.
754         EmitEventAndFreeOtherChannel {
755                 event: events::Event,
756                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, ChannelId, RAAMonitorUpdateBlockingAction)>,
757         },
758         /// Indicates we should immediately resume the operation of another channel, unless there is
759         /// some other reason why the channel is blocked. In practice this simply means immediately
760         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
761         ///
762         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
763         /// from completing a monitor update which removes the payment preimage until the inbound edge
764         /// completes a monitor update containing the payment preimage. However, we use this variant
765         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
766         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
767         ///
768         /// This variant should thus never be written to disk, as it is processed inline rather than
769         /// stored for later processing.
770         FreeOtherChannelImmediately {
771                 downstream_counterparty_node_id: PublicKey,
772                 downstream_funding_outpoint: OutPoint,
773                 blocking_action: RAAMonitorUpdateBlockingAction,
774                 downstream_channel_id: ChannelId,
775         },
776 }
777
778 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
779         (0, PaymentClaimed) => { (0, payment_hash, required) },
780         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
781         // *immediately*. However, for simplicity we implement read/write here.
782         (1, FreeOtherChannelImmediately) => {
783                 (0, downstream_counterparty_node_id, required),
784                 (2, downstream_funding_outpoint, required),
785                 (4, blocking_action, required),
786                 // Note that by the time we get past the required read above, downstream_funding_outpoint will be
787                 // filled in, so we can safely unwrap it here.
788                 (5, downstream_channel_id, (default_value, ChannelId::v1_from_funding_outpoint(downstream_funding_outpoint.0.unwrap()))),
789         },
790         (2, EmitEventAndFreeOtherChannel) => {
791                 (0, event, upgradable_required),
792                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
793                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
794                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
795                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
796                 // downgrades to prior versions.
797                 (1, downstream_counterparty_and_funding_outpoint, option),
798         },
799 );
800
801 #[derive(Clone, Debug, PartialEq, Eq)]
802 pub(crate) enum EventCompletionAction {
803         ReleaseRAAChannelMonitorUpdate {
804                 counterparty_node_id: PublicKey,
805                 channel_funding_outpoint: OutPoint,
806                 channel_id: ChannelId,
807         },
808 }
809 impl_writeable_tlv_based_enum!(EventCompletionAction,
810         (0, ReleaseRAAChannelMonitorUpdate) => {
811                 (0, channel_funding_outpoint, required),
812                 (2, counterparty_node_id, required),
813                 // Note that by the time we get past the required read above, channel_funding_outpoint will be
814                 // filled in, so we can safely unwrap it here.
815                 (3, channel_id, (default_value, ChannelId::v1_from_funding_outpoint(channel_funding_outpoint.0.unwrap()))),
816         };
817 );
818
819 #[derive(Clone, PartialEq, Eq, Debug)]
820 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
821 /// the blocked action here. See enum variants for more info.
822 pub(crate) enum RAAMonitorUpdateBlockingAction {
823         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
824         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
825         /// durably to disk.
826         ForwardedPaymentInboundClaim {
827                 /// The upstream channel ID (i.e. the inbound edge).
828                 channel_id: ChannelId,
829                 /// The HTLC ID on the inbound edge.
830                 htlc_id: u64,
831         },
832 }
833
834 impl RAAMonitorUpdateBlockingAction {
835         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
836                 Self::ForwardedPaymentInboundClaim {
837                         channel_id: prev_hop.channel_id,
838                         htlc_id: prev_hop.htlc_id,
839                 }
840         }
841 }
842
843 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
844         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
845 ;);
846
847
848 /// State we hold per-peer.
849 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
850         /// `channel_id` -> `ChannelPhase`
851         ///
852         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
853         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
854         /// `temporary_channel_id` -> `InboundChannelRequest`.
855         ///
856         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
857         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
858         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
859         /// the channel is rejected, then the entry is simply removed.
860         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
861         /// The latest `InitFeatures` we heard from the peer.
862         latest_features: InitFeatures,
863         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
864         /// for broadcast messages, where ordering isn't as strict).
865         pub(super) pending_msg_events: Vec<MessageSendEvent>,
866         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
867         /// user but which have not yet completed.
868         ///
869         /// Note that the channel may no longer exist. For example if the channel was closed but we
870         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
871         /// for a missing channel.
872         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
873         /// Map from a specific channel to some action(s) that should be taken when all pending
874         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
875         ///
876         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
877         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
878         /// channels with a peer this will just be one allocation and will amount to a linear list of
879         /// channels to walk, avoiding the whole hashing rigmarole.
880         ///
881         /// Note that the channel may no longer exist. For example, if a channel was closed but we
882         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
883         /// for a missing channel. While a malicious peer could construct a second channel with the
884         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
885         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
886         /// duplicates do not occur, so such channels should fail without a monitor update completing.
887         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
888         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
889         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
890         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
891         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
892         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
893         /// The peer is currently connected (i.e. we've seen a
894         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
895         /// [`ChannelMessageHandler::peer_disconnected`].
896         is_connected: bool,
897 }
898
899 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
900         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
901         /// If true is passed for `require_disconnected`, the function will return false if we haven't
902         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
903         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
904                 if require_disconnected && self.is_connected {
905                         return false
906                 }
907                 !self.channel_by_id.iter().any(|(_, phase)|
908                         match phase {
909                                 ChannelPhase::Funded(_) | ChannelPhase::UnfundedOutboundV1(_) => true,
910                                 ChannelPhase::UnfundedInboundV1(_) => false,
911                                 #[cfg(dual_funding)]
912                                 ChannelPhase::UnfundedOutboundV2(_) => true,
913                                 #[cfg(dual_funding)]
914                                 ChannelPhase::UnfundedInboundV2(_) => false,
915                         }
916                 )
917                         && self.monitor_update_blocked_actions.is_empty()
918                         && self.in_flight_monitor_updates.is_empty()
919         }
920
921         // Returns a count of all channels we have with this peer, including unfunded channels.
922         fn total_channel_count(&self) -> usize {
923                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
924         }
925
926         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
927         fn has_channel(&self, channel_id: &ChannelId) -> bool {
928                 self.channel_by_id.contains_key(channel_id) ||
929                         self.inbound_channel_request_by_id.contains_key(channel_id)
930         }
931 }
932
933 /// A not-yet-accepted inbound (from counterparty) channel. Once
934 /// accepted, the parameters will be used to construct a channel.
935 pub(super) struct InboundChannelRequest {
936         /// The original OpenChannel message.
937         pub open_channel_msg: msgs::OpenChannel,
938         /// The number of ticks remaining before the request expires.
939         pub ticks_remaining: i32,
940 }
941
942 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
943 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
944 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
945
946 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
947 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
948 ///
949 /// For users who don't want to bother doing their own payment preimage storage, we also store that
950 /// here.
951 ///
952 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
953 /// and instead encoding it in the payment secret.
954 struct PendingInboundPayment {
955         /// The payment secret that the sender must use for us to accept this payment
956         payment_secret: PaymentSecret,
957         /// Time at which this HTLC expires - blocks with a header time above this value will result in
958         /// this payment being removed.
959         expiry_time: u64,
960         /// Arbitrary identifier the user specifies (or not)
961         user_payment_id: u64,
962         // Other required attributes of the payment, optionally enforced:
963         payment_preimage: Option<PaymentPreimage>,
964         min_value_msat: Option<u64>,
965 }
966
967 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
968 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
969 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
970 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
971 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
972 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
973 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
974 /// of [`KeysManager`] and [`DefaultRouter`].
975 ///
976 /// This is not exported to bindings users as type aliases aren't supported in most languages.
977 #[cfg(not(c_bindings))]
978 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
979         Arc<M>,
980         Arc<T>,
981         Arc<KeysManager>,
982         Arc<KeysManager>,
983         Arc<KeysManager>,
984         Arc<F>,
985         Arc<DefaultRouter<
986                 Arc<NetworkGraph<Arc<L>>>,
987                 Arc<L>,
988                 Arc<KeysManager>,
989                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
990                 ProbabilisticScoringFeeParameters,
991                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
992         >>,
993         Arc<L>
994 >;
995
996 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
997 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
998 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
999 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
1000 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
1001 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
1002 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
1003 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
1004 /// of [`KeysManager`] and [`DefaultRouter`].
1005 ///
1006 /// This is not exported to bindings users as type aliases aren't supported in most languages.
1007 #[cfg(not(c_bindings))]
1008 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
1009         ChannelManager<
1010                 &'a M,
1011                 &'b T,
1012                 &'c KeysManager,
1013                 &'c KeysManager,
1014                 &'c KeysManager,
1015                 &'d F,
1016                 &'e DefaultRouter<
1017                         &'f NetworkGraph<&'g L>,
1018                         &'g L,
1019                         &'c KeysManager,
1020                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
1021                         ProbabilisticScoringFeeParameters,
1022                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
1023                 >,
1024                 &'g L
1025         >;
1026
1027 /// A trivial trait which describes any [`ChannelManager`].
1028 ///
1029 /// This is not exported to bindings users as general cover traits aren't useful in other
1030 /// languages.
1031 pub trait AChannelManager {
1032         /// A type implementing [`chain::Watch`].
1033         type Watch: chain::Watch<Self::Signer> + ?Sized;
1034         /// A type that may be dereferenced to [`Self::Watch`].
1035         type M: Deref<Target = Self::Watch>;
1036         /// A type implementing [`BroadcasterInterface`].
1037         type Broadcaster: BroadcasterInterface + ?Sized;
1038         /// A type that may be dereferenced to [`Self::Broadcaster`].
1039         type T: Deref<Target = Self::Broadcaster>;
1040         /// A type implementing [`EntropySource`].
1041         type EntropySource: EntropySource + ?Sized;
1042         /// A type that may be dereferenced to [`Self::EntropySource`].
1043         type ES: Deref<Target = Self::EntropySource>;
1044         /// A type implementing [`NodeSigner`].
1045         type NodeSigner: NodeSigner + ?Sized;
1046         /// A type that may be dereferenced to [`Self::NodeSigner`].
1047         type NS: Deref<Target = Self::NodeSigner>;
1048         /// A type implementing [`WriteableEcdsaChannelSigner`].
1049         type Signer: WriteableEcdsaChannelSigner + Sized;
1050         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
1051         type SignerProvider: SignerProvider<EcdsaSigner= Self::Signer> + ?Sized;
1052         /// A type that may be dereferenced to [`Self::SignerProvider`].
1053         type SP: Deref<Target = Self::SignerProvider>;
1054         /// A type implementing [`FeeEstimator`].
1055         type FeeEstimator: FeeEstimator + ?Sized;
1056         /// A type that may be dereferenced to [`Self::FeeEstimator`].
1057         type F: Deref<Target = Self::FeeEstimator>;
1058         /// A type implementing [`Router`].
1059         type Router: Router + ?Sized;
1060         /// A type that may be dereferenced to [`Self::Router`].
1061         type R: Deref<Target = Self::Router>;
1062         /// A type implementing [`Logger`].
1063         type Logger: Logger + ?Sized;
1064         /// A type that may be dereferenced to [`Self::Logger`].
1065         type L: Deref<Target = Self::Logger>;
1066         /// Returns a reference to the actual [`ChannelManager`] object.
1067         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
1068 }
1069
1070 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
1071 for ChannelManager<M, T, ES, NS, SP, F, R, L>
1072 where
1073         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1074         T::Target: BroadcasterInterface,
1075         ES::Target: EntropySource,
1076         NS::Target: NodeSigner,
1077         SP::Target: SignerProvider,
1078         F::Target: FeeEstimator,
1079         R::Target: Router,
1080         L::Target: Logger,
1081 {
1082         type Watch = M::Target;
1083         type M = M;
1084         type Broadcaster = T::Target;
1085         type T = T;
1086         type EntropySource = ES::Target;
1087         type ES = ES;
1088         type NodeSigner = NS::Target;
1089         type NS = NS;
1090         type Signer = <SP::Target as SignerProvider>::EcdsaSigner;
1091         type SignerProvider = SP::Target;
1092         type SP = SP;
1093         type FeeEstimator = F::Target;
1094         type F = F;
1095         type Router = R::Target;
1096         type R = R;
1097         type Logger = L::Target;
1098         type L = L;
1099         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
1100 }
1101
1102 /// Manager which keeps track of a number of channels and sends messages to the appropriate
1103 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
1104 ///
1105 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
1106 /// to individual Channels.
1107 ///
1108 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
1109 /// all peers during write/read (though does not modify this instance, only the instance being
1110 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
1111 /// called [`funding_transaction_generated`] for outbound channels) being closed.
1112 ///
1113 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
1114 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
1115 /// [`ChannelMonitorUpdate`] before returning from
1116 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
1117 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
1118 /// `ChannelManager` operations from occurring during the serialization process). If the
1119 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
1120 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
1121 /// will be lost (modulo on-chain transaction fees).
1122 ///
1123 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
1124 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
1125 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
1126 ///
1127 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1128 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1129 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1130 /// offline for a full minute. In order to track this, you must call
1131 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1132 ///
1133 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1134 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1135 /// not have a channel with being unable to connect to us or open new channels with us if we have
1136 /// many peers with unfunded channels.
1137 ///
1138 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1139 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1140 /// never limited. Please ensure you limit the count of such channels yourself.
1141 ///
1142 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1143 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1144 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1145 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1146 /// you're using lightning-net-tokio.
1147 ///
1148 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1149 /// [`funding_created`]: msgs::FundingCreated
1150 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1151 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1152 /// [`update_channel`]: chain::Watch::update_channel
1153 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1154 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1155 /// [`read`]: ReadableArgs::read
1156 //
1157 // Lock order:
1158 // The tree structure below illustrates the lock order requirements for the different locks of the
1159 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1160 // and should then be taken in the order of the lowest to the highest level in the tree.
1161 // Note that locks on different branches shall not be taken at the same time, as doing so will
1162 // create a new lock order for those specific locks in the order they were taken.
1163 //
1164 // Lock order tree:
1165 //
1166 // `pending_offers_messages`
1167 //
1168 // `total_consistency_lock`
1169 //  |
1170 //  |__`forward_htlcs`
1171 //  |   |
1172 //  |   |__`pending_intercepted_htlcs`
1173 //  |
1174 //  |__`per_peer_state`
1175 //      |
1176 //      |__`pending_inbound_payments`
1177 //          |
1178 //          |__`claimable_payments`
1179 //          |
1180 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1181 //              |
1182 //              |__`peer_state`
1183 //                  |
1184 //                  |__`outpoint_to_peer`
1185 //                  |
1186 //                  |__`short_to_chan_info`
1187 //                  |
1188 //                  |__`outbound_scid_aliases`
1189 //                  |
1190 //                  |__`best_block`
1191 //                  |
1192 //                  |__`pending_events`
1193 //                      |
1194 //                      |__`pending_background_events`
1195 //
1196 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1197 where
1198         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1199         T::Target: BroadcasterInterface,
1200         ES::Target: EntropySource,
1201         NS::Target: NodeSigner,
1202         SP::Target: SignerProvider,
1203         F::Target: FeeEstimator,
1204         R::Target: Router,
1205         L::Target: Logger,
1206 {
1207         default_configuration: UserConfig,
1208         chain_hash: ChainHash,
1209         fee_estimator: LowerBoundedFeeEstimator<F>,
1210         chain_monitor: M,
1211         tx_broadcaster: T,
1212         #[allow(unused)]
1213         router: R,
1214
1215         /// See `ChannelManager` struct-level documentation for lock order requirements.
1216         #[cfg(test)]
1217         pub(super) best_block: RwLock<BestBlock>,
1218         #[cfg(not(test))]
1219         best_block: RwLock<BestBlock>,
1220         secp_ctx: Secp256k1<secp256k1::All>,
1221
1222         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1223         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1224         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1225         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1226         ///
1227         /// See `ChannelManager` struct-level documentation for lock order requirements.
1228         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1229
1230         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1231         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1232         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1233         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1234         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1235         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1236         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1237         /// after reloading from disk while replaying blocks against ChannelMonitors.
1238         ///
1239         /// See `PendingOutboundPayment` documentation for more info.
1240         ///
1241         /// See `ChannelManager` struct-level documentation for lock order requirements.
1242         pending_outbound_payments: OutboundPayments,
1243
1244         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1245         ///
1246         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1247         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1248         /// and via the classic SCID.
1249         ///
1250         /// Note that no consistency guarantees are made about the existence of a channel with the
1251         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1252         ///
1253         /// See `ChannelManager` struct-level documentation for lock order requirements.
1254         #[cfg(test)]
1255         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1256         #[cfg(not(test))]
1257         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1258         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1259         /// until the user tells us what we should do with them.
1260         ///
1261         /// See `ChannelManager` struct-level documentation for lock order requirements.
1262         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1263
1264         /// The sets of payments which are claimable or currently being claimed. See
1265         /// [`ClaimablePayments`]' individual field docs for more info.
1266         ///
1267         /// See `ChannelManager` struct-level documentation for lock order requirements.
1268         claimable_payments: Mutex<ClaimablePayments>,
1269
1270         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1271         /// and some closed channels which reached a usable state prior to being closed. This is used
1272         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1273         /// active channel list on load.
1274         ///
1275         /// See `ChannelManager` struct-level documentation for lock order requirements.
1276         outbound_scid_aliases: Mutex<HashSet<u64>>,
1277
1278         /// Channel funding outpoint -> `counterparty_node_id`.
1279         ///
1280         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1281         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1282         /// the handling of the events.
1283         ///
1284         /// Note that no consistency guarantees are made about the existence of a peer with the
1285         /// `counterparty_node_id` in our other maps.
1286         ///
1287         /// TODO:
1288         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1289         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1290         /// would break backwards compatability.
1291         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1292         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1293         /// required to access the channel with the `counterparty_node_id`.
1294         ///
1295         /// See `ChannelManager` struct-level documentation for lock order requirements.
1296         #[cfg(not(test))]
1297         outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1298         #[cfg(test)]
1299         pub(crate) outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1300
1301         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1302         ///
1303         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1304         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1305         /// confirmation depth.
1306         ///
1307         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1308         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1309         /// channel with the `channel_id` in our other maps.
1310         ///
1311         /// See `ChannelManager` struct-level documentation for lock order requirements.
1312         #[cfg(test)]
1313         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1314         #[cfg(not(test))]
1315         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1316
1317         our_network_pubkey: PublicKey,
1318
1319         inbound_payment_key: inbound_payment::ExpandedKey,
1320
1321         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1322         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1323         /// we encrypt the namespace identifier using these bytes.
1324         ///
1325         /// [fake scids]: crate::util::scid_utils::fake_scid
1326         fake_scid_rand_bytes: [u8; 32],
1327
1328         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1329         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1330         /// keeping additional state.
1331         probing_cookie_secret: [u8; 32],
1332
1333         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1334         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1335         /// very far in the past, and can only ever be up to two hours in the future.
1336         highest_seen_timestamp: AtomicUsize,
1337
1338         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1339         /// basis, as well as the peer's latest features.
1340         ///
1341         /// If we are connected to a peer we always at least have an entry here, even if no channels
1342         /// are currently open with that peer.
1343         ///
1344         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1345         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1346         /// channels.
1347         ///
1348         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1349         ///
1350         /// See `ChannelManager` struct-level documentation for lock order requirements.
1351         #[cfg(not(any(test, feature = "_test_utils")))]
1352         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1353         #[cfg(any(test, feature = "_test_utils"))]
1354         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1355
1356         /// The set of events which we need to give to the user to handle. In some cases an event may
1357         /// require some further action after the user handles it (currently only blocking a monitor
1358         /// update from being handed to the user to ensure the included changes to the channel state
1359         /// are handled by the user before they're persisted durably to disk). In that case, the second
1360         /// element in the tuple is set to `Some` with further details of the action.
1361         ///
1362         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1363         /// could be in the middle of being processed without the direct mutex held.
1364         ///
1365         /// See `ChannelManager` struct-level documentation for lock order requirements.
1366         #[cfg(not(any(test, feature = "_test_utils")))]
1367         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1368         #[cfg(any(test, feature = "_test_utils"))]
1369         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1370
1371         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1372         pending_events_processor: AtomicBool,
1373
1374         /// If we are running during init (either directly during the deserialization method or in
1375         /// block connection methods which run after deserialization but before normal operation) we
1376         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1377         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1378         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1379         ///
1380         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1381         ///
1382         /// See `ChannelManager` struct-level documentation for lock order requirements.
1383         ///
1384         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1385         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1386         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1387         /// Essentially just when we're serializing ourselves out.
1388         /// Taken first everywhere where we are making changes before any other locks.
1389         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1390         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1391         /// Notifier the lock contains sends out a notification when the lock is released.
1392         total_consistency_lock: RwLock<()>,
1393         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1394         /// received and the monitor has been persisted.
1395         ///
1396         /// This information does not need to be persisted as funding nodes can forget
1397         /// unfunded channels upon disconnection.
1398         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1399
1400         background_events_processed_since_startup: AtomicBool,
1401
1402         event_persist_notifier: Notifier,
1403         needs_persist_flag: AtomicBool,
1404
1405         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1406
1407         entropy_source: ES,
1408         node_signer: NS,
1409         signer_provider: SP,
1410
1411         logger: L,
1412 }
1413
1414 /// Chain-related parameters used to construct a new `ChannelManager`.
1415 ///
1416 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1417 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1418 /// are not needed when deserializing a previously constructed `ChannelManager`.
1419 #[derive(Clone, Copy, PartialEq)]
1420 pub struct ChainParameters {
1421         /// The network for determining the `chain_hash` in Lightning messages.
1422         pub network: Network,
1423
1424         /// The hash and height of the latest block successfully connected.
1425         ///
1426         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1427         pub best_block: BestBlock,
1428 }
1429
1430 #[derive(Copy, Clone, PartialEq)]
1431 #[must_use]
1432 enum NotifyOption {
1433         DoPersist,
1434         SkipPersistHandleEvents,
1435         SkipPersistNoEvents,
1436 }
1437
1438 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1439 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1440 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1441 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1442 /// sending the aforementioned notification (since the lock being released indicates that the
1443 /// updates are ready for persistence).
1444 ///
1445 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1446 /// notify or not based on whether relevant changes have been made, providing a closure to
1447 /// `optionally_notify` which returns a `NotifyOption`.
1448 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1449         event_persist_notifier: &'a Notifier,
1450         needs_persist_flag: &'a AtomicBool,
1451         should_persist: F,
1452         // We hold onto this result so the lock doesn't get released immediately.
1453         _read_guard: RwLockReadGuard<'a, ()>,
1454 }
1455
1456 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1457         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1458         /// events to handle.
1459         ///
1460         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1461         /// other cases where losing the changes on restart may result in a force-close or otherwise
1462         /// isn't ideal.
1463         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1464                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1465         }
1466
1467         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1468         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1469                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1470                 let force_notify = cm.get_cm().process_background_events();
1471
1472                 PersistenceNotifierGuard {
1473                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1474                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1475                         should_persist: move || {
1476                                 // Pick the "most" action between `persist_check` and the background events
1477                                 // processing and return that.
1478                                 let notify = persist_check();
1479                                 match (notify, force_notify) {
1480                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1481                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1482                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1483                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1484                                         _ => NotifyOption::SkipPersistNoEvents,
1485                                 }
1486                         },
1487                         _read_guard: read_guard,
1488                 }
1489         }
1490
1491         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1492         /// [`ChannelManager::process_background_events`] MUST be called first (or
1493         /// [`Self::optionally_notify`] used).
1494         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1495         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1496                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1497
1498                 PersistenceNotifierGuard {
1499                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1500                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1501                         should_persist: persist_check,
1502                         _read_guard: read_guard,
1503                 }
1504         }
1505 }
1506
1507 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1508         fn drop(&mut self) {
1509                 match (self.should_persist)() {
1510                         NotifyOption::DoPersist => {
1511                                 self.needs_persist_flag.store(true, Ordering::Release);
1512                                 self.event_persist_notifier.notify()
1513                         },
1514                         NotifyOption::SkipPersistHandleEvents =>
1515                                 self.event_persist_notifier.notify(),
1516                         NotifyOption::SkipPersistNoEvents => {},
1517                 }
1518         }
1519 }
1520
1521 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1522 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1523 ///
1524 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1525 ///
1526 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1527 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1528 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1529 /// the maximum required amount in lnd as of March 2021.
1530 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1531
1532 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1533 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1534 ///
1535 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1536 ///
1537 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1538 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1539 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1540 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1541 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1542 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1543 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1544 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1545 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1546 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1547 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1548 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1549 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1550
1551 /// Minimum CLTV difference between the current block height and received inbound payments.
1552 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1553 /// this value.
1554 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1555 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1556 // a payment was being routed, so we add an extra block to be safe.
1557 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1558
1559 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1560 // ie that if the next-hop peer fails the HTLC within
1561 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1562 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1563 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1564 // LATENCY_GRACE_PERIOD_BLOCKS.
1565 #[allow(dead_code)]
1566 const CHECK_CLTV_EXPIRY_SANITY: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - CLTV_CLAIM_BUFFER - ANTI_REORG_DELAY - LATENCY_GRACE_PERIOD_BLOCKS;
1567
1568 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1569 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1570 #[allow(dead_code)]
1571 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1572
1573 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1574 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1575
1576 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1577 /// until we mark the channel disabled and gossip the update.
1578 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1579
1580 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1581 /// we mark the channel enabled and gossip the update.
1582 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1583
1584 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1585 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1586 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1587 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1588
1589 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1590 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1591 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1592
1593 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1594 /// many peers we reject new (inbound) connections.
1595 const MAX_NO_CHANNEL_PEERS: usize = 250;
1596
1597 /// Information needed for constructing an invoice route hint for this channel.
1598 #[derive(Clone, Debug, PartialEq)]
1599 pub struct CounterpartyForwardingInfo {
1600         /// Base routing fee in millisatoshis.
1601         pub fee_base_msat: u32,
1602         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1603         pub fee_proportional_millionths: u32,
1604         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1605         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1606         /// `cltv_expiry_delta` for more details.
1607         pub cltv_expiry_delta: u16,
1608 }
1609
1610 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1611 /// to better separate parameters.
1612 #[derive(Clone, Debug, PartialEq)]
1613 pub struct ChannelCounterparty {
1614         /// The node_id of our counterparty
1615         pub node_id: PublicKey,
1616         /// The Features the channel counterparty provided upon last connection.
1617         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1618         /// many routing-relevant features are present in the init context.
1619         pub features: InitFeatures,
1620         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1621         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1622         /// claiming at least this value on chain.
1623         ///
1624         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1625         ///
1626         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1627         pub unspendable_punishment_reserve: u64,
1628         /// Information on the fees and requirements that the counterparty requires when forwarding
1629         /// payments to us through this channel.
1630         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1631         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1632         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1633         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1634         pub outbound_htlc_minimum_msat: Option<u64>,
1635         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1636         pub outbound_htlc_maximum_msat: Option<u64>,
1637 }
1638
1639 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1640 #[derive(Clone, Debug, PartialEq)]
1641 pub struct ChannelDetails {
1642         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1643         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1644         /// Note that this means this value is *not* persistent - it can change once during the
1645         /// lifetime of the channel.
1646         pub channel_id: ChannelId,
1647         /// Parameters which apply to our counterparty. See individual fields for more information.
1648         pub counterparty: ChannelCounterparty,
1649         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1650         /// our counterparty already.
1651         pub funding_txo: Option<OutPoint>,
1652         /// The features which this channel operates with. See individual features for more info.
1653         ///
1654         /// `None` until negotiation completes and the channel type is finalized.
1655         pub channel_type: Option<ChannelTypeFeatures>,
1656         /// The position of the funding transaction in the chain. None if the funding transaction has
1657         /// not yet been confirmed and the channel fully opened.
1658         ///
1659         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1660         /// payments instead of this. See [`get_inbound_payment_scid`].
1661         ///
1662         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1663         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1664         ///
1665         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1666         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1667         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1668         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1669         /// [`confirmations_required`]: Self::confirmations_required
1670         pub short_channel_id: Option<u64>,
1671         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1672         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1673         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1674         /// `Some(0)`).
1675         ///
1676         /// This will be `None` as long as the channel is not available for routing outbound payments.
1677         ///
1678         /// [`short_channel_id`]: Self::short_channel_id
1679         /// [`confirmations_required`]: Self::confirmations_required
1680         pub outbound_scid_alias: Option<u64>,
1681         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1682         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1683         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1684         /// when they see a payment to be routed to us.
1685         ///
1686         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1687         /// previous values for inbound payment forwarding.
1688         ///
1689         /// [`short_channel_id`]: Self::short_channel_id
1690         pub inbound_scid_alias: Option<u64>,
1691         /// The value, in satoshis, of this channel as appears in the funding output
1692         pub channel_value_satoshis: u64,
1693         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1694         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1695         /// this value on chain.
1696         ///
1697         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1698         ///
1699         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1700         ///
1701         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1702         pub unspendable_punishment_reserve: Option<u64>,
1703         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1704         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1705         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1706         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1707         /// serialized with LDK versions prior to 0.0.113.
1708         ///
1709         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1710         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1711         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1712         pub user_channel_id: u128,
1713         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1714         /// which is applied to commitment and HTLC transactions.
1715         ///
1716         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1717         pub feerate_sat_per_1000_weight: Option<u32>,
1718         /// Our total balance.  This is the amount we would get if we close the channel.
1719         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1720         /// amount is not likely to be recoverable on close.
1721         ///
1722         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1723         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1724         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1725         /// This does not consider any on-chain fees.
1726         ///
1727         /// See also [`ChannelDetails::outbound_capacity_msat`]
1728         pub balance_msat: u64,
1729         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1730         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1731         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1732         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1733         ///
1734         /// See also [`ChannelDetails::balance_msat`]
1735         ///
1736         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1737         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1738         /// should be able to spend nearly this amount.
1739         pub outbound_capacity_msat: u64,
1740         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1741         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1742         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1743         /// to use a limit as close as possible to the HTLC limit we can currently send.
1744         ///
1745         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1746         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1747         pub next_outbound_htlc_limit_msat: u64,
1748         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1749         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1750         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1751         /// route which is valid.
1752         pub next_outbound_htlc_minimum_msat: u64,
1753         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1754         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1755         /// available for inclusion in new inbound HTLCs).
1756         /// Note that there are some corner cases not fully handled here, so the actual available
1757         /// inbound capacity may be slightly higher than this.
1758         ///
1759         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1760         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1761         /// However, our counterparty should be able to spend nearly this amount.
1762         pub inbound_capacity_msat: u64,
1763         /// The number of required confirmations on the funding transaction before the funding will be
1764         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1765         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1766         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1767         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1768         ///
1769         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1770         ///
1771         /// [`is_outbound`]: ChannelDetails::is_outbound
1772         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1773         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1774         pub confirmations_required: Option<u32>,
1775         /// The current number of confirmations on the funding transaction.
1776         ///
1777         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1778         pub confirmations: Option<u32>,
1779         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1780         /// until we can claim our funds after we force-close the channel. During this time our
1781         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1782         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1783         /// time to claim our non-HTLC-encumbered funds.
1784         ///
1785         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1786         pub force_close_spend_delay: Option<u16>,
1787         /// True if the channel was initiated (and thus funded) by us.
1788         pub is_outbound: bool,
1789         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1790         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1791         /// required confirmation count has been reached (and we were connected to the peer at some
1792         /// point after the funding transaction received enough confirmations). The required
1793         /// confirmation count is provided in [`confirmations_required`].
1794         ///
1795         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1796         pub is_channel_ready: bool,
1797         /// The stage of the channel's shutdown.
1798         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1799         pub channel_shutdown_state: Option<ChannelShutdownState>,
1800         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1801         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1802         ///
1803         /// This is a strict superset of `is_channel_ready`.
1804         pub is_usable: bool,
1805         /// True if this channel is (or will be) publicly-announced.
1806         pub is_public: bool,
1807         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1808         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1809         pub inbound_htlc_minimum_msat: Option<u64>,
1810         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1811         pub inbound_htlc_maximum_msat: Option<u64>,
1812         /// Set of configurable parameters that affect channel operation.
1813         ///
1814         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1815         pub config: Option<ChannelConfig>,
1816         /// Pending inbound HTLCs.
1817         ///
1818         /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
1819         pub pending_inbound_htlcs: Vec<InboundHTLCDetails>,
1820         /// Pending outbound HTLCs.
1821         ///
1822         /// This field is empty for objects serialized with LDK versions prior to 0.0.122.
1823         pub pending_outbound_htlcs: Vec<OutboundHTLCDetails>,
1824 }
1825
1826 impl ChannelDetails {
1827         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1828         /// This should be used for providing invoice hints or in any other context where our
1829         /// counterparty will forward a payment to us.
1830         ///
1831         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1832         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1833         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1834                 self.inbound_scid_alias.or(self.short_channel_id)
1835         }
1836
1837         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1838         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1839         /// we're sending or forwarding a payment outbound over this channel.
1840         ///
1841         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1842         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1843         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1844                 self.short_channel_id.or(self.outbound_scid_alias)
1845         }
1846
1847         fn from_channel_context<SP: Deref, F: Deref>(
1848                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1849                 fee_estimator: &LowerBoundedFeeEstimator<F>
1850         ) -> Self
1851         where
1852                 SP::Target: SignerProvider,
1853                 F::Target: FeeEstimator
1854         {
1855                 let balance = context.get_available_balances(fee_estimator);
1856                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1857                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1858                 ChannelDetails {
1859                         channel_id: context.channel_id(),
1860                         counterparty: ChannelCounterparty {
1861                                 node_id: context.get_counterparty_node_id(),
1862                                 features: latest_features,
1863                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1864                                 forwarding_info: context.counterparty_forwarding_info(),
1865                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1866                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1867                                 // message (as they are always the first message from the counterparty).
1868                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1869                                 // default `0` value set by `Channel::new_outbound`.
1870                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1871                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1872                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1873                         },
1874                         funding_txo: context.get_funding_txo(),
1875                         // Note that accept_channel (or open_channel) is always the first message, so
1876                         // `have_received_message` indicates that type negotiation has completed.
1877                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1878                         short_channel_id: context.get_short_channel_id(),
1879                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1880                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1881                         channel_value_satoshis: context.get_value_satoshis(),
1882                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1883                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1884                         balance_msat: balance.balance_msat,
1885                         inbound_capacity_msat: balance.inbound_capacity_msat,
1886                         outbound_capacity_msat: balance.outbound_capacity_msat,
1887                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1888                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1889                         user_channel_id: context.get_user_id(),
1890                         confirmations_required: context.minimum_depth(),
1891                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1892                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1893                         is_outbound: context.is_outbound(),
1894                         is_channel_ready: context.is_usable(),
1895                         is_usable: context.is_live(),
1896                         is_public: context.should_announce(),
1897                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1898                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1899                         config: Some(context.config()),
1900                         channel_shutdown_state: Some(context.shutdown_state()),
1901                         pending_inbound_htlcs: context.get_pending_inbound_htlc_details(),
1902                         pending_outbound_htlcs: context.get_pending_outbound_htlc_details(),
1903                 }
1904         }
1905 }
1906
1907 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1908 /// Further information on the details of the channel shutdown.
1909 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1910 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1911 /// the channel will be removed shortly.
1912 /// Also note, that in normal operation, peers could disconnect at any of these states
1913 /// and require peer re-connection before making progress onto other states
1914 pub enum ChannelShutdownState {
1915         /// Channel has not sent or received a shutdown message.
1916         NotShuttingDown,
1917         /// Local node has sent a shutdown message for this channel.
1918         ShutdownInitiated,
1919         /// Shutdown message exchanges have concluded and the channels are in the midst of
1920         /// resolving all existing open HTLCs before closing can continue.
1921         ResolvingHTLCs,
1922         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1923         NegotiatingClosingFee,
1924         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1925         /// to drop the channel.
1926         ShutdownComplete,
1927 }
1928
1929 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1930 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1931 #[derive(Debug, PartialEq)]
1932 pub enum RecentPaymentDetails {
1933         /// When an invoice was requested and thus a payment has not yet been sent.
1934         AwaitingInvoice {
1935                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1936                 /// a payment and ensure idempotency in LDK.
1937                 payment_id: PaymentId,
1938         },
1939         /// When a payment is still being sent and awaiting successful delivery.
1940         Pending {
1941                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1942                 /// a payment and ensure idempotency in LDK.
1943                 payment_id: PaymentId,
1944                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1945                 /// abandoned.
1946                 payment_hash: PaymentHash,
1947                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1948                 /// not just the amount currently inflight.
1949                 total_msat: u64,
1950         },
1951         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1952         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1953         /// payment is removed from tracking.
1954         Fulfilled {
1955                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1956                 /// a payment and ensure idempotency in LDK.
1957                 payment_id: PaymentId,
1958                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1959                 /// made before LDK version 0.0.104.
1960                 payment_hash: Option<PaymentHash>,
1961         },
1962         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1963         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1964         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1965         Abandoned {
1966                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1967                 /// a payment and ensure idempotency in LDK.
1968                 payment_id: PaymentId,
1969                 /// Hash of the payment that we have given up trying to send.
1970                 payment_hash: PaymentHash,
1971         },
1972 }
1973
1974 /// Route hints used in constructing invoices for [phantom node payents].
1975 ///
1976 /// [phantom node payments]: crate::sign::PhantomKeysManager
1977 #[derive(Clone)]
1978 pub struct PhantomRouteHints {
1979         /// The list of channels to be included in the invoice route hints.
1980         pub channels: Vec<ChannelDetails>,
1981         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1982         /// route hints.
1983         pub phantom_scid: u64,
1984         /// The pubkey of the real backing node that would ultimately receive the payment.
1985         pub real_node_pubkey: PublicKey,
1986 }
1987
1988 macro_rules! handle_error {
1989         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1990                 // In testing, ensure there are no deadlocks where the lock is already held upon
1991                 // entering the macro.
1992                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1993                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1994
1995                 match $internal {
1996                         Ok(msg) => Ok(msg),
1997                         Err(MsgHandleErrInternal { err, shutdown_finish, .. }) => {
1998                                 let mut msg_events = Vec::with_capacity(2);
1999
2000                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
2001                                         let counterparty_node_id = shutdown_res.counterparty_node_id;
2002                                         let channel_id = shutdown_res.channel_id;
2003                                         let logger = WithContext::from(
2004                                                 &$self.logger, Some(counterparty_node_id), Some(channel_id),
2005                                         );
2006                                         log_error!(logger, "Force-closing channel: {}", err.err);
2007
2008                                         $self.finish_close_channel(shutdown_res);
2009                                         if let Some(update) = update_option {
2010                                                 msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
2011                                                         msg: update
2012                                                 });
2013                                         }
2014                                 } else {
2015                                         log_error!($self.logger, "Got non-closing error: {}", err.err);
2016                                 }
2017
2018                                 if let msgs::ErrorAction::IgnoreError = err.action {
2019                                 } else {
2020                                         msg_events.push(events::MessageSendEvent::HandleError {
2021                                                 node_id: $counterparty_node_id,
2022                                                 action: err.action.clone()
2023                                         });
2024                                 }
2025
2026                                 if !msg_events.is_empty() {
2027                                         let per_peer_state = $self.per_peer_state.read().unwrap();
2028                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
2029                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2030                                                 peer_state.pending_msg_events.append(&mut msg_events);
2031                                         }
2032                                 }
2033
2034                                 // Return error in case higher-API need one
2035                                 Err(err)
2036                         },
2037                 }
2038         } };
2039 }
2040
2041 macro_rules! update_maps_on_chan_removal {
2042         ($self: expr, $channel_context: expr) => {{
2043                 if let Some(outpoint) = $channel_context.get_funding_txo() {
2044                         $self.outpoint_to_peer.lock().unwrap().remove(&outpoint);
2045                 }
2046                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2047                 if let Some(short_id) = $channel_context.get_short_channel_id() {
2048                         short_to_chan_info.remove(&short_id);
2049                 } else {
2050                         // If the channel was never confirmed on-chain prior to its closure, remove the
2051                         // outbound SCID alias we used for it from the collision-prevention set. While we
2052                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
2053                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
2054                         // opening a million channels with us which are closed before we ever reach the funding
2055                         // stage.
2056                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
2057                         debug_assert!(alias_removed);
2058                 }
2059                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
2060         }}
2061 }
2062
2063 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
2064 macro_rules! convert_chan_phase_err {
2065         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
2066                 match $err {
2067                         ChannelError::Warn(msg) => {
2068                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
2069                         },
2070                         ChannelError::Ignore(msg) => {
2071                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
2072                         },
2073                         ChannelError::Close(msg) => {
2074                                 let logger = WithChannelContext::from(&$self.logger, &$channel.context);
2075                                 log_error!(logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
2076                                 update_maps_on_chan_removal!($self, $channel.context);
2077                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
2078                                 let shutdown_res = $channel.context.force_shutdown(true, reason);
2079                                 let err =
2080                                         MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $channel_update);
2081                                 (true, err)
2082                         },
2083                 }
2084         };
2085         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
2086                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
2087         };
2088         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
2089                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
2090         };
2091         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
2092                 match $channel_phase {
2093                         ChannelPhase::Funded(channel) => {
2094                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
2095                         },
2096                         ChannelPhase::UnfundedOutboundV1(channel) => {
2097                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2098                         },
2099                         ChannelPhase::UnfundedInboundV1(channel) => {
2100                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2101                         },
2102                         #[cfg(dual_funding)]
2103                         ChannelPhase::UnfundedOutboundV2(channel) => {
2104                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2105                         },
2106                         #[cfg(dual_funding)]
2107                         ChannelPhase::UnfundedInboundV2(channel) => {
2108                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2109                         },
2110                 }
2111         };
2112 }
2113
2114 macro_rules! break_chan_phase_entry {
2115         ($self: ident, $res: expr, $entry: expr) => {
2116                 match $res {
2117                         Ok(res) => res,
2118                         Err(e) => {
2119                                 let key = *$entry.key();
2120                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2121                                 if drop {
2122                                         $entry.remove_entry();
2123                                 }
2124                                 break Err(res);
2125                         }
2126                 }
2127         }
2128 }
2129
2130 macro_rules! try_chan_phase_entry {
2131         ($self: ident, $res: expr, $entry: expr) => {
2132                 match $res {
2133                         Ok(res) => res,
2134                         Err(e) => {
2135                                 let key = *$entry.key();
2136                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2137                                 if drop {
2138                                         $entry.remove_entry();
2139                                 }
2140                                 return Err(res);
2141                         }
2142                 }
2143         }
2144 }
2145
2146 macro_rules! remove_channel_phase {
2147         ($self: expr, $entry: expr) => {
2148                 {
2149                         let channel = $entry.remove_entry().1;
2150                         update_maps_on_chan_removal!($self, &channel.context());
2151                         channel
2152                 }
2153         }
2154 }
2155
2156 macro_rules! send_channel_ready {
2157         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2158                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2159                         node_id: $channel.context.get_counterparty_node_id(),
2160                         msg: $channel_ready_msg,
2161                 });
2162                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2163                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2164                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2165                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2166                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2167                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2168                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2169                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2170                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2171                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2172                 }
2173         }}
2174 }
2175
2176 macro_rules! emit_channel_pending_event {
2177         ($locked_events: expr, $channel: expr) => {
2178                 if $channel.context.should_emit_channel_pending_event() {
2179                         $locked_events.push_back((events::Event::ChannelPending {
2180                                 channel_id: $channel.context.channel_id(),
2181                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2182                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2183                                 user_channel_id: $channel.context.get_user_id(),
2184                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2185                                 channel_type: Some($channel.context.get_channel_type().clone()),
2186                         }, None));
2187                         $channel.context.set_channel_pending_event_emitted();
2188                 }
2189         }
2190 }
2191
2192 macro_rules! emit_channel_ready_event {
2193         ($locked_events: expr, $channel: expr) => {
2194                 if $channel.context.should_emit_channel_ready_event() {
2195                         debug_assert!($channel.context.channel_pending_event_emitted());
2196                         $locked_events.push_back((events::Event::ChannelReady {
2197                                 channel_id: $channel.context.channel_id(),
2198                                 user_channel_id: $channel.context.get_user_id(),
2199                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2200                                 channel_type: $channel.context.get_channel_type().clone(),
2201                         }, None));
2202                         $channel.context.set_channel_ready_event_emitted();
2203                 }
2204         }
2205 }
2206
2207 macro_rules! handle_monitor_update_completion {
2208         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2209                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2210                 let mut updates = $chan.monitor_updating_restored(&&logger,
2211                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2212                         $self.best_block.read().unwrap().height());
2213                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2214                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2215                         // We only send a channel_update in the case where we are just now sending a
2216                         // channel_ready and the channel is in a usable state. We may re-send a
2217                         // channel_update later through the announcement_signatures process for public
2218                         // channels, but there's no reason not to just inform our counterparty of our fees
2219                         // now.
2220                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2221                                 Some(events::MessageSendEvent::SendChannelUpdate {
2222                                         node_id: counterparty_node_id,
2223                                         msg,
2224                                 })
2225                         } else { None }
2226                 } else { None };
2227
2228                 let update_actions = $peer_state.monitor_update_blocked_actions
2229                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2230
2231                 let htlc_forwards = $self.handle_channel_resumption(
2232                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2233                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2234                         updates.funding_broadcastable, updates.channel_ready,
2235                         updates.announcement_sigs);
2236                 if let Some(upd) = channel_update {
2237                         $peer_state.pending_msg_events.push(upd);
2238                 }
2239
2240                 let channel_id = $chan.context.channel_id();
2241                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2242                 core::mem::drop($peer_state_lock);
2243                 core::mem::drop($per_peer_state_lock);
2244
2245                 // If the channel belongs to a batch funding transaction, the progress of the batch
2246                 // should be updated as we have received funding_signed and persisted the monitor.
2247                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2248                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2249                         let mut batch_completed = false;
2250                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2251                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2252                                         *chan_id == channel_id &&
2253                                         *pubkey == counterparty_node_id
2254                                 ));
2255                                 if let Some(channel_state) = channel_state {
2256                                         channel_state.2 = true;
2257                                 } else {
2258                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2259                                 }
2260                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2261                         } else {
2262                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2263                         }
2264
2265                         // When all channels in a batched funding transaction have become ready, it is not necessary
2266                         // to track the progress of the batch anymore and the state of the channels can be updated.
2267                         if batch_completed {
2268                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2269                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2270                                 let mut batch_funding_tx = None;
2271                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2272                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2273                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2274                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2275                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2276                                                         chan.set_batch_ready();
2277                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2278                                                         emit_channel_pending_event!(pending_events, chan);
2279                                                 }
2280                                         }
2281                                 }
2282                                 if let Some(tx) = batch_funding_tx {
2283                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2284                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2285                                 }
2286                         }
2287                 }
2288
2289                 $self.handle_monitor_update_completion_actions(update_actions);
2290
2291                 if let Some(forwards) = htlc_forwards {
2292                         $self.forward_htlcs(&mut [forwards][..]);
2293                 }
2294                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2295                 for failure in updates.failed_htlcs.drain(..) {
2296                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2297                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2298                 }
2299         } }
2300 }
2301
2302 macro_rules! handle_new_monitor_update {
2303         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2304                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2305                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2306                 match $update_res {
2307                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2308                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2309                                 log_error!(logger, "{}", err_str);
2310                                 panic!("{}", err_str);
2311                         },
2312                         ChannelMonitorUpdateStatus::InProgress => {
2313                                 log_debug!(logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2314                                         &$chan.context.channel_id());
2315                                 false
2316                         },
2317                         ChannelMonitorUpdateStatus::Completed => {
2318                                 $completed;
2319                                 true
2320                         },
2321                 }
2322         } };
2323         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2324                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2325                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2326         };
2327         ($self: ident, $funding_txo: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2328                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2329                         .or_insert_with(Vec::new);
2330                 // During startup, we push monitor updates as background events through to here in
2331                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2332                 // filter for uniqueness here.
2333                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2334                         .unwrap_or_else(|| {
2335                                 in_flight_updates.push($update);
2336                                 in_flight_updates.len() - 1
2337                         });
2338                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2339                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2340                         {
2341                                 let _ = in_flight_updates.remove(idx);
2342                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2343                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2344                                 }
2345                         })
2346         } };
2347 }
2348
2349 macro_rules! process_events_body {
2350         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2351                 let mut processed_all_events = false;
2352                 while !processed_all_events {
2353                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2354                                 return;
2355                         }
2356
2357                         let mut result;
2358
2359                         {
2360                                 // We'll acquire our total consistency lock so that we can be sure no other
2361                                 // persists happen while processing monitor events.
2362                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2363
2364                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2365                                 // ensure any startup-generated background events are handled first.
2366                                 result = $self.process_background_events();
2367
2368                                 // TODO: This behavior should be documented. It's unintuitive that we query
2369                                 // ChannelMonitors when clearing other events.
2370                                 if $self.process_pending_monitor_events() {
2371                                         result = NotifyOption::DoPersist;
2372                                 }
2373                         }
2374
2375                         let pending_events = $self.pending_events.lock().unwrap().clone();
2376                         let num_events = pending_events.len();
2377                         if !pending_events.is_empty() {
2378                                 result = NotifyOption::DoPersist;
2379                         }
2380
2381                         let mut post_event_actions = Vec::new();
2382
2383                         for (event, action_opt) in pending_events {
2384                                 $event_to_handle = event;
2385                                 $handle_event;
2386                                 if let Some(action) = action_opt {
2387                                         post_event_actions.push(action);
2388                                 }
2389                         }
2390
2391                         {
2392                                 let mut pending_events = $self.pending_events.lock().unwrap();
2393                                 pending_events.drain(..num_events);
2394                                 processed_all_events = pending_events.is_empty();
2395                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2396                                 // updated here with the `pending_events` lock acquired.
2397                                 $self.pending_events_processor.store(false, Ordering::Release);
2398                         }
2399
2400                         if !post_event_actions.is_empty() {
2401                                 $self.handle_post_event_actions(post_event_actions);
2402                                 // If we had some actions, go around again as we may have more events now
2403                                 processed_all_events = false;
2404                         }
2405
2406                         match result {
2407                                 NotifyOption::DoPersist => {
2408                                         $self.needs_persist_flag.store(true, Ordering::Release);
2409                                         $self.event_persist_notifier.notify();
2410                                 },
2411                                 NotifyOption::SkipPersistHandleEvents =>
2412                                         $self.event_persist_notifier.notify(),
2413                                 NotifyOption::SkipPersistNoEvents => {},
2414                         }
2415                 }
2416         }
2417 }
2418
2419 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, L>
2420 where
2421         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
2422         T::Target: BroadcasterInterface,
2423         ES::Target: EntropySource,
2424         NS::Target: NodeSigner,
2425         SP::Target: SignerProvider,
2426         F::Target: FeeEstimator,
2427         R::Target: Router,
2428         L::Target: Logger,
2429 {
2430         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2431         ///
2432         /// The current time or latest block header time can be provided as the `current_timestamp`.
2433         ///
2434         /// This is the main "logic hub" for all channel-related actions, and implements
2435         /// [`ChannelMessageHandler`].
2436         ///
2437         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2438         ///
2439         /// Users need to notify the new `ChannelManager` when a new block is connected or
2440         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2441         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2442         /// more details.
2443         ///
2444         /// [`block_connected`]: chain::Listen::block_connected
2445         /// [`block_disconnected`]: chain::Listen::block_disconnected
2446         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2447         pub fn new(
2448                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2449                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2450                 current_timestamp: u32,
2451         ) -> Self {
2452                 let mut secp_ctx = Secp256k1::new();
2453                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2454                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2455                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2456                 ChannelManager {
2457                         default_configuration: config.clone(),
2458                         chain_hash: ChainHash::using_genesis_block(params.network),
2459                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2460                         chain_monitor,
2461                         tx_broadcaster,
2462                         router,
2463
2464                         best_block: RwLock::new(params.best_block),
2465
2466                         outbound_scid_aliases: Mutex::new(new_hash_set()),
2467                         pending_inbound_payments: Mutex::new(new_hash_map()),
2468                         pending_outbound_payments: OutboundPayments::new(),
2469                         forward_htlcs: Mutex::new(new_hash_map()),
2470                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: new_hash_map(), pending_claiming_payments: new_hash_map() }),
2471                         pending_intercepted_htlcs: Mutex::new(new_hash_map()),
2472                         outpoint_to_peer: Mutex::new(new_hash_map()),
2473                         short_to_chan_info: FairRwLock::new(new_hash_map()),
2474
2475                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2476                         secp_ctx,
2477
2478                         inbound_payment_key: expanded_inbound_key,
2479                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2480
2481                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2482
2483                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2484
2485                         per_peer_state: FairRwLock::new(new_hash_map()),
2486
2487                         pending_events: Mutex::new(VecDeque::new()),
2488                         pending_events_processor: AtomicBool::new(false),
2489                         pending_background_events: Mutex::new(Vec::new()),
2490                         total_consistency_lock: RwLock::new(()),
2491                         background_events_processed_since_startup: AtomicBool::new(false),
2492                         event_persist_notifier: Notifier::new(),
2493                         needs_persist_flag: AtomicBool::new(false),
2494                         funding_batch_states: Mutex::new(BTreeMap::new()),
2495
2496                         pending_offers_messages: Mutex::new(Vec::new()),
2497
2498                         entropy_source,
2499                         node_signer,
2500                         signer_provider,
2501
2502                         logger,
2503                 }
2504         }
2505
2506         /// Gets the current configuration applied to all new channels.
2507         pub fn get_current_default_configuration(&self) -> &UserConfig {
2508                 &self.default_configuration
2509         }
2510
2511         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2512                 let height = self.best_block.read().unwrap().height();
2513                 let mut outbound_scid_alias = 0;
2514                 let mut i = 0;
2515                 loop {
2516                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2517                                 outbound_scid_alias += 1;
2518                         } else {
2519                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2520                         }
2521                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2522                                 break;
2523                         }
2524                         i += 1;
2525                         if i > 1_000_000 { panic!("Your RNG is busted or we ran out of possible outbound SCID aliases (which should never happen before we run out of memory to store channels"); }
2526                 }
2527                 outbound_scid_alias
2528         }
2529
2530         /// Creates a new outbound channel to the given remote node and with the given value.
2531         ///
2532         /// `user_channel_id` will be provided back as in
2533         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2534         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2535         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2536         /// is simply copied to events and otherwise ignored.
2537         ///
2538         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2539         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2540         ///
2541         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2542         /// generate a shutdown scriptpubkey or destination script set by
2543         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2544         ///
2545         /// Note that we do not check if you are currently connected to the given peer. If no
2546         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2547         /// the channel eventually being silently forgotten (dropped on reload).
2548         ///
2549         /// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the
2550         /// channel. Otherwise, a random one will be generated for you.
2551         ///
2552         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2553         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2554         /// [`ChannelDetails::channel_id`] until after
2555         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2556         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2557         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2558         ///
2559         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2560         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2561         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2562         pub fn create_channel(&self, their_network_key: PublicKey, channel_value_satoshis: u64, push_msat: u64, user_channel_id: u128, temporary_channel_id: Option<ChannelId>, override_config: Option<UserConfig>) -> Result<ChannelId, APIError> {
2563                 if channel_value_satoshis < 1000 {
2564                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2565                 }
2566
2567                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2568                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2569                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2570
2571                 let per_peer_state = self.per_peer_state.read().unwrap();
2572
2573                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2574                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2575
2576                 let mut peer_state = peer_state_mutex.lock().unwrap();
2577
2578                 if let Some(temporary_channel_id) = temporary_channel_id {
2579                         if peer_state.channel_by_id.contains_key(&temporary_channel_id) {
2580                                 return Err(APIError::APIMisuseError{ err: format!("Channel with temporary channel ID {} already exists!", temporary_channel_id)});
2581                         }
2582                 }
2583
2584                 let channel = {
2585                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2586                         let their_features = &peer_state.latest_features;
2587                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2588                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2589                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2590                                 self.best_block.read().unwrap().height(), outbound_scid_alias, temporary_channel_id)
2591                         {
2592                                 Ok(res) => res,
2593                                 Err(e) => {
2594                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2595                                         return Err(e);
2596                                 },
2597                         }
2598                 };
2599                 let res = channel.get_open_channel(self.chain_hash);
2600
2601                 let temporary_channel_id = channel.context.channel_id();
2602                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2603                         hash_map::Entry::Occupied(_) => {
2604                                 if cfg!(fuzzing) {
2605                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2606                                 } else {
2607                                         panic!("RNG is bad???");
2608                                 }
2609                         },
2610                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2611                 }
2612
2613                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2614                         node_id: their_network_key,
2615                         msg: res,
2616                 });
2617                 Ok(temporary_channel_id)
2618         }
2619
2620         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2621                 // Allocate our best estimate of the number of channels we have in the `res`
2622                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2623                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2624                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2625                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2626                 // the same channel.
2627                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2628                 {
2629                         let best_block_height = self.best_block.read().unwrap().height();
2630                         let per_peer_state = self.per_peer_state.read().unwrap();
2631                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2632                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2633                                 let peer_state = &mut *peer_state_lock;
2634                                 res.extend(peer_state.channel_by_id.iter()
2635                                         .filter_map(|(chan_id, phase)| match phase {
2636                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2637                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2638                                                 _ => None,
2639                                         })
2640                                         .filter(f)
2641                                         .map(|(_channel_id, channel)| {
2642                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2643                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2644                                         })
2645                                 );
2646                         }
2647                 }
2648                 res
2649         }
2650
2651         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2652         /// more information.
2653         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2654                 // Allocate our best estimate of the number of channels we have in the `res`
2655                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2656                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2657                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2658                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2659                 // the same channel.
2660                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2661                 {
2662                         let best_block_height = self.best_block.read().unwrap().height();
2663                         let per_peer_state = self.per_peer_state.read().unwrap();
2664                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2665                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2666                                 let peer_state = &mut *peer_state_lock;
2667                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2668                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2669                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2670                                         res.push(details);
2671                                 }
2672                         }
2673                 }
2674                 res
2675         }
2676
2677         /// Gets the list of usable channels, in random order. Useful as an argument to
2678         /// [`Router::find_route`] to ensure non-announced channels are used.
2679         ///
2680         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2681         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2682         /// are.
2683         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2684                 // Note we use is_live here instead of usable which leads to somewhat confused
2685                 // internal/external nomenclature, but that's ok cause that's probably what the user
2686                 // really wanted anyway.
2687                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2688         }
2689
2690         /// Gets the list of channels we have with a given counterparty, in random order.
2691         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2692                 let best_block_height = self.best_block.read().unwrap().height();
2693                 let per_peer_state = self.per_peer_state.read().unwrap();
2694
2695                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2696                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2697                         let peer_state = &mut *peer_state_lock;
2698                         let features = &peer_state.latest_features;
2699                         let context_to_details = |context| {
2700                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2701                         };
2702                         return peer_state.channel_by_id
2703                                 .iter()
2704                                 .map(|(_, phase)| phase.context())
2705                                 .map(context_to_details)
2706                                 .collect();
2707                 }
2708                 vec![]
2709         }
2710
2711         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2712         /// successful path, or have unresolved HTLCs.
2713         ///
2714         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2715         /// result of a crash. If such a payment exists, is not listed here, and an
2716         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2717         ///
2718         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2719         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2720                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2721                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2722                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2723                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2724                                 },
2725                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2726                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2727                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2728                                 },
2729                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2730                                         Some(RecentPaymentDetails::Pending {
2731                                                 payment_id: *payment_id,
2732                                                 payment_hash: *payment_hash,
2733                                                 total_msat: *total_msat,
2734                                         })
2735                                 },
2736                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2737                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2738                                 },
2739                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2740                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2741                                 },
2742                                 PendingOutboundPayment::Legacy { .. } => None
2743                         })
2744                         .collect()
2745         }
2746
2747         fn close_channel_internal(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, override_shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
2748                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2749
2750                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
2751                 let mut shutdown_result = None;
2752
2753                 {
2754                         let per_peer_state = self.per_peer_state.read().unwrap();
2755
2756                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2757                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2758
2759                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2760                         let peer_state = &mut *peer_state_lock;
2761
2762                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2763                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2764                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2765                                                 let funding_txo_opt = chan.context.get_funding_txo();
2766                                                 let their_features = &peer_state.latest_features;
2767                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2768                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2769                                                 failed_htlcs = htlcs;
2770
2771                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2772                                                 // here as we don't need the monitor update to complete until we send a
2773                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2774                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2775                                                         node_id: *counterparty_node_id,
2776                                                         msg: shutdown_msg,
2777                                                 });
2778
2779                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2780                                                         "We can't both complete shutdown and generate a monitor update");
2781
2782                                                 // Update the monitor with the shutdown script if necessary.
2783                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2784                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
2785                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2786                                                 }
2787                                         } else {
2788                                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2789                                                 shutdown_result = Some(chan_phase.context_mut().force_shutdown(false, ClosureReason::HolderForceClosed));
2790                                         }
2791                                 },
2792                                 hash_map::Entry::Vacant(_) => {
2793                                         return Err(APIError::ChannelUnavailable {
2794                                                 err: format!(
2795                                                         "Channel with id {} not found for the passed counterparty node_id {}",
2796                                                         channel_id, counterparty_node_id,
2797                                                 )
2798                                         });
2799                                 },
2800                         }
2801                 }
2802
2803                 for htlc_source in failed_htlcs.drain(..) {
2804                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2805                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2806                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2807                 }
2808
2809                 if let Some(shutdown_result) = shutdown_result {
2810                         self.finish_close_channel(shutdown_result);
2811                 }
2812
2813                 Ok(())
2814         }
2815
2816         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2817         /// will be accepted on the given channel, and after additional timeout/the closing of all
2818         /// pending HTLCs, the channel will be closed on chain.
2819         ///
2820         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2821         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2822         ///    fee estimate.
2823         ///  * If our counterparty is the channel initiator, we will require a channel closing
2824         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2825         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2826         ///    counterparty to pay as much fee as they'd like, however.
2827         ///
2828         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2829         ///
2830         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2831         /// generate a shutdown scriptpubkey or destination script set by
2832         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2833         /// channel.
2834         ///
2835         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2836         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2837         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2838         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2839         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2840                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2841         }
2842
2843         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2844         /// will be accepted on the given channel, and after additional timeout/the closing of all
2845         /// pending HTLCs, the channel will be closed on chain.
2846         ///
2847         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2848         /// the channel being closed or not:
2849         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2850         ///    transaction. The upper-bound is set by
2851         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2852         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2853         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2854         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2855         ///    will appear on a force-closure transaction, whichever is lower).
2856         ///
2857         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2858         /// Will fail if a shutdown script has already been set for this channel by
2859         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2860         /// also be compatible with our and the counterparty's features.
2861         ///
2862         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2863         ///
2864         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2865         /// generate a shutdown scriptpubkey or destination script set by
2866         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2867         /// channel.
2868         ///
2869         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2870         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2871         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2872         pub fn close_channel_with_feerate_and_script(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
2873                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2874         }
2875
2876         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2877                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2878                 #[cfg(debug_assertions)]
2879                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2880                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2881                 }
2882
2883                 let logger = WithContext::from(
2884                         &self.logger, Some(shutdown_res.counterparty_node_id), Some(shutdown_res.channel_id),
2885                 );
2886
2887                 log_debug!(logger, "Finishing closure of channel due to {} with {} HTLCs to fail",
2888                         shutdown_res.closure_reason, shutdown_res.dropped_outbound_htlcs.len());
2889                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2890                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2891                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2892                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2893                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2894                 }
2895                 if let Some((_, funding_txo, _channel_id, monitor_update)) = shutdown_res.monitor_update {
2896                         // There isn't anything we can do if we get an update failure - we're already
2897                         // force-closing. The monitor update on the required in-memory copy should broadcast
2898                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2899                         // ignore the result here.
2900                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2901                 }
2902                 let mut shutdown_results = Vec::new();
2903                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2904                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2905                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2906                         let per_peer_state = self.per_peer_state.read().unwrap();
2907                         let mut has_uncompleted_channel = None;
2908                         for (channel_id, counterparty_node_id, state) in affected_channels {
2909                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2910                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2911                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2912                                                 update_maps_on_chan_removal!(self, &chan.context());
2913                                                 shutdown_results.push(chan.context_mut().force_shutdown(false, ClosureReason::FundingBatchClosure));
2914                                         }
2915                                 }
2916                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2917                         }
2918                         debug_assert!(
2919                                 has_uncompleted_channel.unwrap_or(true),
2920                                 "Closing a batch where all channels have completed initial monitor update",
2921                         );
2922                 }
2923
2924                 {
2925                         let mut pending_events = self.pending_events.lock().unwrap();
2926                         pending_events.push_back((events::Event::ChannelClosed {
2927                                 channel_id: shutdown_res.channel_id,
2928                                 user_channel_id: shutdown_res.user_channel_id,
2929                                 reason: shutdown_res.closure_reason,
2930                                 counterparty_node_id: Some(shutdown_res.counterparty_node_id),
2931                                 channel_capacity_sats: Some(shutdown_res.channel_capacity_satoshis),
2932                                 channel_funding_txo: shutdown_res.channel_funding_txo,
2933                         }, None));
2934
2935                         if let Some(transaction) = shutdown_res.unbroadcasted_funding_tx {
2936                                 pending_events.push_back((events::Event::DiscardFunding {
2937                                         channel_id: shutdown_res.channel_id, transaction
2938                                 }, None));
2939                         }
2940                 }
2941                 for shutdown_result in shutdown_results.drain(..) {
2942                         self.finish_close_channel(shutdown_result);
2943                 }
2944         }
2945
2946         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2947         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2948         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2949         -> Result<PublicKey, APIError> {
2950                 let per_peer_state = self.per_peer_state.read().unwrap();
2951                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2952                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2953                 let (update_opt, counterparty_node_id) = {
2954                         let mut peer_state = peer_state_mutex.lock().unwrap();
2955                         let closure_reason = if let Some(peer_msg) = peer_msg {
2956                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2957                         } else {
2958                                 ClosureReason::HolderForceClosed
2959                         };
2960                         let logger = WithContext::from(&self.logger, Some(*peer_node_id), Some(*channel_id));
2961                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2962                                 log_error!(logger, "Force-closing channel {}", channel_id);
2963                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2964                                 mem::drop(peer_state);
2965                                 mem::drop(per_peer_state);
2966                                 match chan_phase {
2967                                         ChannelPhase::Funded(mut chan) => {
2968                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast, closure_reason));
2969                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2970                                         },
2971                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2972                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false, closure_reason));
2973                                                 // Unfunded channel has no update
2974                                                 (None, chan_phase.context().get_counterparty_node_id())
2975                                         },
2976                                         // TODO(dual_funding): Combine this match arm with above once #[cfg(dual_funding)] is removed.
2977                                         #[cfg(dual_funding)]
2978                                         ChannelPhase::UnfundedOutboundV2(_) | ChannelPhase::UnfundedInboundV2(_) => {
2979                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false, closure_reason));
2980                                                 // Unfunded channel has no update
2981                                                 (None, chan_phase.context().get_counterparty_node_id())
2982                                         },
2983                                 }
2984                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2985                                 log_error!(logger, "Force-closing channel {}", &channel_id);
2986                                 // N.B. that we don't send any channel close event here: we
2987                                 // don't have a user_channel_id, and we never sent any opening
2988                                 // events anyway.
2989                                 (None, *peer_node_id)
2990                         } else {
2991                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2992                         }
2993                 };
2994                 if let Some(update) = update_opt {
2995                         // Try to send the `BroadcastChannelUpdate` to the peer we just force-closed on, but if
2996                         // not try to broadcast it via whatever peer we have.
2997                         let per_peer_state = self.per_peer_state.read().unwrap();
2998                         let a_peer_state_opt = per_peer_state.get(peer_node_id)
2999                                 .ok_or(per_peer_state.values().next());
3000                         if let Ok(a_peer_state_mutex) = a_peer_state_opt {
3001                                 let mut a_peer_state = a_peer_state_mutex.lock().unwrap();
3002                                 a_peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
3003                                         msg: update
3004                                 });
3005                         }
3006                 }
3007
3008                 Ok(counterparty_node_id)
3009         }
3010
3011         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
3012                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3013                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
3014                         Ok(counterparty_node_id) => {
3015                                 let per_peer_state = self.per_peer_state.read().unwrap();
3016                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
3017                                         let mut peer_state = peer_state_mutex.lock().unwrap();
3018                                         peer_state.pending_msg_events.push(
3019                                                 events::MessageSendEvent::HandleError {
3020                                                         node_id: counterparty_node_id,
3021                                                         action: msgs::ErrorAction::DisconnectPeer {
3022                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
3023                                                         },
3024                                                 }
3025                                         );
3026                                 }
3027                                 Ok(())
3028                         },
3029                         Err(e) => Err(e)
3030                 }
3031         }
3032
3033         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
3034         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
3035         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
3036         /// channel.
3037         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
3038         -> Result<(), APIError> {
3039                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
3040         }
3041
3042         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
3043         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
3044         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
3045         ///
3046         /// You can always broadcast the latest local transaction(s) via
3047         /// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
3048         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
3049         -> Result<(), APIError> {
3050                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
3051         }
3052
3053         /// Force close all channels, immediately broadcasting the latest local commitment transaction
3054         /// for each to the chain and rejecting new HTLCs on each.
3055         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
3056                 for chan in self.list_channels() {
3057                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
3058                 }
3059         }
3060
3061         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
3062         /// local transaction(s).
3063         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
3064                 for chan in self.list_channels() {
3065                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
3066                 }
3067         }
3068
3069         fn decode_update_add_htlc_onion(
3070                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey,
3071         ) -> Result<
3072                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
3073         > {
3074                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
3075                         msg, &self.node_signer, &self.logger, &self.secp_ctx
3076                 )?;
3077
3078                 let is_intro_node_forward = match next_hop {
3079                         onion_utils::Hop::Forward {
3080                                 next_hop_data: msgs::InboundOnionPayload::BlindedForward {
3081                                         intro_node_blinding_point: Some(_), ..
3082                                 }, ..
3083                         } => true,
3084                         _ => false,
3085                 };
3086
3087                 macro_rules! return_err {
3088                         ($msg: expr, $err_code: expr, $data: expr) => {
3089                                 {
3090                                         log_info!(
3091                                                 WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id)),
3092                                                 "Failed to accept/forward incoming HTLC: {}", $msg
3093                                         );
3094                                         // If `msg.blinding_point` is set, we must always fail with malformed.
3095                                         if msg.blinding_point.is_some() {
3096                                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3097                                                         channel_id: msg.channel_id,
3098                                                         htlc_id: msg.htlc_id,
3099                                                         sha256_of_onion: [0; 32],
3100                                                         failure_code: INVALID_ONION_BLINDING,
3101                                                 }));
3102                                         }
3103
3104                                         let (err_code, err_data) = if is_intro_node_forward {
3105                                                 (INVALID_ONION_BLINDING, &[0; 32][..])
3106                                         } else { ($err_code, $data) };
3107                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3108                                                 channel_id: msg.channel_id,
3109                                                 htlc_id: msg.htlc_id,
3110                                                 reason: HTLCFailReason::reason(err_code, err_data.to_vec())
3111                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3112                                         }));
3113                                 }
3114                         }
3115                 }
3116
3117                 let NextPacketDetails {
3118                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
3119                 } = match next_packet_details_opt {
3120                         Some(next_packet_details) => next_packet_details,
3121                         // it is a receive, so no need for outbound checks
3122                         None => return Ok((next_hop, shared_secret, None)),
3123                 };
3124
3125                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3126                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3127                 if let Some((err, mut code, chan_update)) = loop {
3128                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3129                         let forwarding_chan_info_opt = match id_option {
3130                                 None => { // unknown_next_peer
3131                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3132                                         // phantom or an intercept.
3133                                         if (self.default_configuration.accept_intercept_htlcs &&
3134                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3135                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3136                                         {
3137                                                 None
3138                                         } else {
3139                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3140                                         }
3141                                 },
3142                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3143                         };
3144                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3145                                 let per_peer_state = self.per_peer_state.read().unwrap();
3146                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3147                                 if peer_state_mutex_opt.is_none() {
3148                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3149                                 }
3150                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3151                                 let peer_state = &mut *peer_state_lock;
3152                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3153                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3154                                 ).flatten() {
3155                                         None => {
3156                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3157                                                 // have no consistency guarantees.
3158                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3159                                         },
3160                                         Some(chan) => chan
3161                                 };
3162                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3163                                         // Note that the behavior here should be identical to the above block - we
3164                                         // should NOT reveal the existence or non-existence of a private channel if
3165                                         // we don't allow forwards outbound over them.
3166                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3167                                 }
3168                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3169                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3170                                         // "refuse to forward unless the SCID alias was used", so we pretend
3171                                         // we don't have the channel here.
3172                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3173                                 }
3174                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3175
3176                                 // Note that we could technically not return an error yet here and just hope
3177                                 // that the connection is reestablished or monitor updated by the time we get
3178                                 // around to doing the actual forward, but better to fail early if we can and
3179                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3180                                 // on a small/per-node/per-channel scale.
3181                                 if !chan.context.is_live() { // channel_disabled
3182                                         // If the channel_update we're going to return is disabled (i.e. the
3183                                         // peer has been disabled for some time), return `channel_disabled`,
3184                                         // otherwise return `temporary_channel_failure`.
3185                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3186                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3187                                         } else {
3188                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3189                                         }
3190                                 }
3191                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3192                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3193                                 }
3194                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3195                                         break Some((err, code, chan_update_opt));
3196                                 }
3197                                 chan_update_opt
3198                         } else {
3199                                 None
3200                         };
3201
3202                         let cur_height = self.best_block.read().unwrap().height() + 1;
3203
3204                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3205                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3206                         ) {
3207                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3208                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3209                                         // forwarding over a real channel we can't generate a channel_update
3210                                         // for it. Instead we just return a generic temporary_node_failure.
3211                                         break Some((err_msg, 0x2000 | 2, None))
3212                                 }
3213                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3214                                 break Some((err_msg, code, chan_update_opt));
3215                         }
3216
3217                         break None;
3218                 }
3219                 {
3220                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3221                         if let Some(chan_update) = chan_update {
3222                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3223                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3224                                 }
3225                                 else if code == 0x1000 | 13 {
3226                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3227                                 }
3228                                 else if code == 0x1000 | 20 {
3229                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3230                                         0u16.write(&mut res).expect("Writes cannot fail");
3231                                 }
3232                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3233                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3234                                 chan_update.write(&mut res).expect("Writes cannot fail");
3235                         } else if code & 0x1000 == 0x1000 {
3236                                 // If we're trying to return an error that requires a `channel_update` but
3237                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3238                                 // generate an update), just use the generic "temporary_node_failure"
3239                                 // instead.
3240                                 code = 0x2000 | 2;
3241                         }
3242                         return_err!(err, code, &res.0[..]);
3243                 }
3244                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3245         }
3246
3247         fn construct_pending_htlc_status<'a>(
3248                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, shared_secret: [u8; 32],
3249                 decoded_hop: onion_utils::Hop, allow_underpay: bool,
3250                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>,
3251         ) -> PendingHTLCStatus {
3252                 macro_rules! return_err {
3253                         ($msg: expr, $err_code: expr, $data: expr) => {
3254                                 {
3255                                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
3256                                         log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3257                                         if msg.blinding_point.is_some() {
3258                                                 return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
3259                                                         msgs::UpdateFailMalformedHTLC {
3260                                                                 channel_id: msg.channel_id,
3261                                                                 htlc_id: msg.htlc_id,
3262                                                                 sha256_of_onion: [0; 32],
3263                                                                 failure_code: INVALID_ONION_BLINDING,
3264                                                         }
3265                                                 ))
3266                                         }
3267                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3268                                                 channel_id: msg.channel_id,
3269                                                 htlc_id: msg.htlc_id,
3270                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3271                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3272                                         }));
3273                                 }
3274                         }
3275                 }
3276                 match decoded_hop {
3277                         onion_utils::Hop::Receive(next_hop_data) => {
3278                                 // OUR PAYMENT!
3279                                 let current_height: u32 = self.best_block.read().unwrap().height();
3280                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3281                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3282                                         current_height, self.default_configuration.accept_mpp_keysend)
3283                                 {
3284                                         Ok(info) => {
3285                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3286                                                 // message, however that would leak that we are the recipient of this payment, so
3287                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3288                                                 // delay) once they've send us a commitment_signed!
3289                                                 PendingHTLCStatus::Forward(info)
3290                                         },
3291                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3292                                 }
3293                         },
3294                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3295                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3296                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3297                                         Ok(info) => PendingHTLCStatus::Forward(info),
3298                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3299                                 }
3300                         }
3301                 }
3302         }
3303
3304         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3305         /// public, and thus should be called whenever the result is going to be passed out in a
3306         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3307         ///
3308         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3309         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3310         /// storage and the `peer_state` lock has been dropped.
3311         ///
3312         /// [`channel_update`]: msgs::ChannelUpdate
3313         /// [`internal_closing_signed`]: Self::internal_closing_signed
3314         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3315                 if !chan.context.should_announce() {
3316                         return Err(LightningError {
3317                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3318                                 action: msgs::ErrorAction::IgnoreError
3319                         });
3320                 }
3321                 if chan.context.get_short_channel_id().is_none() {
3322                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3323                 }
3324                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3325                 log_trace!(logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3326                 self.get_channel_update_for_unicast(chan)
3327         }
3328
3329         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3330         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3331         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3332         /// provided evidence that they know about the existence of the channel.
3333         ///
3334         /// Note that through [`internal_closing_signed`], this function is called without the
3335         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3336         /// removed from the storage and the `peer_state` lock has been dropped.
3337         ///
3338         /// [`channel_update`]: msgs::ChannelUpdate
3339         /// [`internal_closing_signed`]: Self::internal_closing_signed
3340         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3341                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3342                 log_trace!(logger, "Attempting to generate channel update for channel {}", chan.context.channel_id());
3343                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3344                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3345                         Some(id) => id,
3346                 };
3347
3348                 self.get_channel_update_for_onion(short_channel_id, chan)
3349         }
3350
3351         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3352                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3353                 log_trace!(logger, "Generating channel update for channel {}", chan.context.channel_id());
3354                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3355
3356                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3357                         ChannelUpdateStatus::Enabled => true,
3358                         ChannelUpdateStatus::DisabledStaged(_) => true,
3359                         ChannelUpdateStatus::Disabled => false,
3360                         ChannelUpdateStatus::EnabledStaged(_) => false,
3361                 };
3362
3363                 let unsigned = msgs::UnsignedChannelUpdate {
3364                         chain_hash: self.chain_hash,
3365                         short_channel_id,
3366                         timestamp: chan.context.get_update_time_counter(),
3367                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3368                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3369                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3370                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3371                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3372                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3373                         excess_data: Vec::new(),
3374                 };
3375                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3376                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3377                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3378                 // channel.
3379                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3380
3381                 Ok(msgs::ChannelUpdate {
3382                         signature: sig,
3383                         contents: unsigned
3384                 })
3385         }
3386
3387         #[cfg(test)]
3388         pub(crate) fn test_send_payment_along_path(&self, path: &Path, payment_hash: &PaymentHash, recipient_onion: RecipientOnionFields, total_value: u64, cur_height: u32, payment_id: PaymentId, keysend_preimage: &Option<PaymentPreimage>, session_priv_bytes: [u8; 32]) -> Result<(), APIError> {
3389                 let _lck = self.total_consistency_lock.read().unwrap();
3390                 self.send_payment_along_path(SendAlongPathArgs {
3391                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3392                         session_priv_bytes
3393                 })
3394         }
3395
3396         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3397                 let SendAlongPathArgs {
3398                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3399                         session_priv_bytes
3400                 } = args;
3401                 // The top-level caller should hold the total_consistency_lock read lock.
3402                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3403                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3404                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3405
3406                 let (onion_packet, htlc_msat, htlc_cltv) = onion_utils::create_payment_onion(
3407                         &self.secp_ctx, &path, &session_priv, total_value, recipient_onion, cur_height,
3408                         payment_hash, keysend_preimage, prng_seed
3409                 ).map_err(|e| {
3410                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3411                         log_error!(logger, "Failed to build an onion for path for payment hash {}", payment_hash);
3412                         e
3413                 })?;
3414
3415                 let err: Result<(), _> = loop {
3416                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3417                                 None => {
3418                                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3419                                         log_error!(logger, "Failed to find first-hop for payment hash {}", payment_hash);
3420                                         return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()})
3421                                 },
3422                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3423                         };
3424
3425                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(id));
3426                         log_trace!(logger,
3427                                 "Attempting to send payment with payment hash {} along path with next hop {}",
3428                                 payment_hash, path.hops.first().unwrap().short_channel_id);
3429
3430                         let per_peer_state = self.per_peer_state.read().unwrap();
3431                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3432                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3433                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3434                         let peer_state = &mut *peer_state_lock;
3435                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3436                                 match chan_phase_entry.get_mut() {
3437                                         ChannelPhase::Funded(chan) => {
3438                                                 if !chan.context.is_live() {
3439                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3440                                                 }
3441                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3442                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3443                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3444                                                         htlc_cltv, HTLCSource::OutboundRoute {
3445                                                                 path: path.clone(),
3446                                                                 session_priv: session_priv.clone(),
3447                                                                 first_hop_htlc_msat: htlc_msat,
3448                                                                 payment_id,
3449                                                         }, onion_packet, None, &self.fee_estimator, &&logger);
3450                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3451                                                         Some(monitor_update) => {
3452                                                                 match handle_new_monitor_update!(self, funding_txo, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3453                                                                         false => {
3454                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3455                                                                                 // docs) that we will resend the commitment update once monitor
3456                                                                                 // updating completes. Therefore, we must return an error
3457                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3458                                                                                 // which we do in the send_payment check for
3459                                                                                 // MonitorUpdateInProgress, below.
3460                                                                                 return Err(APIError::MonitorUpdateInProgress);
3461                                                                         },
3462                                                                         true => {},
3463                                                                 }
3464                                                         },
3465                                                         None => {},
3466                                                 }
3467                                         },
3468                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3469                                 };
3470                         } else {
3471                                 // The channel was likely removed after we fetched the id from the
3472                                 // `short_to_chan_info` map, but before we successfully locked the
3473                                 // `channel_by_id` map.
3474                                 // This can occur as no consistency guarantees exists between the two maps.
3475                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3476                         }
3477                         return Ok(());
3478                 };
3479                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3480                         Ok(_) => unreachable!(),
3481                         Err(e) => {
3482                                 Err(APIError::ChannelUnavailable { err: e.err })
3483                         },
3484                 }
3485         }
3486
3487         /// Sends a payment along a given route.
3488         ///
3489         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3490         /// fields for more info.
3491         ///
3492         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3493         /// [`PeerManager::process_events`]).
3494         ///
3495         /// # Avoiding Duplicate Payments
3496         ///
3497         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3498         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3499         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3500         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3501         /// second payment with the same [`PaymentId`].
3502         ///
3503         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3504         /// tracking of payments, including state to indicate once a payment has completed. Because you
3505         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3506         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3507         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3508         ///
3509         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3510         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3511         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3512         /// [`ChannelManager::list_recent_payments`] for more information.
3513         ///
3514         /// # Possible Error States on [`PaymentSendFailure`]
3515         ///
3516         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3517         /// each entry matching the corresponding-index entry in the route paths, see
3518         /// [`PaymentSendFailure`] for more info.
3519         ///
3520         /// In general, a path may raise:
3521         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3522         ///    node public key) is specified.
3523         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3524         ///    closed, doesn't exist, or the peer is currently disconnected.
3525         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3526         ///    relevant updates.
3527         ///
3528         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3529         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3530         /// different route unless you intend to pay twice!
3531         ///
3532         /// [`RouteHop`]: crate::routing::router::RouteHop
3533         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3534         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3535         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3536         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3537         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3538         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3539                 let best_block_height = self.best_block.read().unwrap().height();
3540                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3541                 self.pending_outbound_payments
3542                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3543                                 &self.entropy_source, &self.node_signer, best_block_height,
3544                                 |args| self.send_payment_along_path(args))
3545         }
3546
3547         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3548         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3549         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3550                 let best_block_height = self.best_block.read().unwrap().height();
3551                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3552                 self.pending_outbound_payments
3553                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3554                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3555                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3556                                 &self.pending_events, |args| self.send_payment_along_path(args))
3557         }
3558
3559         #[cfg(test)]
3560         pub(super) fn test_send_payment_internal(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: Vec<[u8; 32]>) -> Result<(), PaymentSendFailure> {
3561                 let best_block_height = self.best_block.read().unwrap().height();
3562                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3563                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3564                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3565                         best_block_height, |args| self.send_payment_along_path(args))
3566         }
3567
3568         #[cfg(test)]
3569         pub(crate) fn test_add_new_pending_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route: &Route) -> Result<Vec<[u8; 32]>, PaymentSendFailure> {
3570                 let best_block_height = self.best_block.read().unwrap().height();
3571                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3572         }
3573
3574         #[cfg(test)]
3575         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3576                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3577         }
3578
3579         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3580                 let best_block_height = self.best_block.read().unwrap().height();
3581                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3582                 self.pending_outbound_payments
3583                         .send_payment_for_bolt12_invoice(
3584                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3585                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3586                                 best_block_height, &self.logger, &self.pending_events,
3587                                 |args| self.send_payment_along_path(args)
3588                         )
3589         }
3590
3591         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3592         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3593         /// retries are exhausted.
3594         ///
3595         /// # Event Generation
3596         ///
3597         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3598         /// as there are no remaining pending HTLCs for this payment.
3599         ///
3600         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3601         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3602         /// determine the ultimate status of a payment.
3603         ///
3604         /// # Requested Invoices
3605         ///
3606         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3607         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3608         /// and prevent any attempts at paying it once received. The other events may only be generated
3609         /// once the invoice has been received.
3610         ///
3611         /// # Restart Behavior
3612         ///
3613         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3614         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3615         /// [`Event::InvoiceRequestFailed`].
3616         ///
3617         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3618         pub fn abandon_payment(&self, payment_id: PaymentId) {
3619                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3620                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3621         }
3622
3623         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3624         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3625         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3626         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3627         /// never reach the recipient.
3628         ///
3629         /// See [`send_payment`] documentation for more details on the return value of this function
3630         /// and idempotency guarantees provided by the [`PaymentId`] key.
3631         ///
3632         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3633         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3634         ///
3635         /// [`send_payment`]: Self::send_payment
3636         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3637                 let best_block_height = self.best_block.read().unwrap().height();
3638                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3639                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3640                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3641                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3642         }
3643
3644         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3645         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3646         ///
3647         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3648         /// payments.
3649         ///
3650         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3651         pub fn send_spontaneous_payment_with_retry(&self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<PaymentHash, RetryableSendFailure> {
3652                 let best_block_height = self.best_block.read().unwrap().height();
3653                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3654                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3655                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3656                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3657                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3658         }
3659
3660         /// Send a payment that is probing the given route for liquidity. We calculate the
3661         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3662         /// us to easily discern them from real payments.
3663         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3664                 let best_block_height = self.best_block.read().unwrap().height();
3665                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3666                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3667                         &self.entropy_source, &self.node_signer, best_block_height,
3668                         |args| self.send_payment_along_path(args))
3669         }
3670
3671         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3672         /// payment probe.
3673         #[cfg(test)]
3674         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3675                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3676         }
3677
3678         /// Sends payment probes over all paths of a route that would be used to pay the given
3679         /// amount to the given `node_id`.
3680         ///
3681         /// See [`ChannelManager::send_preflight_probes`] for more information.
3682         pub fn send_spontaneous_preflight_probes(
3683                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3684                 liquidity_limit_multiplier: Option<u64>,
3685         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3686                 let payment_params =
3687                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3688
3689                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3690
3691                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3692         }
3693
3694         /// Sends payment probes over all paths of a route that would be used to pay a route found
3695         /// according to the given [`RouteParameters`].
3696         ///
3697         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3698         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3699         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3700         /// confirmation in a wallet UI.
3701         ///
3702         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3703         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3704         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3705         /// payment. To mitigate this issue, channels with available liquidity less than the required
3706         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3707         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3708         pub fn send_preflight_probes(
3709                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3710         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3711                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3712
3713                 let payer = self.get_our_node_id();
3714                 let usable_channels = self.list_usable_channels();
3715                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3716                 let inflight_htlcs = self.compute_inflight_htlcs();
3717
3718                 let route = self
3719                         .router
3720                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3721                         .map_err(|e| {
3722                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3723                                 ProbeSendFailure::RouteNotFound
3724                         })?;
3725
3726                 let mut used_liquidity_map = hash_map_with_capacity(first_hops.len());
3727
3728                 let mut res = Vec::new();
3729
3730                 for mut path in route.paths {
3731                         // If the last hop is probably an unannounced channel we refrain from probing all the
3732                         // way through to the end and instead probe up to the second-to-last channel.
3733                         while let Some(last_path_hop) = path.hops.last() {
3734                                 if last_path_hop.maybe_announced_channel {
3735                                         // We found a potentially announced last hop.
3736                                         break;
3737                                 } else {
3738                                         // Drop the last hop, as it's likely unannounced.
3739                                         log_debug!(
3740                                                 self.logger,
3741                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3742                                                 last_path_hop.short_channel_id
3743                                         );
3744                                         let final_value_msat = path.final_value_msat();
3745                                         path.hops.pop();
3746                                         if let Some(new_last) = path.hops.last_mut() {
3747                                                 new_last.fee_msat += final_value_msat;
3748                                         }
3749                                 }
3750                         }
3751
3752                         if path.hops.len() < 2 {
3753                                 log_debug!(
3754                                         self.logger,
3755                                         "Skipped sending payment probe over path with less than two hops."
3756                                 );
3757                                 continue;
3758                         }
3759
3760                         if let Some(first_path_hop) = path.hops.first() {
3761                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3762                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3763                                 }) {
3764                                         let path_value = path.final_value_msat() + path.fee_msat();
3765                                         let used_liquidity =
3766                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3767
3768                                         if first_hop.next_outbound_htlc_limit_msat
3769                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3770                                         {
3771                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3772                                                 continue;
3773                                         } else {
3774                                                 *used_liquidity += path_value;
3775                                         }
3776                                 }
3777                         }
3778
3779                         res.push(self.send_probe(path).map_err(|e| {
3780                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3781                                 ProbeSendFailure::SendingFailed(e)
3782                         })?);
3783                 }
3784
3785                 Ok(res)
3786         }
3787
3788         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3789         /// which checks the correctness of the funding transaction given the associated channel.
3790         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3791                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3792                 mut find_funding_output: FundingOutput,
3793         ) -> Result<(), APIError> {
3794                 let per_peer_state = self.per_peer_state.read().unwrap();
3795                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3796                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3797
3798                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3799                 let peer_state = &mut *peer_state_lock;
3800                 let funding_txo;
3801                 let (mut chan, msg_opt) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3802                         Some(ChannelPhase::UnfundedOutboundV1(mut chan)) => {
3803                                 funding_txo = find_funding_output(&chan, &funding_transaction)?;
3804
3805                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3806                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &&logger)
3807                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3808                                                 let channel_id = chan.context.channel_id();
3809                                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
3810                                                 let shutdown_res = chan.context.force_shutdown(false, reason);
3811                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, None))
3812                                         } else { unreachable!(); });
3813                                 match funding_res {
3814                                         Ok(funding_msg) => (chan, funding_msg),
3815                                         Err((chan, err)) => {
3816                                                 mem::drop(peer_state_lock);
3817                                                 mem::drop(per_peer_state);
3818                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3819                                                 return Err(APIError::ChannelUnavailable {
3820                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3821                                                 });
3822                                         },
3823                                 }
3824                         },
3825                         Some(phase) => {
3826                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3827                                 return Err(APIError::APIMisuseError {
3828                                         err: format!(
3829                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3830                                                 temporary_channel_id, counterparty_node_id),
3831                                 })
3832                         },
3833                         None => return Err(APIError::ChannelUnavailable {err: format!(
3834                                 "Channel with id {} not found for the passed counterparty node_id {}",
3835                                 temporary_channel_id, counterparty_node_id),
3836                                 }),
3837                 };
3838
3839                 if let Some(msg) = msg_opt {
3840                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3841                                 node_id: chan.context.get_counterparty_node_id(),
3842                                 msg,
3843                         });
3844                 }
3845                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3846                         hash_map::Entry::Occupied(_) => {
3847                                 panic!("Generated duplicate funding txid?");
3848                         },
3849                         hash_map::Entry::Vacant(e) => {
3850                                 let mut outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
3851                                 match outpoint_to_peer.entry(funding_txo) {
3852                                         hash_map::Entry::Vacant(e) => { e.insert(chan.context.get_counterparty_node_id()); },
3853                                         hash_map::Entry::Occupied(o) => {
3854                                                 let err = format!(
3855                                                         "An existing channel using outpoint {} is open with peer {}",
3856                                                         funding_txo, o.get()
3857                                                 );
3858                                                 mem::drop(outpoint_to_peer);
3859                                                 mem::drop(peer_state_lock);
3860                                                 mem::drop(per_peer_state);
3861                                                 let reason = ClosureReason::ProcessingError { err: err.clone() };
3862                                                 self.finish_close_channel(chan.context.force_shutdown(true, reason));
3863                                                 return Err(APIError::ChannelUnavailable { err });
3864                                         }
3865                                 }
3866                                 e.insert(ChannelPhase::UnfundedOutboundV1(chan));
3867                         }
3868                 }
3869                 Ok(())
3870         }
3871
3872         #[cfg(test)]
3873         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3874                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3875                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3876                 })
3877         }
3878
3879         /// Call this upon creation of a funding transaction for the given channel.
3880         ///
3881         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3882         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3883         ///
3884         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3885         /// across the p2p network.
3886         ///
3887         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3888         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3889         ///
3890         /// May panic if the output found in the funding transaction is duplicative with some other
3891         /// channel (note that this should be trivially prevented by using unique funding transaction
3892         /// keys per-channel).
3893         ///
3894         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3895         /// counterparty's signature the funding transaction will automatically be broadcast via the
3896         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3897         ///
3898         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3899         /// not currently support replacing a funding transaction on an existing channel. Instead,
3900         /// create a new channel with a conflicting funding transaction.
3901         ///
3902         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3903         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3904         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3905         /// for more details.
3906         ///
3907         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3908         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3909         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3910                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3911         }
3912
3913         /// Call this upon creation of a batch funding transaction for the given channels.
3914         ///
3915         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3916         /// each individual channel and transaction output.
3917         ///
3918         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3919         /// will only be broadcast when we have safely received and persisted the counterparty's
3920         /// signature for each channel.
3921         ///
3922         /// If there is an error, all channels in the batch are to be considered closed.
3923         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3924                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3925                 let mut result = Ok(());
3926
3927                 if !funding_transaction.is_coin_base() {
3928                         for inp in funding_transaction.input.iter() {
3929                                 if inp.witness.is_empty() {
3930                                         result = result.and(Err(APIError::APIMisuseError {
3931                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3932                                         }));
3933                                 }
3934                         }
3935                 }
3936                 if funding_transaction.output.len() > u16::max_value() as usize {
3937                         result = result.and(Err(APIError::APIMisuseError {
3938                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3939                         }));
3940                 }
3941                 {
3942                         let height = self.best_block.read().unwrap().height();
3943                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3944                         // lower than the next block height. However, the modules constituting our Lightning
3945                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3946                         // module is ahead of LDK, only allow one more block of headroom.
3947                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) &&
3948                                 funding_transaction.lock_time.is_block_height() &&
3949                                 funding_transaction.lock_time.to_consensus_u32() > height + 1
3950                         {
3951                                 result = result.and(Err(APIError::APIMisuseError {
3952                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3953                                 }));
3954                         }
3955                 }
3956
3957                 let txid = funding_transaction.txid();
3958                 let is_batch_funding = temporary_channels.len() > 1;
3959                 let mut funding_batch_states = if is_batch_funding {
3960                         Some(self.funding_batch_states.lock().unwrap())
3961                 } else {
3962                         None
3963                 };
3964                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3965                         match states.entry(txid) {
3966                                 btree_map::Entry::Occupied(_) => {
3967                                         result = result.clone().and(Err(APIError::APIMisuseError {
3968                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3969                                         }));
3970                                         None
3971                                 },
3972                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3973                         }
3974                 });
3975                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3976                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3977                                 temporary_channel_id,
3978                                 counterparty_node_id,
3979                                 funding_transaction.clone(),
3980                                 is_batch_funding,
3981                                 |chan, tx| {
3982                                         let mut output_index = None;
3983                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3984                                         for (idx, outp) in tx.output.iter().enumerate() {
3985                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3986                                                         if output_index.is_some() {
3987                                                                 return Err(APIError::APIMisuseError {
3988                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3989                                                                 });
3990                                                         }
3991                                                         output_index = Some(idx as u16);
3992                                                 }
3993                                         }
3994                                         if output_index.is_none() {
3995                                                 return Err(APIError::APIMisuseError {
3996                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3997                                                 });
3998                                         }
3999                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
4000                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
4001                                                 // TODO(dual_funding): We only do batch funding for V1 channels at the moment, but we'll probably
4002                                                 // need to fix this somehow to not rely on using the outpoint for the channel ID if we
4003                                                 // want to support V2 batching here as well.
4004                                                 funding_batch_state.push((ChannelId::v1_from_funding_outpoint(outpoint), *counterparty_node_id, false));
4005                                         }
4006                                         Ok(outpoint)
4007                                 })
4008                         );
4009                 }
4010                 if let Err(ref e) = result {
4011                         // Remaining channels need to be removed on any error.
4012                         let e = format!("Error in transaction funding: {:?}", e);
4013                         let mut channels_to_remove = Vec::new();
4014                         channels_to_remove.extend(funding_batch_states.as_mut()
4015                                 .and_then(|states| states.remove(&txid))
4016                                 .into_iter().flatten()
4017                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
4018                         );
4019                         channels_to_remove.extend(temporary_channels.iter()
4020                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
4021                         );
4022                         let mut shutdown_results = Vec::new();
4023                         {
4024                                 let per_peer_state = self.per_peer_state.read().unwrap();
4025                                 for (channel_id, counterparty_node_id) in channels_to_remove {
4026                                         per_peer_state.get(&counterparty_node_id)
4027                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
4028                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
4029                                                 .map(|mut chan| {
4030                                                         update_maps_on_chan_removal!(self, &chan.context());
4031                                                         let closure_reason = ClosureReason::ProcessingError { err: e.clone() };
4032                                                         shutdown_results.push(chan.context_mut().force_shutdown(false, closure_reason));
4033                                                 });
4034                                 }
4035                         }
4036                         mem::drop(funding_batch_states);
4037                         for shutdown_result in shutdown_results.drain(..) {
4038                                 self.finish_close_channel(shutdown_result);
4039                         }
4040                 }
4041                 result
4042         }
4043
4044         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
4045         ///
4046         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4047         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4048         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4049         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4050         ///
4051         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4052         /// `counterparty_node_id` is provided.
4053         ///
4054         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4055         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4056         ///
4057         /// If an error is returned, none of the updates should be considered applied.
4058         ///
4059         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4060         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4061         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4062         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4063         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4064         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4065         /// [`APIMisuseError`]: APIError::APIMisuseError
4066         pub fn update_partial_channel_config(
4067                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4068         ) -> Result<(), APIError> {
4069                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4070                         return Err(APIError::APIMisuseError {
4071                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4072                         });
4073                 }
4074
4075                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4076                 let per_peer_state = self.per_peer_state.read().unwrap();
4077                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4078                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4079                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4080                 let peer_state = &mut *peer_state_lock;
4081                 for channel_id in channel_ids {
4082                         if !peer_state.has_channel(channel_id) {
4083                                 return Err(APIError::ChannelUnavailable {
4084                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4085                                 });
4086                         };
4087                 }
4088                 for channel_id in channel_ids {
4089                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4090                                 let mut config = channel_phase.context().config();
4091                                 config.apply(config_update);
4092                                 if !channel_phase.context_mut().update_config(&config) {
4093                                         continue;
4094                                 }
4095                                 if let ChannelPhase::Funded(channel) = channel_phase {
4096                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4097                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4098                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4099                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4100                                                         node_id: channel.context.get_counterparty_node_id(),
4101                                                         msg,
4102                                                 });
4103                                         }
4104                                 }
4105                                 continue;
4106                         } else {
4107                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4108                                 debug_assert!(false);
4109                                 return Err(APIError::ChannelUnavailable {
4110                                         err: format!(
4111                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4112                                                 channel_id, counterparty_node_id),
4113                                 });
4114                         };
4115                 }
4116                 Ok(())
4117         }
4118
4119         /// Atomically updates the [`ChannelConfig`] for the given channels.
4120         ///
4121         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4122         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4123         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4124         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4125         ///
4126         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4127         /// `counterparty_node_id` is provided.
4128         ///
4129         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4130         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4131         ///
4132         /// If an error is returned, none of the updates should be considered applied.
4133         ///
4134         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4135         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4136         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4137         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4138         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4139         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4140         /// [`APIMisuseError`]: APIError::APIMisuseError
4141         pub fn update_channel_config(
4142                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4143         ) -> Result<(), APIError> {
4144                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4145         }
4146
4147         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4148         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4149         ///
4150         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4151         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4152         ///
4153         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4154         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4155         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4156         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4157         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4158         ///
4159         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4160         /// you from forwarding more than you received. See
4161         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4162         /// than expected.
4163         ///
4164         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4165         /// backwards.
4166         ///
4167         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4168         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4169         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4170         // TODO: when we move to deciding the best outbound channel at forward time, only take
4171         // `next_node_id` and not `next_hop_channel_id`
4172         pub fn forward_intercepted_htlc(&self, intercept_id: InterceptId, next_hop_channel_id: &ChannelId, next_node_id: PublicKey, amt_to_forward_msat: u64) -> Result<(), APIError> {
4173                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4174
4175                 let next_hop_scid = {
4176                         let peer_state_lock = self.per_peer_state.read().unwrap();
4177                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4178                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4179                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4180                         let peer_state = &mut *peer_state_lock;
4181                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4182                                 Some(ChannelPhase::Funded(chan)) => {
4183                                         if !chan.context.is_usable() {
4184                                                 return Err(APIError::ChannelUnavailable {
4185                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4186                                                 })
4187                                         }
4188                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4189                                 },
4190                                 Some(_) => return Err(APIError::ChannelUnavailable {
4191                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4192                                                 next_hop_channel_id, next_node_id)
4193                                 }),
4194                                 None => {
4195                                         let error = format!("Channel with id {} not found for the passed counterparty node_id {}",
4196                                                 next_hop_channel_id, next_node_id);
4197                                         let logger = WithContext::from(&self.logger, Some(next_node_id), Some(*next_hop_channel_id));
4198                                         log_error!(logger, "{} when attempting to forward intercepted HTLC", error);
4199                                         return Err(APIError::ChannelUnavailable {
4200                                                 err: error
4201                                         })
4202                                 }
4203                         }
4204                 };
4205
4206                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4207                         .ok_or_else(|| APIError::APIMisuseError {
4208                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4209                         })?;
4210
4211                 let routing = match payment.forward_info.routing {
4212                         PendingHTLCRouting::Forward { onion_packet, blinded, .. } => {
4213                                 PendingHTLCRouting::Forward {
4214                                         onion_packet, blinded, short_channel_id: next_hop_scid
4215                                 }
4216                         },
4217                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4218                 };
4219                 let skimmed_fee_msat =
4220                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4221                 let pending_htlc_info = PendingHTLCInfo {
4222                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4223                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4224                 };
4225
4226                 let mut per_source_pending_forward = [(
4227                         payment.prev_short_channel_id,
4228                         payment.prev_funding_outpoint,
4229                         payment.prev_channel_id,
4230                         payment.prev_user_channel_id,
4231                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4232                 )];
4233                 self.forward_htlcs(&mut per_source_pending_forward);
4234                 Ok(())
4235         }
4236
4237         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4238         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4239         ///
4240         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4241         /// backwards.
4242         ///
4243         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4244         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4245                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4246
4247                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4248                         .ok_or_else(|| APIError::APIMisuseError {
4249                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4250                         })?;
4251
4252                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4253                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4254                                 short_channel_id: payment.prev_short_channel_id,
4255                                 user_channel_id: Some(payment.prev_user_channel_id),
4256                                 outpoint: payment.prev_funding_outpoint,
4257                                 channel_id: payment.prev_channel_id,
4258                                 htlc_id: payment.prev_htlc_id,
4259                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4260                                 phantom_shared_secret: None,
4261                                 blinded_failure: payment.forward_info.routing.blinded_failure(),
4262                         });
4263
4264                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4265                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4266                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4267                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4268
4269                 Ok(())
4270         }
4271
4272         /// Processes HTLCs which are pending waiting on random forward delay.
4273         ///
4274         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4275         /// Will likely generate further events.
4276         pub fn process_pending_htlc_forwards(&self) {
4277                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4278
4279                 let mut new_events = VecDeque::new();
4280                 let mut failed_forwards = Vec::new();
4281                 let mut phantom_receives: Vec<(u64, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4282                 {
4283                         let mut forward_htlcs = new_hash_map();
4284                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4285
4286                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4287                                 if short_chan_id != 0 {
4288                                         let mut forwarding_counterparty = None;
4289                                         macro_rules! forwarding_channel_not_found {
4290                                                 () => {
4291                                                         for forward_info in pending_forwards.drain(..) {
4292                                                                 match forward_info {
4293                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4294                                                                                 prev_short_channel_id, prev_htlc_id, prev_channel_id, prev_funding_outpoint,
4295                                                                                 prev_user_channel_id, forward_info: PendingHTLCInfo {
4296                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4297                                                                                         outgoing_cltv_value, ..
4298                                                                                 }
4299                                                                         }) => {
4300                                                                                 macro_rules! failure_handler {
4301                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4302                                                                                                 let logger = WithContext::from(&self.logger, forwarding_counterparty, Some(prev_channel_id));
4303                                                                                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4304
4305                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4306                                                                                                         short_channel_id: prev_short_channel_id,
4307                                                                                                         user_channel_id: Some(prev_user_channel_id),
4308                                                                                                         channel_id: prev_channel_id,
4309                                                                                                         outpoint: prev_funding_outpoint,
4310                                                                                                         htlc_id: prev_htlc_id,
4311                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4312                                                                                                         phantom_shared_secret: $phantom_ss,
4313                                                                                                         blinded_failure: routing.blinded_failure(),
4314                                                                                                 });
4315
4316                                                                                                 let reason = if $next_hop_unknown {
4317                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4318                                                                                                 } else {
4319                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4320                                                                                                 };
4321
4322                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4323                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4324                                                                                                         reason
4325                                                                                                 ));
4326                                                                                                 continue;
4327                                                                                         }
4328                                                                                 }
4329                                                                                 macro_rules! fail_forward {
4330                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4331                                                                                                 {
4332                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4333                                                                                                 }
4334                                                                                         }
4335                                                                                 }
4336                                                                                 macro_rules! failed_payment {
4337                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4338                                                                                                 {
4339                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4340                                                                                                 }
4341                                                                                         }
4342                                                                                 }
4343                                                                                 if let PendingHTLCRouting::Forward { ref onion_packet, .. } = routing {
4344                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4345                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4346                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4347                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4348                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4349                                                                                                         payment_hash, None, &self.node_signer
4350                                                                                                 ) {
4351                                                                                                         Ok(res) => res,
4352                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4353                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).to_byte_array();
4354                                                                                                                 // In this scenario, the phantom would have sent us an
4355                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4356                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4357                                                                                                                 // of the onion.
4358                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4359                                                                                                         },
4360                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4361                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4362                                                                                                         },
4363                                                                                                 };
4364                                                                                                 match next_hop {
4365                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4366                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4367                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4368                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4369                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4370                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4371                                                                                                                 {
4372                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4373                                                                                                                         Err(InboundHTLCErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4374                                                                                                                 }
4375                                                                                                         },
4376                                                                                                         _ => panic!(),
4377                                                                                                 }
4378                                                                                         } else {
4379                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4380                                                                                         }
4381                                                                                 } else {
4382                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4383                                                                                 }
4384                                                                         },
4385                                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4386                                                                                 // Channel went away before we could fail it. This implies
4387                                                                                 // the channel is now on chain and our counterparty is
4388                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4389                                                                                 // problem, not ours.
4390                                                                         }
4391                                                                 }
4392                                                         }
4393                                                 }
4394                                         }
4395                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4396                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4397                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4398                                                 None => {
4399                                                         forwarding_channel_not_found!();
4400                                                         continue;
4401                                                 }
4402                                         };
4403                                         forwarding_counterparty = Some(counterparty_node_id);
4404                                         let per_peer_state = self.per_peer_state.read().unwrap();
4405                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4406                                         if peer_state_mutex_opt.is_none() {
4407                                                 forwarding_channel_not_found!();
4408                                                 continue;
4409                                         }
4410                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4411                                         let peer_state = &mut *peer_state_lock;
4412                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4413                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4414                                                 for forward_info in pending_forwards.drain(..) {
4415                                                         let queue_fail_htlc_res = match forward_info {
4416                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4417                                                                         prev_short_channel_id, prev_htlc_id, prev_channel_id, prev_funding_outpoint,
4418                                                                         prev_user_channel_id, forward_info: PendingHTLCInfo {
4419                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4420                                                                                 routing: PendingHTLCRouting::Forward {
4421                                                                                         onion_packet, blinded, ..
4422                                                                                 }, skimmed_fee_msat, ..
4423                                                                         },
4424                                                                 }) => {
4425                                                                         log_trace!(logger, "Adding HTLC from short id {} with payment_hash {} to channel with short id {} after delay", prev_short_channel_id, &payment_hash, short_chan_id);
4426                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4427                                                                                 short_channel_id: prev_short_channel_id,
4428                                                                                 user_channel_id: Some(prev_user_channel_id),
4429                                                                                 channel_id: prev_channel_id,
4430                                                                                 outpoint: prev_funding_outpoint,
4431                                                                                 htlc_id: prev_htlc_id,
4432                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4433                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4434                                                                                 phantom_shared_secret: None,
4435                                                                                 blinded_failure: blinded.map(|b| b.failure),
4436                                                                         });
4437                                                                         let next_blinding_point = blinded.and_then(|b| {
4438                                                                                 let encrypted_tlvs_ss = self.node_signer.ecdh(
4439                                                                                         Recipient::Node, &b.inbound_blinding_point, None
4440                                                                                 ).unwrap().secret_bytes();
4441                                                                                 onion_utils::next_hop_pubkey(
4442                                                                                         &self.secp_ctx, b.inbound_blinding_point, &encrypted_tlvs_ss
4443                                                                                 ).ok()
4444                                                                         });
4445                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4446                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4447                                                                                 onion_packet, skimmed_fee_msat, next_blinding_point, &self.fee_estimator,
4448                                                                                 &&logger)
4449                                                                         {
4450                                                                                 if let ChannelError::Ignore(msg) = e {
4451                                                                                         log_trace!(logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4452                                                                                 } else {
4453                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4454                                                                                 }
4455                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4456                                                                                 failed_forwards.push((htlc_source, payment_hash,
4457                                                                                         HTLCFailReason::reason(failure_code, data),
4458                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4459                                                                                 ));
4460                                                                                 continue;
4461                                                                         }
4462                                                                         None
4463                                                                 },
4464                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4465                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4466                                                                 },
4467                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4468                                                                         log_trace!(logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4469                                                                         Some((chan.queue_fail_htlc(htlc_id, err_packet, &&logger), htlc_id))
4470                                                                 },
4471                                                                 HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
4472                                                                         log_trace!(logger, "Failing malformed HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4473                                                                         let res = chan.queue_fail_malformed_htlc(
4474                                                                                 htlc_id, failure_code, sha256_of_onion, &&logger
4475                                                                         );
4476                                                                         Some((res, htlc_id))
4477                                                                 },
4478                                                         };
4479                                                         if let Some((queue_fail_htlc_res, htlc_id)) = queue_fail_htlc_res {
4480                                                                 if let Err(e) = queue_fail_htlc_res {
4481                                                                         if let ChannelError::Ignore(msg) = e {
4482                                                                                 log_trace!(logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4483                                                                         } else {
4484                                                                                 panic!("Stated return value requirements in queue_fail_{{malformed_}}htlc() were not met");
4485                                                                         }
4486                                                                         // fail-backs are best-effort, we probably already have one
4487                                                                         // pending, and if not that's OK, if not, the channel is on
4488                                                                         // the chain and sending the HTLC-Timeout is their problem.
4489                                                                         continue;
4490                                                                 }
4491                                                         }
4492                                                 }
4493                                         } else {
4494                                                 forwarding_channel_not_found!();
4495                                                 continue;
4496                                         }
4497                                 } else {
4498                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4499                                                 match forward_info {
4500                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4501                                                                 prev_short_channel_id, prev_htlc_id, prev_channel_id, prev_funding_outpoint,
4502                                                                 prev_user_channel_id, forward_info: PendingHTLCInfo {
4503                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4504                                                                         skimmed_fee_msat, ..
4505                                                                 }
4506                                                         }) => {
4507                                                                 let blinded_failure = routing.blinded_failure();
4508                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4509                                                                         PendingHTLCRouting::Receive {
4510                                                                                 payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret,
4511                                                                                 custom_tlvs, requires_blinded_error: _
4512                                                                         } => {
4513                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4514                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4515                                                                                                 payment_metadata, custom_tlvs };
4516                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4517                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4518                                                                         },
4519                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4520                                                                                 let onion_fields = RecipientOnionFields {
4521                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4522                                                                                         payment_metadata,
4523                                                                                         custom_tlvs,
4524                                                                                 };
4525                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4526                                                                                         payment_data, None, onion_fields)
4527                                                                         },
4528                                                                         _ => {
4529                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4530                                                                         }
4531                                                                 };
4532                                                                 let claimable_htlc = ClaimableHTLC {
4533                                                                         prev_hop: HTLCPreviousHopData {
4534                                                                                 short_channel_id: prev_short_channel_id,
4535                                                                                 user_channel_id: Some(prev_user_channel_id),
4536                                                                                 channel_id: prev_channel_id,
4537                                                                                 outpoint: prev_funding_outpoint,
4538                                                                                 htlc_id: prev_htlc_id,
4539                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4540                                                                                 phantom_shared_secret,
4541                                                                                 blinded_failure,
4542                                                                         },
4543                                                                         // We differentiate the received value from the sender intended value
4544                                                                         // if possible so that we don't prematurely mark MPP payments complete
4545                                                                         // if routing nodes overpay
4546                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4547                                                                         sender_intended_value: outgoing_amt_msat,
4548                                                                         timer_ticks: 0,
4549                                                                         total_value_received: None,
4550                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4551                                                                         cltv_expiry,
4552                                                                         onion_payload,
4553                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4554                                                                 };
4555
4556                                                                 let mut committed_to_claimable = false;
4557
4558                                                                 macro_rules! fail_htlc {
4559                                                                         ($htlc: expr, $payment_hash: expr) => {
4560                                                                                 debug_assert!(!committed_to_claimable);
4561                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4562                                                                                 htlc_msat_height_data.extend_from_slice(
4563                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4564                                                                                 );
4565                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4566                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4567                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4568                                                                                                 channel_id: prev_channel_id,
4569                                                                                                 outpoint: prev_funding_outpoint,
4570                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4571                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4572                                                                                                 phantom_shared_secret,
4573                                                                                                 blinded_failure,
4574                                                                                         }), payment_hash,
4575                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4576                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4577                                                                                 ));
4578                                                                                 continue 'next_forwardable_htlc;
4579                                                                         }
4580                                                                 }
4581                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4582                                                                 let mut receiver_node_id = self.our_network_pubkey;
4583                                                                 if phantom_shared_secret.is_some() {
4584                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4585                                                                                 .expect("Failed to get node_id for phantom node recipient");
4586                                                                 }
4587
4588                                                                 macro_rules! check_total_value {
4589                                                                         ($purpose: expr) => {{
4590                                                                                 let mut payment_claimable_generated = false;
4591                                                                                 let is_keysend = match $purpose {
4592                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4593                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4594                                                                                 };
4595                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4596                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4597                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4598                                                                                 }
4599                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4600                                                                                         .entry(payment_hash)
4601                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4602                                                                                         .or_insert_with(|| {
4603                                                                                                 committed_to_claimable = true;
4604                                                                                                 ClaimablePayment {
4605                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4606                                                                                                 }
4607                                                                                         });
4608                                                                                 if $purpose != claimable_payment.purpose {
4609                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4610                                                                                         log_trace!(self.logger, "Failing new {} HTLC with payment_hash {} as we already had an existing {} HTLC with the same payment hash", log_keysend(is_keysend), &payment_hash, log_keysend(!is_keysend));
4611                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4612                                                                                 }
4613                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4614                                                                                         log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} as we already had an existing keysend HTLC with the same payment hash and our config states we don't accept MPP keysend", &payment_hash);
4615                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4616                                                                                 }
4617                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4618                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4619                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4620                                                                                         }
4621                                                                                 } else {
4622                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4623                                                                                 }
4624                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4625                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4626                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4627                                                                                 for htlc in htlcs.iter() {
4628                                                                                         total_value += htlc.sender_intended_value;
4629                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4630                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4631                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4632                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4633                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4634                                                                                         }
4635                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4636                                                                                 }
4637                                                                                 // The condition determining whether an MPP is complete must
4638                                                                                 // match exactly the condition used in `timer_tick_occurred`
4639                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4640                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4641                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4642                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4643                                                                                                 &payment_hash);
4644                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4645                                                                                 } else if total_value >= claimable_htlc.total_msat {
4646                                                                                         #[allow(unused_assignments)] {
4647                                                                                                 committed_to_claimable = true;
4648                                                                                         }
4649                                                                                         htlcs.push(claimable_htlc);
4650                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4651                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4652                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4653                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4654                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4655                                                                                                 counterparty_skimmed_fee_msat);
4656                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4657                                                                                                 receiver_node_id: Some(receiver_node_id),
4658                                                                                                 payment_hash,
4659                                                                                                 purpose: $purpose,
4660                                                                                                 amount_msat,
4661                                                                                                 counterparty_skimmed_fee_msat,
4662                                                                                                 via_channel_id: Some(prev_channel_id),
4663                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4664                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4665                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4666                                                                                         }, None));
4667                                                                                         payment_claimable_generated = true;
4668                                                                                 } else {
4669                                                                                         // Nothing to do - we haven't reached the total
4670                                                                                         // payment value yet, wait until we receive more
4671                                                                                         // MPP parts.
4672                                                                                         htlcs.push(claimable_htlc);
4673                                                                                         #[allow(unused_assignments)] {
4674                                                                                                 committed_to_claimable = true;
4675                                                                                         }
4676                                                                                 }
4677                                                                                 payment_claimable_generated
4678                                                                         }}
4679                                                                 }
4680
4681                                                                 // Check that the payment hash and secret are known. Note that we
4682                                                                 // MUST take care to handle the "unknown payment hash" and
4683                                                                 // "incorrect payment secret" cases here identically or we'd expose
4684                                                                 // that we are the ultimate recipient of the given payment hash.
4685                                                                 // Further, we must not expose whether we have any other HTLCs
4686                                                                 // associated with the same payment_hash pending or not.
4687                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4688                                                                 match payment_secrets.entry(payment_hash) {
4689                                                                         hash_map::Entry::Vacant(_) => {
4690                                                                                 match claimable_htlc.onion_payload {
4691                                                                                         OnionPayload::Invoice { .. } => {
4692                                                                                                 let payment_data = payment_data.unwrap();
4693                                                                                                 let (payment_preimage, min_final_cltv_expiry_delta) = match inbound_payment::verify(payment_hash, &payment_data, self.highest_seen_timestamp.load(Ordering::Acquire) as u64, &self.inbound_payment_key, &self.logger) {
4694                                                                                                         Ok(result) => result,
4695                                                                                                         Err(()) => {
4696                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4697                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4698                                                                                                         }
4699                                                                                                 };
4700                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4701                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4702                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4703                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4704                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4705                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4706                                                                                                         }
4707                                                                                                 }
4708                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4709                                                                                                         payment_preimage: payment_preimage.clone(),
4710                                                                                                         payment_secret: payment_data.payment_secret,
4711                                                                                                 };
4712                                                                                                 check_total_value!(purpose);
4713                                                                                         },
4714                                                                                         OnionPayload::Spontaneous(preimage) => {
4715                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4716                                                                                                 check_total_value!(purpose);
4717                                                                                         }
4718                                                                                 }
4719                                                                         },
4720                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4721                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4722                                                                                         log_trace!(self.logger, "Failing new keysend HTLC with payment_hash {} because we already have an inbound payment with the same payment hash", &payment_hash);
4723                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4724                                                                                 }
4725                                                                                 let payment_data = payment_data.unwrap();
4726                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4727                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4728                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4729                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4730                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4731                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4732                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4733                                                                                 } else {
4734                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4735                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4736                                                                                                 payment_secret: payment_data.payment_secret,
4737                                                                                         };
4738                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4739                                                                                         if payment_claimable_generated {
4740                                                                                                 inbound_payment.remove_entry();
4741                                                                                         }
4742                                                                                 }
4743                                                                         },
4744                                                                 };
4745                                                         },
4746                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4747                                                                 panic!("Got pending fail of our own HTLC");
4748                                                         }
4749                                                 }
4750                                         }
4751                                 }
4752                         }
4753                 }
4754
4755                 let best_block_height = self.best_block.read().unwrap().height();
4756                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4757                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4758                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4759
4760                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4761                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4762                 }
4763                 self.forward_htlcs(&mut phantom_receives);
4764
4765                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4766                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4767                 // nice to do the work now if we can rather than while we're trying to get messages in the
4768                 // network stack.
4769                 self.check_free_holding_cells();
4770
4771                 if new_events.is_empty() { return }
4772                 let mut events = self.pending_events.lock().unwrap();
4773                 events.append(&mut new_events);
4774         }
4775
4776         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4777         ///
4778         /// Expects the caller to have a total_consistency_lock read lock.
4779         fn process_background_events(&self) -> NotifyOption {
4780                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4781
4782                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4783
4784                 let mut background_events = Vec::new();
4785                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4786                 if background_events.is_empty() {
4787                         return NotifyOption::SkipPersistNoEvents;
4788                 }
4789
4790                 for event in background_events.drain(..) {
4791                         match event {
4792                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, _channel_id, update)) => {
4793                                         // The channel has already been closed, so no use bothering to care about the
4794                                         // monitor updating completing.
4795                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4796                                 },
4797                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, channel_id, update } => {
4798                                         let mut updated_chan = false;
4799                                         {
4800                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4801                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4802                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4803                                                         let peer_state = &mut *peer_state_lock;
4804                                                         match peer_state.channel_by_id.entry(channel_id) {
4805                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4806                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4807                                                                                 updated_chan = true;
4808                                                                                 handle_new_monitor_update!(self, funding_txo, update.clone(),
4809                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4810                                                                         } else {
4811                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4812                                                                         }
4813                                                                 },
4814                                                                 hash_map::Entry::Vacant(_) => {},
4815                                                         }
4816                                                 }
4817                                         }
4818                                         if !updated_chan {
4819                                                 // TODO: Track this as in-flight even though the channel is closed.
4820                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4821                                         }
4822                                 },
4823                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4824                                         let per_peer_state = self.per_peer_state.read().unwrap();
4825                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4826                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4827                                                 let peer_state = &mut *peer_state_lock;
4828                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4829                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4830                                                 } else {
4831                                                         let update_actions = peer_state.monitor_update_blocked_actions
4832                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4833                                                         mem::drop(peer_state_lock);
4834                                                         mem::drop(per_peer_state);
4835                                                         self.handle_monitor_update_completion_actions(update_actions);
4836                                                 }
4837                                         }
4838                                 },
4839                         }
4840                 }
4841                 NotifyOption::DoPersist
4842         }
4843
4844         #[cfg(any(test, feature = "_test_utils"))]
4845         /// Process background events, for functional testing
4846         pub fn test_process_background_events(&self) {
4847                 let _lck = self.total_consistency_lock.read().unwrap();
4848                 let _ = self.process_background_events();
4849         }
4850
4851         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4852                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4853
4854                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4855
4856                 // If the feerate has decreased by less than half, don't bother
4857                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4858                         return NotifyOption::SkipPersistNoEvents;
4859                 }
4860                 if !chan.context.is_live() {
4861                         log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4862                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4863                         return NotifyOption::SkipPersistNoEvents;
4864                 }
4865                 log_trace!(logger, "Channel {} qualifies for a feerate change from {} to {}.",
4866                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4867
4868                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &&logger);
4869                 NotifyOption::DoPersist
4870         }
4871
4872         #[cfg(fuzzing)]
4873         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4874         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4875         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4876         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4877         pub fn maybe_update_chan_fees(&self) {
4878                 PersistenceNotifierGuard::optionally_notify(self, || {
4879                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4880
4881                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4882                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4883
4884                         let per_peer_state = self.per_peer_state.read().unwrap();
4885                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4886                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4887                                 let peer_state = &mut *peer_state_lock;
4888                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4889                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4890                                 ) {
4891                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4892                                                 anchor_feerate
4893                                         } else {
4894                                                 non_anchor_feerate
4895                                         };
4896                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4897                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4898                                 }
4899                         }
4900
4901                         should_persist
4902                 });
4903         }
4904
4905         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4906         ///
4907         /// This currently includes:
4908         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4909         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4910         ///    than a minute, informing the network that they should no longer attempt to route over
4911         ///    the channel.
4912         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4913         ///    with the current [`ChannelConfig`].
4914         ///  * Removing peers which have disconnected but and no longer have any channels.
4915         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4916         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4917         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4918         ///    The latter is determined using the system clock in `std` and the highest seen block time
4919         ///    minus two hours in `no-std`.
4920         ///
4921         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4922         /// estimate fetches.
4923         ///
4924         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4925         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4926         pub fn timer_tick_occurred(&self) {
4927                 PersistenceNotifierGuard::optionally_notify(self, || {
4928                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4929
4930                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4931                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4932
4933                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4934                         let mut timed_out_mpp_htlcs = Vec::new();
4935                         let mut pending_peers_awaiting_removal = Vec::new();
4936                         let mut shutdown_channels = Vec::new();
4937
4938                         let mut process_unfunded_channel_tick = |
4939                                 chan_id: &ChannelId,
4940                                 context: &mut ChannelContext<SP>,
4941                                 unfunded_context: &mut UnfundedChannelContext,
4942                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4943                                 counterparty_node_id: PublicKey,
4944                         | {
4945                                 context.maybe_expire_prev_config();
4946                                 if unfunded_context.should_expire_unfunded_channel() {
4947                                         let logger = WithChannelContext::from(&self.logger, context);
4948                                         log_error!(logger,
4949                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4950                                         update_maps_on_chan_removal!(self, &context);
4951                                         shutdown_channels.push(context.force_shutdown(false, ClosureReason::HolderForceClosed));
4952                                         pending_msg_events.push(MessageSendEvent::HandleError {
4953                                                 node_id: counterparty_node_id,
4954                                                 action: msgs::ErrorAction::SendErrorMessage {
4955                                                         msg: msgs::ErrorMessage {
4956                                                                 channel_id: *chan_id,
4957                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4958                                                         },
4959                                                 },
4960                                         });
4961                                         false
4962                                 } else {
4963                                         true
4964                                 }
4965                         };
4966
4967                         {
4968                                 let per_peer_state = self.per_peer_state.read().unwrap();
4969                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4970                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4971                                         let peer_state = &mut *peer_state_lock;
4972                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4973                                         let counterparty_node_id = *counterparty_node_id;
4974                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4975                                                 match phase {
4976                                                         ChannelPhase::Funded(chan) => {
4977                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4978                                                                         anchor_feerate
4979                                                                 } else {
4980                                                                         non_anchor_feerate
4981                                                                 };
4982                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4983                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4984
4985                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4986                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4987                                                                         handle_errors.push((Err(err), counterparty_node_id));
4988                                                                         if needs_close { return false; }
4989                                                                 }
4990
4991                                                                 match chan.channel_update_status() {
4992                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4993                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4994                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4995                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4996                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4997                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4998                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4999                                                                                 n += 1;
5000                                                                                 if n >= DISABLE_GOSSIP_TICKS {
5001                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
5002                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5003                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5004                                                                                                         msg: update
5005                                                                                                 });
5006                                                                                         }
5007                                                                                         should_persist = NotifyOption::DoPersist;
5008                                                                                 } else {
5009                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
5010                                                                                 }
5011                                                                         },
5012                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
5013                                                                                 n += 1;
5014                                                                                 if n >= ENABLE_GOSSIP_TICKS {
5015                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
5016                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
5017                                                                                                 pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
5018                                                                                                         msg: update
5019                                                                                                 });
5020                                                                                         }
5021                                                                                         should_persist = NotifyOption::DoPersist;
5022                                                                                 } else {
5023                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
5024                                                                                 }
5025                                                                         },
5026                                                                         _ => {},
5027                                                                 }
5028
5029                                                                 chan.context.maybe_expire_prev_config();
5030
5031                                                                 if chan.should_disconnect_peer_awaiting_response() {
5032                                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
5033                                                                         log_debug!(logger, "Disconnecting peer {} due to not making any progress on channel {}",
5034                                                                                         counterparty_node_id, chan_id);
5035                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
5036                                                                                 node_id: counterparty_node_id,
5037                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
5038                                                                                         msg: msgs::WarningMessage {
5039                                                                                                 channel_id: *chan_id,
5040                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
5041                                                                                         },
5042                                                                                 },
5043                                                                         });
5044                                                                 }
5045
5046                                                                 true
5047                                                         },
5048                                                         ChannelPhase::UnfundedInboundV1(chan) => {
5049                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5050                                                                         pending_msg_events, counterparty_node_id)
5051                                                         },
5052                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
5053                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5054                                                                         pending_msg_events, counterparty_node_id)
5055                                                         },
5056                                                         #[cfg(dual_funding)]
5057                                                         ChannelPhase::UnfundedInboundV2(chan) => {
5058                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5059                                                                         pending_msg_events, counterparty_node_id)
5060                                                         },
5061                                                         #[cfg(dual_funding)]
5062                                                         ChannelPhase::UnfundedOutboundV2(chan) => {
5063                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5064                                                                         pending_msg_events, counterparty_node_id)
5065                                                         },
5066                                                 }
5067                                         });
5068
5069                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
5070                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
5071                                                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(*chan_id));
5072                                                         log_error!(logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
5073                                                         peer_state.pending_msg_events.push(
5074                                                                 events::MessageSendEvent::HandleError {
5075                                                                         node_id: counterparty_node_id,
5076                                                                         action: msgs::ErrorAction::SendErrorMessage {
5077                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
5078                                                                         },
5079                                                                 }
5080                                                         );
5081                                                 }
5082                                         }
5083                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
5084
5085                                         if peer_state.ok_to_remove(true) {
5086                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
5087                                         }
5088                                 }
5089                         }
5090
5091                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
5092                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
5093                         // of to that peer is later closed while still being disconnected (i.e. force closed),
5094                         // we therefore need to remove the peer from `peer_state` separately.
5095                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
5096                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
5097                         // negative effects on parallelism as much as possible.
5098                         if pending_peers_awaiting_removal.len() > 0 {
5099                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
5100                                 for counterparty_node_id in pending_peers_awaiting_removal {
5101                                         match per_peer_state.entry(counterparty_node_id) {
5102                                                 hash_map::Entry::Occupied(entry) => {
5103                                                         // Remove the entry if the peer is still disconnected and we still
5104                                                         // have no channels to the peer.
5105                                                         let remove_entry = {
5106                                                                 let peer_state = entry.get().lock().unwrap();
5107                                                                 peer_state.ok_to_remove(true)
5108                                                         };
5109                                                         if remove_entry {
5110                                                                 entry.remove_entry();
5111                                                         }
5112                                                 },
5113                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5114                                         }
5115                                 }
5116                         }
5117
5118                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5119                                 if payment.htlcs.is_empty() {
5120                                         // This should be unreachable
5121                                         debug_assert!(false);
5122                                         return false;
5123                                 }
5124                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5125                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5126                                         // In this case we're not going to handle any timeouts of the parts here.
5127                                         // This condition determining whether the MPP is complete here must match
5128                                         // exactly the condition used in `process_pending_htlc_forwards`.
5129                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5130                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5131                                         {
5132                                                 return true;
5133                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5134                                                 htlc.timer_ticks += 1;
5135                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5136                                         }) {
5137                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5138                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5139                                                 return false;
5140                                         }
5141                                 }
5142                                 true
5143                         });
5144
5145                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5146                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5147                                 let reason = HTLCFailReason::from_failure_code(23);
5148                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5149                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5150                         }
5151
5152                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5153                                 let _ = handle_error!(self, err, counterparty_node_id);
5154                         }
5155
5156                         for shutdown_res in shutdown_channels {
5157                                 self.finish_close_channel(shutdown_res);
5158                         }
5159
5160                         #[cfg(feature = "std")]
5161                         let duration_since_epoch = std::time::SystemTime::now()
5162                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5163                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5164                         #[cfg(not(feature = "std"))]
5165                         let duration_since_epoch = Duration::from_secs(
5166                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5167                         );
5168
5169                         self.pending_outbound_payments.remove_stale_payments(
5170                                 duration_since_epoch, &self.pending_events
5171                         );
5172
5173                         // Technically we don't need to do this here, but if we have holding cell entries in a
5174                         // channel that need freeing, it's better to do that here and block a background task
5175                         // than block the message queueing pipeline.
5176                         if self.check_free_holding_cells() {
5177                                 should_persist = NotifyOption::DoPersist;
5178                         }
5179
5180                         should_persist
5181                 });
5182         }
5183
5184         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5185         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5186         /// along the path (including in our own channel on which we received it).
5187         ///
5188         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5189         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5190         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5191         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5192         ///
5193         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5194         /// [`ChannelManager::claim_funds`]), you should still monitor for
5195         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5196         /// startup during which time claims that were in-progress at shutdown may be replayed.
5197         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5198                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5199         }
5200
5201         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5202         /// reason for the failure.
5203         ///
5204         /// See [`FailureCode`] for valid failure codes.
5205         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5206                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5207
5208                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5209                 if let Some(payment) = removed_source {
5210                         for htlc in payment.htlcs {
5211                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5212                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5213                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5214                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5215                         }
5216                 }
5217         }
5218
5219         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5220         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5221                 match failure_code {
5222                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5223                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5224                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5225                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5226                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5227                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5228                         },
5229                         FailureCode::InvalidOnionPayload(data) => {
5230                                 let fail_data = match data {
5231                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5232                                         None => Vec::new(),
5233                                 };
5234                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5235                         }
5236                 }
5237         }
5238
5239         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5240         /// that we want to return and a channel.
5241         ///
5242         /// This is for failures on the channel on which the HTLC was *received*, not failures
5243         /// forwarding
5244         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5245                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5246                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5247                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5248                 // an inbound SCID alias before the real SCID.
5249                 let scid_pref = if chan.context.should_announce() {
5250                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5251                 } else {
5252                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5253                 };
5254                 if let Some(scid) = scid_pref {
5255                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5256                 } else {
5257                         (0x4000|10, Vec::new())
5258                 }
5259         }
5260
5261
5262         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5263         /// that we want to return and a channel.
5264         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5265                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5266                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5267                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5268                         if desired_err_code == 0x1000 | 20 {
5269                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5270                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5271                                 0u16.write(&mut enc).expect("Writes cannot fail");
5272                         }
5273                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5274                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5275                         upd.write(&mut enc).expect("Writes cannot fail");
5276                         (desired_err_code, enc.0)
5277                 } else {
5278                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5279                         // which means we really shouldn't have gotten a payment to be forwarded over this
5280                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5281                         // PERM|no_such_channel should be fine.
5282                         (0x4000|10, Vec::new())
5283                 }
5284         }
5285
5286         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5287         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5288         // be surfaced to the user.
5289         fn fail_holding_cell_htlcs(
5290                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5291                 counterparty_node_id: &PublicKey
5292         ) {
5293                 let (failure_code, onion_failure_data) = {
5294                         let per_peer_state = self.per_peer_state.read().unwrap();
5295                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5296                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5297                                 let peer_state = &mut *peer_state_lock;
5298                                 match peer_state.channel_by_id.entry(channel_id) {
5299                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5300                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5301                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5302                                                 } else {
5303                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5304                                                         debug_assert!(false);
5305                                                         (0x4000|10, Vec::new())
5306                                                 }
5307                                         },
5308                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5309                                 }
5310                         } else { (0x4000|10, Vec::new()) }
5311                 };
5312
5313                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5314                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5315                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5316                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5317                 }
5318         }
5319
5320         /// Fails an HTLC backwards to the sender of it to us.
5321         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5322         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5323                 // Ensure that no peer state channel storage lock is held when calling this function.
5324                 // This ensures that future code doesn't introduce a lock-order requirement for
5325                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5326                 // this function with any `per_peer_state` peer lock acquired would.
5327                 #[cfg(debug_assertions)]
5328                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5329                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5330                 }
5331
5332                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5333                 //identify whether we sent it or not based on the (I presume) very different runtime
5334                 //between the branches here. We should make this async and move it into the forward HTLCs
5335                 //timer handling.
5336
5337                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5338                 // from block_connected which may run during initialization prior to the chain_monitor
5339                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5340                 match source {
5341                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5342                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5343                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5344                                         &self.pending_events, &self.logger)
5345                                 { self.push_pending_forwards_ev(); }
5346                         },
5347                         HTLCSource::PreviousHopData(HTLCPreviousHopData {
5348                                 ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret,
5349                                 ref phantom_shared_secret, outpoint: _, ref blinded_failure, ref channel_id, ..
5350                         }) => {
5351                                 log_trace!(
5352                                         WithContext::from(&self.logger, None, Some(*channel_id)),
5353                                         "Failing {}HTLC with payment_hash {} backwards from us: {:?}",
5354                                         if blinded_failure.is_some() { "blinded " } else { "" }, &payment_hash, onion_error
5355                                 );
5356                                 let failure = match blinded_failure {
5357                                         Some(BlindedFailure::FromIntroductionNode) => {
5358                                                 let blinded_onion_error = HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32]);
5359                                                 let err_packet = blinded_onion_error.get_encrypted_failure_packet(
5360                                                         incoming_packet_shared_secret, phantom_shared_secret
5361                                                 );
5362                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5363                                         },
5364                                         Some(BlindedFailure::FromBlindedNode) => {
5365                                                 HTLCForwardInfo::FailMalformedHTLC {
5366                                                         htlc_id: *htlc_id,
5367                                                         failure_code: INVALID_ONION_BLINDING,
5368                                                         sha256_of_onion: [0; 32]
5369                                                 }
5370                                         },
5371                                         None => {
5372                                                 let err_packet = onion_error.get_encrypted_failure_packet(
5373                                                         incoming_packet_shared_secret, phantom_shared_secret
5374                                                 );
5375                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5376                                         }
5377                                 };
5378
5379                                 let mut push_forward_ev = false;
5380                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5381                                 if forward_htlcs.is_empty() {
5382                                         push_forward_ev = true;
5383                                 }
5384                                 match forward_htlcs.entry(*short_channel_id) {
5385                                         hash_map::Entry::Occupied(mut entry) => {
5386                                                 entry.get_mut().push(failure);
5387                                         },
5388                                         hash_map::Entry::Vacant(entry) => {
5389                                                 entry.insert(vec!(failure));
5390                                         }
5391                                 }
5392                                 mem::drop(forward_htlcs);
5393                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5394                                 let mut pending_events = self.pending_events.lock().unwrap();
5395                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5396                                         prev_channel_id: *channel_id,
5397                                         failed_next_destination: destination,
5398                                 }, None));
5399                         },
5400                 }
5401         }
5402
5403         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5404         /// [`MessageSendEvent`]s needed to claim the payment.
5405         ///
5406         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5407         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5408         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5409         /// successful. It will generally be available in the next [`process_pending_events`] call.
5410         ///
5411         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5412         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5413         /// event matches your expectation. If you fail to do so and call this method, you may provide
5414         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5415         ///
5416         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5417         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5418         /// [`claim_funds_with_known_custom_tlvs`].
5419         ///
5420         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5421         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5422         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5423         /// [`process_pending_events`]: EventsProvider::process_pending_events
5424         /// [`create_inbound_payment`]: Self::create_inbound_payment
5425         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5426         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5427         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5428                 self.claim_payment_internal(payment_preimage, false);
5429         }
5430
5431         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5432         /// even type numbers.
5433         ///
5434         /// # Note
5435         ///
5436         /// You MUST check you've understood all even TLVs before using this to
5437         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5438         ///
5439         /// [`claim_funds`]: Self::claim_funds
5440         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5441                 self.claim_payment_internal(payment_preimage, true);
5442         }
5443
5444         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5445                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
5446
5447                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5448
5449                 let mut sources = {
5450                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5451                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5452                                 let mut receiver_node_id = self.our_network_pubkey;
5453                                 for htlc in payment.htlcs.iter() {
5454                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5455                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5456                                                         .expect("Failed to get node_id for phantom node recipient");
5457                                                 receiver_node_id = phantom_pubkey;
5458                                                 break;
5459                                         }
5460                                 }
5461
5462                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5463                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5464                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5465                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5466                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5467                                 });
5468                                 if dup_purpose.is_some() {
5469                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5470                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5471                                                 &payment_hash);
5472                                 }
5473
5474                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5475                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5476                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5477                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5478                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5479                                                 mem::drop(claimable_payments);
5480                                                 for htlc in payment.htlcs {
5481                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5482                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5483                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5484                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5485                                                 }
5486                                                 return;
5487                                         }
5488                                 }
5489
5490                                 payment.htlcs
5491                         } else { return; }
5492                 };
5493                 debug_assert!(!sources.is_empty());
5494
5495                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5496                 // and when we got here we need to check that the amount we're about to claim matches the
5497                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5498                 // the MPP parts all have the same `total_msat`.
5499                 let mut claimable_amt_msat = 0;
5500                 let mut prev_total_msat = None;
5501                 let mut expected_amt_msat = None;
5502                 let mut valid_mpp = true;
5503                 let mut errs = Vec::new();
5504                 let per_peer_state = self.per_peer_state.read().unwrap();
5505                 for htlc in sources.iter() {
5506                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5507                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5508                                 debug_assert!(false);
5509                                 valid_mpp = false;
5510                                 break;
5511                         }
5512                         prev_total_msat = Some(htlc.total_msat);
5513
5514                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5515                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5516                                 debug_assert!(false);
5517                                 valid_mpp = false;
5518                                 break;
5519                         }
5520                         expected_amt_msat = htlc.total_value_received;
5521                         claimable_amt_msat += htlc.value;
5522                 }
5523                 mem::drop(per_peer_state);
5524                 if sources.is_empty() || expected_amt_msat.is_none() {
5525                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5526                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5527                         return;
5528                 }
5529                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5530                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5531                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5532                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5533                         return;
5534                 }
5535                 if valid_mpp {
5536                         for htlc in sources.drain(..) {
5537                                 let prev_hop_chan_id = htlc.prev_hop.channel_id;
5538                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5539                                         htlc.prev_hop, payment_preimage,
5540                                         |_, definitely_duplicate| {
5541                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5542                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5543                                         }
5544                                 ) {
5545                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5546                                                 // We got a temporary failure updating monitor, but will claim the
5547                                                 // HTLC when the monitor updating is restored (or on chain).
5548                                                 let logger = WithContext::from(&self.logger, None, Some(prev_hop_chan_id));
5549                                                 log_error!(logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5550                                         } else { errs.push((pk, err)); }
5551                                 }
5552                         }
5553                 }
5554                 if !valid_mpp {
5555                         for htlc in sources.drain(..) {
5556                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5557                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5558                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5559                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5560                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5561                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5562                         }
5563                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5564                 }
5565
5566                 // Now we can handle any errors which were generated.
5567                 for (counterparty_node_id, err) in errs.drain(..) {
5568                         let res: Result<(), _> = Err(err);
5569                         let _ = handle_error!(self, res, counterparty_node_id);
5570                 }
5571         }
5572
5573         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5574                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5575         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5576                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5577
5578                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5579                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5580                 // `BackgroundEvent`s.
5581                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5582
5583                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5584                 // the required mutexes are not held before we start.
5585                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5586                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5587
5588                 {
5589                         let per_peer_state = self.per_peer_state.read().unwrap();
5590                         let chan_id = prev_hop.channel_id;
5591                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5592                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5593                                 None => None
5594                         };
5595
5596                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5597                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5598                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5599                         ).unwrap_or(None);
5600
5601                         if peer_state_opt.is_some() {
5602                                 let mut peer_state_lock = peer_state_opt.unwrap();
5603                                 let peer_state = &mut *peer_state_lock;
5604                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5605                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5606                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5607                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
5608                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &&logger);
5609
5610                                                 match fulfill_res {
5611                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5612                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5613                                                                         log_trace!(logger, "Tracking monitor update completion action for channel {}: {:?}",
5614                                                                                 chan_id, action);
5615                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5616                                                                 }
5617                                                                 if !during_init {
5618                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
5619                                                                                 peer_state, per_peer_state, chan);
5620                                                                 } else {
5621                                                                         // If we're running during init we cannot update a monitor directly -
5622                                                                         // they probably haven't actually been loaded yet. Instead, push the
5623                                                                         // monitor update as a background event.
5624                                                                         self.pending_background_events.lock().unwrap().push(
5625                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5626                                                                                         counterparty_node_id,
5627                                                                                         funding_txo: prev_hop.outpoint,
5628                                                                                         channel_id: prev_hop.channel_id,
5629                                                                                         update: monitor_update.clone(),
5630                                                                                 });
5631                                                                 }
5632                                                         }
5633                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5634                                                                 let action = if let Some(action) = completion_action(None, true) {
5635                                                                         action
5636                                                                 } else {
5637                                                                         return Ok(());
5638                                                                 };
5639                                                                 mem::drop(peer_state_lock);
5640
5641                                                                 log_trace!(logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5642                                                                         chan_id, action);
5643                                                                 let (node_id, _funding_outpoint, channel_id, blocker) =
5644                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5645                                                                         downstream_counterparty_node_id: node_id,
5646                                                                         downstream_funding_outpoint: funding_outpoint,
5647                                                                         blocking_action: blocker, downstream_channel_id: channel_id,
5648                                                                 } = action {
5649                                                                         (node_id, funding_outpoint, channel_id, blocker)
5650                                                                 } else {
5651                                                                         debug_assert!(false,
5652                                                                                 "Duplicate claims should always free another channel immediately");
5653                                                                         return Ok(());
5654                                                                 };
5655                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5656                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5657                                                                         if let Some(blockers) = peer_state
5658                                                                                 .actions_blocking_raa_monitor_updates
5659                                                                                 .get_mut(&channel_id)
5660                                                                         {
5661                                                                                 let mut found_blocker = false;
5662                                                                                 blockers.retain(|iter| {
5663                                                                                         // Note that we could actually be blocked, in
5664                                                                                         // which case we need to only remove the one
5665                                                                                         // blocker which was added duplicatively.
5666                                                                                         let first_blocker = !found_blocker;
5667                                                                                         if *iter == blocker { found_blocker = true; }
5668                                                                                         *iter != blocker || !first_blocker
5669                                                                                 });
5670                                                                                 debug_assert!(found_blocker);
5671                                                                         }
5672                                                                 } else {
5673                                                                         debug_assert!(false);
5674                                                                 }
5675                                                         }
5676                                                 }
5677                                         }
5678                                         return Ok(());
5679                                 }
5680                         }
5681                 }
5682                 let preimage_update = ChannelMonitorUpdate {
5683                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5684                         counterparty_node_id: None,
5685                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5686                                 payment_preimage,
5687                         }],
5688                         channel_id: Some(prev_hop.channel_id),
5689                 };
5690
5691                 if !during_init {
5692                         // We update the ChannelMonitor on the backward link, after
5693                         // receiving an `update_fulfill_htlc` from the forward link.
5694                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5695                         if update_res != ChannelMonitorUpdateStatus::Completed {
5696                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5697                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5698                                 // channel, or we must have an ability to receive the same event and try
5699                                 // again on restart.
5700                                 log_error!(WithContext::from(&self.logger, None, Some(prev_hop.channel_id)),
5701                                         "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5702                                         payment_preimage, update_res);
5703                         }
5704                 } else {
5705                         // If we're running during init we cannot update a monitor directly - they probably
5706                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5707                         // event.
5708                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5709                         // channel is already closed) we need to ultimately handle the monitor update
5710                         // completion action only after we've completed the monitor update. This is the only
5711                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5712                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5713                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5714                         // complete the monitor update completion action from `completion_action`.
5715                         self.pending_background_events.lock().unwrap().push(
5716                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5717                                         prev_hop.outpoint, prev_hop.channel_id, preimage_update,
5718                                 )));
5719                 }
5720                 // Note that we do process the completion action here. This totally could be a
5721                 // duplicate claim, but we have no way of knowing without interrogating the
5722                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5723                 // generally always allowed to be duplicative (and it's specifically noted in
5724                 // `PaymentForwarded`).
5725                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5726                 Ok(())
5727         }
5728
5729         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5730                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5731         }
5732
5733         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5734                 forwarded_htlc_value_msat: Option<u64>, skimmed_fee_msat: Option<u64>, from_onchain: bool,
5735                 startup_replay: bool, next_channel_counterparty_node_id: Option<PublicKey>,
5736                 next_channel_outpoint: OutPoint, next_channel_id: ChannelId,
5737         ) {
5738                 match source {
5739                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5740                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5741                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5742                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5743                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5744                                 }
5745                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5746                                         channel_funding_outpoint: next_channel_outpoint, channel_id: next_channel_id,
5747                                         counterparty_node_id: path.hops[0].pubkey,
5748                                 };
5749                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5750                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5751                                         &self.logger);
5752                         },
5753                         HTLCSource::PreviousHopData(hop_data) => {
5754                                 let prev_channel_id = hop_data.channel_id;
5755                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5756                                 #[cfg(debug_assertions)]
5757                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5758                                 #[cfg(debug_assertions)]
5759                                 let claiming_channel_id = hop_data.channel_id;
5760                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5761                                         |htlc_claim_value_msat, definitely_duplicate| {
5762                                                 let chan_to_release =
5763                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5764                                                                 Some((node_id, next_channel_outpoint, next_channel_id, completed_blocker))
5765                                                         } else {
5766                                                                 // We can only get `None` here if we are processing a
5767                                                                 // `ChannelMonitor`-originated event, in which case we
5768                                                                 // don't care about ensuring we wake the downstream
5769                                                                 // channel's monitor updating - the channel is already
5770                                                                 // closed.
5771                                                                 None
5772                                                         };
5773
5774                                                 if definitely_duplicate && startup_replay {
5775                                                         // On startup we may get redundant claims which are related to
5776                                                         // monitor updates still in flight. In that case, we shouldn't
5777                                                         // immediately free, but instead let that monitor update complete
5778                                                         // in the background.
5779                                                         #[cfg(debug_assertions)] {
5780                                                                 let background_events = self.pending_background_events.lock().unwrap();
5781                                                                 // There should be a `BackgroundEvent` pending...
5782                                                                 assert!(background_events.iter().any(|ev| {
5783                                                                         match ev {
5784                                                                                 // to apply a monitor update that blocked the claiming channel,
5785                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5786                                                                                         funding_txo, update, ..
5787                                                                                 } => {
5788                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5789                                                                                                 assert!(update.updates.iter().any(|upd|
5790                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5791                                                                                                                 payment_preimage: update_preimage
5792                                                                                                         } = upd {
5793                                                                                                                 payment_preimage == *update_preimage
5794                                                                                                         } else { false }
5795                                                                                                 ), "{:?}", update);
5796                                                                                                 true
5797                                                                                         } else { false }
5798                                                                                 },
5799                                                                                 // or the channel we'd unblock is already closed,
5800                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5801                                                                                         (funding_txo, _channel_id, monitor_update)
5802                                                                                 ) => {
5803                                                                                         if *funding_txo == next_channel_outpoint {
5804                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5805                                                                                                 assert!(matches!(
5806                                                                                                         monitor_update.updates[0],
5807                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5808                                                                                                 ));
5809                                                                                                 true
5810                                                                                         } else { false }
5811                                                                                 },
5812                                                                                 // or the monitor update has completed and will unblock
5813                                                                                 // immediately once we get going.
5814                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5815                                                                                         channel_id, ..
5816                                                                                 } =>
5817                                                                                         *channel_id == claiming_channel_id,
5818                                                                         }
5819                                                                 }), "{:?}", *background_events);
5820                                                         }
5821                                                         None
5822                                                 } else if definitely_duplicate {
5823                                                         if let Some(other_chan) = chan_to_release {
5824                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5825                                                                         downstream_counterparty_node_id: other_chan.0,
5826                                                                         downstream_funding_outpoint: other_chan.1,
5827                                                                         downstream_channel_id: other_chan.2,
5828                                                                         blocking_action: other_chan.3,
5829                                                                 })
5830                                                         } else { None }
5831                                                 } else {
5832                                                         let total_fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5833                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5834                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5835                                                                 } else { None }
5836                                                         } else { None };
5837                                                         debug_assert!(skimmed_fee_msat <= total_fee_earned_msat,
5838                                                                 "skimmed_fee_msat must always be included in total_fee_earned_msat");
5839                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5840                                                                 event: events::Event::PaymentForwarded {
5841                                                                         total_fee_earned_msat,
5842                                                                         claim_from_onchain_tx: from_onchain,
5843                                                                         prev_channel_id: Some(prev_channel_id),
5844                                                                         next_channel_id: Some(next_channel_id),
5845                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5846                                                                         skimmed_fee_msat,
5847                                                                 },
5848                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5849                                                         })
5850                                                 }
5851                                         });
5852                                 if let Err((pk, err)) = res {
5853                                         let result: Result<(), _> = Err(err);
5854                                         let _ = handle_error!(self, result, pk);
5855                                 }
5856                         },
5857                 }
5858         }
5859
5860         /// Gets the node_id held by this ChannelManager
5861         pub fn get_our_node_id(&self) -> PublicKey {
5862                 self.our_network_pubkey.clone()
5863         }
5864
5865         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5866                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5867                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5868                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5869
5870                 for action in actions.into_iter() {
5871                         match action {
5872                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5873                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5874                                         if let Some(ClaimingPayment {
5875                                                 amount_msat,
5876                                                 payment_purpose: purpose,
5877                                                 receiver_node_id,
5878                                                 htlcs,
5879                                                 sender_intended_value: sender_intended_total_msat,
5880                                         }) = payment {
5881                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5882                                                         payment_hash,
5883                                                         purpose,
5884                                                         amount_msat,
5885                                                         receiver_node_id: Some(receiver_node_id),
5886                                                         htlcs,
5887                                                         sender_intended_total_msat,
5888                                                 }, None));
5889                                         }
5890                                 },
5891                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5892                                         event, downstream_counterparty_and_funding_outpoint
5893                                 } => {
5894                                         self.pending_events.lock().unwrap().push_back((event, None));
5895                                         if let Some((node_id, funding_outpoint, channel_id, blocker)) = downstream_counterparty_and_funding_outpoint {
5896                                                 self.handle_monitor_update_release(node_id, funding_outpoint, channel_id, Some(blocker));
5897                                         }
5898                                 },
5899                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5900                                         downstream_counterparty_node_id, downstream_funding_outpoint, downstream_channel_id, blocking_action,
5901                                 } => {
5902                                         self.handle_monitor_update_release(
5903                                                 downstream_counterparty_node_id,
5904                                                 downstream_funding_outpoint,
5905                                                 downstream_channel_id,
5906                                                 Some(blocking_action),
5907                                         );
5908                                 },
5909                         }
5910                 }
5911         }
5912
5913         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5914         /// update completion.
5915         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5916                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5917                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5918                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5919                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5920         -> Option<(u64, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)> {
5921                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5922                 log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5923                         &channel.context.channel_id(),
5924                         if raa.is_some() { "an" } else { "no" },
5925                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5926                         if funding_broadcastable.is_some() { "" } else { "not " },
5927                         if channel_ready.is_some() { "sending" } else { "without" },
5928                         if announcement_sigs.is_some() { "sending" } else { "without" });
5929
5930                 let mut htlc_forwards = None;
5931
5932                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5933                 if !pending_forwards.is_empty() {
5934                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5935                                 channel.context.get_funding_txo().unwrap(), channel.context.channel_id(), channel.context.get_user_id(), pending_forwards));
5936                 }
5937
5938                 if let Some(msg) = channel_ready {
5939                         send_channel_ready!(self, pending_msg_events, channel, msg);
5940                 }
5941                 if let Some(msg) = announcement_sigs {
5942                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5943                                 node_id: counterparty_node_id,
5944                                 msg,
5945                         });
5946                 }
5947
5948                 macro_rules! handle_cs { () => {
5949                         if let Some(update) = commitment_update {
5950                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5951                                         node_id: counterparty_node_id,
5952                                         updates: update,
5953                                 });
5954                         }
5955                 } }
5956                 macro_rules! handle_raa { () => {
5957                         if let Some(revoke_and_ack) = raa {
5958                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5959                                         node_id: counterparty_node_id,
5960                                         msg: revoke_and_ack,
5961                                 });
5962                         }
5963                 } }
5964                 match order {
5965                         RAACommitmentOrder::CommitmentFirst => {
5966                                 handle_cs!();
5967                                 handle_raa!();
5968                         },
5969                         RAACommitmentOrder::RevokeAndACKFirst => {
5970                                 handle_raa!();
5971                                 handle_cs!();
5972                         },
5973                 }
5974
5975                 if let Some(tx) = funding_broadcastable {
5976                         log_info!(logger, "Broadcasting funding transaction with txid {}", tx.txid());
5977                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5978                 }
5979
5980                 {
5981                         let mut pending_events = self.pending_events.lock().unwrap();
5982                         emit_channel_pending_event!(pending_events, channel);
5983                         emit_channel_ready_event!(pending_events, channel);
5984                 }
5985
5986                 htlc_forwards
5987         }
5988
5989         fn channel_monitor_updated(&self, funding_txo: &OutPoint, channel_id: &ChannelId, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5990                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5991
5992                 let counterparty_node_id = match counterparty_node_id {
5993                         Some(cp_id) => cp_id.clone(),
5994                         None => {
5995                                 // TODO: Once we can rely on the counterparty_node_id from the
5996                                 // monitor event, this and the outpoint_to_peer map should be removed.
5997                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
5998                                 match outpoint_to_peer.get(funding_txo) {
5999                                         Some(cp_id) => cp_id.clone(),
6000                                         None => return,
6001                                 }
6002                         }
6003                 };
6004                 let per_peer_state = self.per_peer_state.read().unwrap();
6005                 let mut peer_state_lock;
6006                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
6007                 if peer_state_mutex_opt.is_none() { return }
6008                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
6009                 let peer_state = &mut *peer_state_lock;
6010                 let channel =
6011                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(channel_id) {
6012                                 chan
6013                         } else {
6014                                 let update_actions = peer_state.monitor_update_blocked_actions
6015                                         .remove(&channel_id).unwrap_or(Vec::new());
6016                                 mem::drop(peer_state_lock);
6017                                 mem::drop(per_peer_state);
6018                                 self.handle_monitor_update_completion_actions(update_actions);
6019                                 return;
6020                         };
6021                 let remaining_in_flight =
6022                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
6023                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
6024                                 pending.len()
6025                         } else { 0 };
6026                 let logger = WithChannelContext::from(&self.logger, &channel.context);
6027                 log_trace!(logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
6028                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
6029                         remaining_in_flight);
6030                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
6031                         return;
6032                 }
6033                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
6034         }
6035
6036         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
6037         ///
6038         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
6039         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
6040         /// the channel.
6041         ///
6042         /// The `user_channel_id` parameter will be provided back in
6043         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
6044         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
6045         ///
6046         /// Note that this method will return an error and reject the channel, if it requires support
6047         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
6048         /// used to accept such channels.
6049         ///
6050         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
6051         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
6052         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
6053                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
6054         }
6055
6056         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
6057         /// it as confirmed immediately.
6058         ///
6059         /// The `user_channel_id` parameter will be provided back in
6060         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
6061         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
6062         ///
6063         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
6064         /// and (if the counterparty agrees), enables forwarding of payments immediately.
6065         ///
6066         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
6067         /// transaction and blindly assumes that it will eventually confirm.
6068         ///
6069         /// If it does not confirm before we decide to close the channel, or if the funding transaction
6070         /// does not pay to the correct script the correct amount, *you will lose funds*.
6071         ///
6072         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
6073         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
6074         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
6075                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
6076         }
6077
6078         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
6079
6080                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(*temporary_channel_id));
6081                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6082
6083                 let peers_without_funded_channels =
6084                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
6085                 let per_peer_state = self.per_peer_state.read().unwrap();
6086                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6087                 .ok_or_else(|| {
6088                         let err_str = format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id);
6089                         log_error!(logger, "{}", err_str);
6090
6091                         APIError::ChannelUnavailable { err: err_str }
6092                 })?;
6093                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6094                 let peer_state = &mut *peer_state_lock;
6095                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
6096
6097                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
6098                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
6099                 // that we can delay allocating the SCID until after we're sure that the checks below will
6100                 // succeed.
6101                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
6102                         Some(unaccepted_channel) => {
6103                                 let best_block_height = self.best_block.read().unwrap().height();
6104                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6105                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
6106                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
6107                                         &self.logger, accept_0conf).map_err(|e| {
6108                                                 let err_str = e.to_string();
6109                                                 log_error!(logger, "{}", err_str);
6110
6111                                                 APIError::ChannelUnavailable { err: err_str }
6112                                         })
6113                                 }
6114                         _ => {
6115                                 let err_str = "No such channel awaiting to be accepted.".to_owned();
6116                                 log_error!(logger, "{}", err_str);
6117
6118                                 Err(APIError::APIMisuseError { err: err_str })
6119                         }
6120                 }?;
6121
6122                 if accept_0conf {
6123                         // This should have been correctly configured by the call to InboundV1Channel::new.
6124                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
6125                 } else if channel.context.get_channel_type().requires_zero_conf() {
6126                         let send_msg_err_event = events::MessageSendEvent::HandleError {
6127                                 node_id: channel.context.get_counterparty_node_id(),
6128                                 action: msgs::ErrorAction::SendErrorMessage{
6129                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
6130                                 }
6131                         };
6132                         peer_state.pending_msg_events.push(send_msg_err_event);
6133                         let err_str = "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned();
6134                         log_error!(logger, "{}", err_str);
6135
6136                         return Err(APIError::APIMisuseError { err: err_str });
6137                 } else {
6138                         // If this peer already has some channels, a new channel won't increase our number of peers
6139                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6140                         // channels per-peer we can accept channels from a peer with existing ones.
6141                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
6142                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
6143                                         node_id: channel.context.get_counterparty_node_id(),
6144                                         action: msgs::ErrorAction::SendErrorMessage{
6145                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
6146                                         }
6147                                 };
6148                                 peer_state.pending_msg_events.push(send_msg_err_event);
6149                                 let err_str = "Too many peers with unfunded channels, refusing to accept new ones".to_owned();
6150                                 log_error!(logger, "{}", err_str);
6151
6152                                 return Err(APIError::APIMisuseError { err: err_str });
6153                         }
6154                 }
6155
6156                 // Now that we know we have a channel, assign an outbound SCID alias.
6157                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6158                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6159
6160                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6161                         node_id: channel.context.get_counterparty_node_id(),
6162                         msg: channel.accept_inbound_channel(),
6163                 });
6164
6165                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
6166
6167                 Ok(())
6168         }
6169
6170         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
6171         /// or 0-conf channels.
6172         ///
6173         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6174         /// non-0-conf channels we have with the peer.
6175         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6176         where Filter: Fn(&PeerState<SP>) -> bool {
6177                 let mut peers_without_funded_channels = 0;
6178                 let best_block_height = self.best_block.read().unwrap().height();
6179                 {
6180                         let peer_state_lock = self.per_peer_state.read().unwrap();
6181                         for (_, peer_mtx) in peer_state_lock.iter() {
6182                                 let peer = peer_mtx.lock().unwrap();
6183                                 if !maybe_count_peer(&*peer) { continue; }
6184                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6185                                 if num_unfunded_channels == peer.total_channel_count() {
6186                                         peers_without_funded_channels += 1;
6187                                 }
6188                         }
6189                 }
6190                 return peers_without_funded_channels;
6191         }
6192
6193         fn unfunded_channel_count(
6194                 peer: &PeerState<SP>, best_block_height: u32
6195         ) -> usize {
6196                 let mut num_unfunded_channels = 0;
6197                 for (_, phase) in peer.channel_by_id.iter() {
6198                         match phase {
6199                                 ChannelPhase::Funded(chan) => {
6200                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6201                                         // which have not yet had any confirmations on-chain.
6202                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6203                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6204                                         {
6205                                                 num_unfunded_channels += 1;
6206                                         }
6207                                 },
6208                                 ChannelPhase::UnfundedInboundV1(chan) => {
6209                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6210                                                 num_unfunded_channels += 1;
6211                                         }
6212                                 },
6213                                 // TODO(dual_funding): Combine this match arm with above once #[cfg(dual_funding)] is removed.
6214                                 #[cfg(dual_funding)]
6215                                 ChannelPhase::UnfundedInboundV2(chan) => {
6216                                         // Only inbound V2 channels that are not 0conf and that we do not contribute to will be
6217                                         // included in the unfunded count.
6218                                         if chan.context.minimum_depth().unwrap_or(1) != 0 &&
6219                                                 chan.dual_funding_context.our_funding_satoshis == 0 {
6220                                                 num_unfunded_channels += 1;
6221                                         }
6222                                 },
6223                                 ChannelPhase::UnfundedOutboundV1(_) => {
6224                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6225                                         continue;
6226                                 },
6227                                 // TODO(dual_funding): Combine this match arm with above once #[cfg(dual_funding)] is removed.
6228                                 #[cfg(dual_funding)]
6229                                 ChannelPhase::UnfundedOutboundV2(_) => {
6230                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6231                                         continue;
6232                                 }
6233                         }
6234                 }
6235                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6236         }
6237
6238         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6239                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6240                 // likely to be lost on restart!
6241                 if msg.common_fields.chain_hash != self.chain_hash {
6242                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(),
6243                                  msg.common_fields.temporary_channel_id.clone()));
6244                 }
6245
6246                 if !self.default_configuration.accept_inbound_channels {
6247                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(),
6248                                  msg.common_fields.temporary_channel_id.clone()));
6249                 }
6250
6251                 // Get the number of peers with channels, but without funded ones. We don't care too much
6252                 // about peers that never open a channel, so we filter by peers that have at least one
6253                 // channel, and then limit the number of those with unfunded channels.
6254                 let channeled_peers_without_funding =
6255                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6256
6257                 let per_peer_state = self.per_peer_state.read().unwrap();
6258                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6259                     .ok_or_else(|| {
6260                                 debug_assert!(false);
6261                                 MsgHandleErrInternal::send_err_msg_no_close(
6262                                         format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
6263                                         msg.common_fields.temporary_channel_id.clone())
6264                         })?;
6265                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6266                 let peer_state = &mut *peer_state_lock;
6267
6268                 // If this peer already has some channels, a new channel won't increase our number of peers
6269                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6270                 // channels per-peer we can accept channels from a peer with existing ones.
6271                 if peer_state.total_channel_count() == 0 &&
6272                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6273                         !self.default_configuration.manually_accept_inbound_channels
6274                 {
6275                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6276                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6277                                 msg.common_fields.temporary_channel_id.clone()));
6278                 }
6279
6280                 let best_block_height = self.best_block.read().unwrap().height();
6281                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6282                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6283                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6284                                 msg.common_fields.temporary_channel_id.clone()));
6285                 }
6286
6287                 let channel_id = msg.common_fields.temporary_channel_id;
6288                 let channel_exists = peer_state.has_channel(&channel_id);
6289                 if channel_exists {
6290                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6291                                 "temporary_channel_id collision for the same peer!".to_owned(),
6292                                 msg.common_fields.temporary_channel_id.clone()));
6293                 }
6294
6295                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6296                 if self.default_configuration.manually_accept_inbound_channels {
6297                         let channel_type = channel::channel_type_from_open_channel(
6298                                         &msg.common_fields, &peer_state.latest_features, &self.channel_type_features()
6299                                 ).map_err(|e|
6300                                         MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id)
6301                                 )?;
6302                         let mut pending_events = self.pending_events.lock().unwrap();
6303                         pending_events.push_back((events::Event::OpenChannelRequest {
6304                                 temporary_channel_id: msg.common_fields.temporary_channel_id.clone(),
6305                                 counterparty_node_id: counterparty_node_id.clone(),
6306                                 funding_satoshis: msg.common_fields.funding_satoshis,
6307                                 push_msat: msg.push_msat,
6308                                 channel_type,
6309                         }, None));
6310                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6311                                 open_channel_msg: msg.clone(),
6312                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6313                         });
6314                         return Ok(());
6315                 }
6316
6317                 // Otherwise create the channel right now.
6318                 let mut random_bytes = [0u8; 16];
6319                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6320                 let user_channel_id = u128::from_be_bytes(random_bytes);
6321                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6322                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6323                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6324                 {
6325                         Err(e) => {
6326                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.common_fields.temporary_channel_id));
6327                         },
6328                         Ok(res) => res
6329                 };
6330
6331                 let channel_type = channel.context.get_channel_type();
6332                 if channel_type.requires_zero_conf() {
6333                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6334                                 "No zero confirmation channels accepted".to_owned(),
6335                                 msg.common_fields.temporary_channel_id.clone()));
6336                 }
6337                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6338                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6339                                 "No channels with anchor outputs accepted".to_owned(),
6340                                 msg.common_fields.temporary_channel_id.clone()));
6341                 }
6342
6343                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6344                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6345
6346                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6347                         node_id: counterparty_node_id.clone(),
6348                         msg: channel.accept_inbound_channel(),
6349                 });
6350                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6351                 Ok(())
6352         }
6353
6354         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6355                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6356                 // likely to be lost on restart!
6357                 let (value, output_script, user_id) = {
6358                         let per_peer_state = self.per_peer_state.read().unwrap();
6359                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6360                                 .ok_or_else(|| {
6361                                         debug_assert!(false);
6362                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.common_fields.temporary_channel_id)
6363                                 })?;
6364                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6365                         let peer_state = &mut *peer_state_lock;
6366                         match peer_state.channel_by_id.entry(msg.common_fields.temporary_channel_id) {
6367                                 hash_map::Entry::Occupied(mut phase) => {
6368                                         match phase.get_mut() {
6369                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6370                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6371                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6372                                                 },
6373                                                 _ => {
6374                                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got an unexpected accept_channel message from peer with counterparty_node_id {}", counterparty_node_id), msg.common_fields.temporary_channel_id));
6375                                                 }
6376                                         }
6377                                 },
6378                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.common_fields.temporary_channel_id))
6379                         }
6380                 };
6381                 let mut pending_events = self.pending_events.lock().unwrap();
6382                 pending_events.push_back((events::Event::FundingGenerationReady {
6383                         temporary_channel_id: msg.common_fields.temporary_channel_id,
6384                         counterparty_node_id: *counterparty_node_id,
6385                         channel_value_satoshis: value,
6386                         output_script,
6387                         user_channel_id: user_id,
6388                 }, None));
6389                 Ok(())
6390         }
6391
6392         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6393                 let best_block = *self.best_block.read().unwrap();
6394
6395                 let per_peer_state = self.per_peer_state.read().unwrap();
6396                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6397                         .ok_or_else(|| {
6398                                 debug_assert!(false);
6399                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.temporary_channel_id)
6400                         })?;
6401
6402                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6403                 let peer_state = &mut *peer_state_lock;
6404                 let (mut chan, funding_msg_opt, monitor) =
6405                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6406                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6407                                         let logger = WithChannelContext::from(&self.logger, &inbound_chan.context);
6408                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &&logger) {
6409                                                 Ok(res) => res,
6410                                                 Err((inbound_chan, err)) => {
6411                                                         // We've already removed this inbound channel from the map in `PeerState`
6412                                                         // above so at this point we just need to clean up any lingering entries
6413                                                         // concerning this channel as it is safe to do so.
6414                                                         debug_assert!(matches!(err, ChannelError::Close(_)));
6415                                                         // Really we should be returning the channel_id the peer expects based
6416                                                         // on their funding info here, but they're horribly confused anyway, so
6417                                                         // there's not a lot we can do to save them.
6418                                                         return Err(convert_chan_phase_err!(self, err, &mut ChannelPhase::UnfundedInboundV1(inbound_chan), &msg.temporary_channel_id).1);
6419                                                 },
6420                                         }
6421                                 },
6422                                 Some(mut phase) => {
6423                                         let err_msg = format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id);
6424                                         let err = ChannelError::Close(err_msg);
6425                                         return Err(convert_chan_phase_err!(self, err, &mut phase, &msg.temporary_channel_id).1);
6426                                 },
6427                                 None => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.temporary_channel_id))
6428                         };
6429
6430                 let funded_channel_id = chan.context.channel_id();
6431
6432                 macro_rules! fail_chan { ($err: expr) => { {
6433                         // Note that at this point we've filled in the funding outpoint on our
6434                         // channel, but its actually in conflict with another channel. Thus, if
6435                         // we call `convert_chan_phase_err` immediately (thus calling
6436                         // `update_maps_on_chan_removal`), we'll remove the existing channel
6437                         // from `outpoint_to_peer`. Thus, we must first unset the funding outpoint
6438                         // on the channel.
6439                         let err = ChannelError::Close($err.to_owned());
6440                         chan.unset_funding_info(msg.temporary_channel_id);
6441                         return Err(convert_chan_phase_err!(self, err, chan, &funded_channel_id, UNFUNDED_CHANNEL).1);
6442                 } } }
6443
6444                 match peer_state.channel_by_id.entry(funded_channel_id) {
6445                         hash_map::Entry::Occupied(_) => {
6446                                 fail_chan!("Already had channel with the new channel_id");
6447                         },
6448                         hash_map::Entry::Vacant(e) => {
6449                                 let mut outpoint_to_peer_lock = self.outpoint_to_peer.lock().unwrap();
6450                                 match outpoint_to_peer_lock.entry(monitor.get_funding_txo().0) {
6451                                         hash_map::Entry::Occupied(_) => {
6452                                                 fail_chan!("The funding_created message had the same funding_txid as an existing channel - funding is not possible");
6453                                         },
6454                                         hash_map::Entry::Vacant(i_e) => {
6455                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6456                                                 if let Ok(persist_state) = monitor_res {
6457                                                         i_e.insert(chan.context.get_counterparty_node_id());
6458                                                         mem::drop(outpoint_to_peer_lock);
6459
6460                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6461                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6462                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6463                                                         // until we have persisted our monitor.
6464                                                         if let Some(msg) = funding_msg_opt {
6465                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6466                                                                         node_id: counterparty_node_id.clone(),
6467                                                                         msg,
6468                                                                 });
6469                                                         }
6470
6471                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6472                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6473                                                                         per_peer_state, chan, INITIAL_MONITOR);
6474                                                         } else {
6475                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6476                                                         }
6477                                                         Ok(())
6478                                                 } else {
6479                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6480                                                         log_error!(logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6481                                                         fail_chan!("Duplicate funding outpoint");
6482                                                 }
6483                                         }
6484                                 }
6485                         }
6486                 }
6487         }
6488
6489         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6490                 let best_block = *self.best_block.read().unwrap();
6491                 let per_peer_state = self.per_peer_state.read().unwrap();
6492                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6493                         .ok_or_else(|| {
6494                                 debug_assert!(false);
6495                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6496                         })?;
6497
6498                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6499                 let peer_state = &mut *peer_state_lock;
6500                 match peer_state.channel_by_id.entry(msg.channel_id) {
6501                         hash_map::Entry::Occupied(chan_phase_entry) => {
6502                                 if matches!(chan_phase_entry.get(), ChannelPhase::UnfundedOutboundV1(_)) {
6503                                         let chan = if let ChannelPhase::UnfundedOutboundV1(chan) = chan_phase_entry.remove() { chan } else { unreachable!() };
6504                                         let logger = WithContext::from(
6505                                                 &self.logger,
6506                                                 Some(chan.context.get_counterparty_node_id()),
6507                                                 Some(chan.context.channel_id())
6508                                         );
6509                                         let res =
6510                                                 chan.funding_signed(&msg, best_block, &self.signer_provider, &&logger);
6511                                         match res {
6512                                                 Ok((mut chan, monitor)) => {
6513                                                         if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6514                                                                 // We really should be able to insert here without doing a second
6515                                                                 // lookup, but sadly rust stdlib doesn't currently allow keeping
6516                                                                 // the original Entry around with the value removed.
6517                                                                 let mut chan = peer_state.channel_by_id.entry(msg.channel_id).or_insert(ChannelPhase::Funded(chan));
6518                                                                 if let ChannelPhase::Funded(ref mut chan) = &mut chan {
6519                                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6520                                                                 } else { unreachable!(); }
6521                                                                 Ok(())
6522                                                         } else {
6523                                                                 let e = ChannelError::Close("Channel funding outpoint was a duplicate".to_owned());
6524                                                                 // We weren't able to watch the channel to begin with, so no
6525                                                                 // updates should be made on it. Previously, full_stack_target
6526                                                                 // found an (unreachable) panic when the monitor update contained
6527                                                                 // within `shutdown_finish` was applied.
6528                                                                 chan.unset_funding_info(msg.channel_id);
6529                                                                 return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::Funded(chan), &msg.channel_id).1);
6530                                                         }
6531                                                 },
6532                                                 Err((chan, e)) => {
6533                                                         debug_assert!(matches!(e, ChannelError::Close(_)),
6534                                                                 "We don't have a channel anymore, so the error better have expected close");
6535                                                         // We've already removed this outbound channel from the map in
6536                                                         // `PeerState` above so at this point we just need to clean up any
6537                                                         // lingering entries concerning this channel as it is safe to do so.
6538                                                         return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::UnfundedOutboundV1(chan), &msg.channel_id).1);
6539                                                 }
6540                                         }
6541                                 } else {
6542                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6543                                 }
6544                         },
6545                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6546                 }
6547         }
6548
6549         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6550                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6551                 // closing a channel), so any changes are likely to be lost on restart!
6552                 let per_peer_state = self.per_peer_state.read().unwrap();
6553                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6554                         .ok_or_else(|| {
6555                                 debug_assert!(false);
6556                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6557                         })?;
6558                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6559                 let peer_state = &mut *peer_state_lock;
6560                 match peer_state.channel_by_id.entry(msg.channel_id) {
6561                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6562                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6563                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6564                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6565                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &&logger), chan_phase_entry);
6566                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6567                                                 log_trace!(logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6568                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6569                                                         node_id: counterparty_node_id.clone(),
6570                                                         msg: announcement_sigs,
6571                                                 });
6572                                         } else if chan.context.is_usable() {
6573                                                 // If we're sending an announcement_signatures, we'll send the (public)
6574                                                 // channel_update after sending a channel_announcement when we receive our
6575                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6576                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6577                                                 // announcement_signatures.
6578                                                 log_trace!(logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6579                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6580                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6581                                                                 node_id: counterparty_node_id.clone(),
6582                                                                 msg,
6583                                                         });
6584                                                 }
6585                                         }
6586
6587                                         {
6588                                                 let mut pending_events = self.pending_events.lock().unwrap();
6589                                                 emit_channel_ready_event!(pending_events, chan);
6590                                         }
6591
6592                                         Ok(())
6593                                 } else {
6594                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6595                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6596                                 }
6597                         },
6598                         hash_map::Entry::Vacant(_) => {
6599                                 Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6600                         }
6601                 }
6602         }
6603
6604         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6605                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6606                 let mut finish_shutdown = None;
6607                 {
6608                         let per_peer_state = self.per_peer_state.read().unwrap();
6609                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6610                                 .ok_or_else(|| {
6611                                         debug_assert!(false);
6612                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6613                                 })?;
6614                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6615                         let peer_state = &mut *peer_state_lock;
6616                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6617                                 let phase = chan_phase_entry.get_mut();
6618                                 match phase {
6619                                         ChannelPhase::Funded(chan) => {
6620                                                 if !chan.received_shutdown() {
6621                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6622                                                         log_info!(logger, "Received a shutdown message from our counterparty for channel {}{}.",
6623                                                                 msg.channel_id,
6624                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6625                                                 }
6626
6627                                                 let funding_txo_opt = chan.context.get_funding_txo();
6628                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6629                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6630                                                 dropped_htlcs = htlcs;
6631
6632                                                 if let Some(msg) = shutdown {
6633                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6634                                                         // here as we don't need the monitor update to complete until we send a
6635                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6636                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6637                                                                 node_id: *counterparty_node_id,
6638                                                                 msg,
6639                                                         });
6640                                                 }
6641                                                 // Update the monitor with the shutdown script if necessary.
6642                                                 if let Some(monitor_update) = monitor_update_opt {
6643                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), monitor_update,
6644                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6645                                                 }
6646                                         },
6647                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6648                                                 let context = phase.context_mut();
6649                                                 let logger = WithChannelContext::from(&self.logger, context);
6650                                                 log_error!(logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6651                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6652                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false, ClosureReason::CounterpartyCoopClosedUnfundedChannel));
6653                                         },
6654                                         // TODO(dual_funding): Combine this match arm with above.
6655                                         #[cfg(dual_funding)]
6656                                         ChannelPhase::UnfundedInboundV2(_) | ChannelPhase::UnfundedOutboundV2(_) => {
6657                                                 let context = phase.context_mut();
6658                                                 log_error!(self.logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6659                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6660                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false, ClosureReason::CounterpartyCoopClosedUnfundedChannel));
6661                                         },
6662                                 }
6663                         } else {
6664                                 return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6665                         }
6666                 }
6667                 for htlc_source in dropped_htlcs.drain(..) {
6668                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6669                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6670                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6671                 }
6672                 if let Some(shutdown_res) = finish_shutdown {
6673                         self.finish_close_channel(shutdown_res);
6674                 }
6675
6676                 Ok(())
6677         }
6678
6679         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6680                 let per_peer_state = self.per_peer_state.read().unwrap();
6681                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6682                         .ok_or_else(|| {
6683                                 debug_assert!(false);
6684                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6685                         })?;
6686                 let (tx, chan_option, shutdown_result) = {
6687                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6688                         let peer_state = &mut *peer_state_lock;
6689                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6690                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6691                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6692                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6693                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6694                                                 if let Some(msg) = closing_signed {
6695                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6696                                                                 node_id: counterparty_node_id.clone(),
6697                                                                 msg,
6698                                                         });
6699                                                 }
6700                                                 if tx.is_some() {
6701                                                         // We're done with this channel, we've got a signed closing transaction and
6702                                                         // will send the closing_signed back to the remote peer upon return. This
6703                                                         // also implies there are no pending HTLCs left on the channel, so we can
6704                                                         // fully delete it from tracking (the channel monitor is still around to
6705                                                         // watch for old state broadcasts)!
6706                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6707                                                 } else { (tx, None, shutdown_result) }
6708                                         } else {
6709                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6710                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6711                                         }
6712                                 },
6713                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6714                         }
6715                 };
6716                 if let Some(broadcast_tx) = tx {
6717                         let channel_id = chan_option.as_ref().map(|channel| channel.context().channel_id());
6718                         log_info!(WithContext::from(&self.logger, Some(*counterparty_node_id), channel_id), "Broadcasting {}", log_tx!(broadcast_tx));
6719                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6720                 }
6721                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6722                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6723                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6724                                 let peer_state = &mut *peer_state_lock;
6725                                 peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
6726                                         msg: update
6727                                 });
6728                         }
6729                 }
6730                 mem::drop(per_peer_state);
6731                 if let Some(shutdown_result) = shutdown_result {
6732                         self.finish_close_channel(shutdown_result);
6733                 }
6734                 Ok(())
6735         }
6736
6737         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6738                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6739                 //determine the state of the payment based on our response/if we forward anything/the time
6740                 //we take to respond. We should take care to avoid allowing such an attack.
6741                 //
6742                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6743                 //us repeatedly garbled in different ways, and compare our error messages, which are
6744                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6745                 //but we should prevent it anyway.
6746
6747                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6748                 // closing a channel), so any changes are likely to be lost on restart!
6749
6750                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg, counterparty_node_id);
6751                 let per_peer_state = self.per_peer_state.read().unwrap();
6752                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6753                         .ok_or_else(|| {
6754                                 debug_assert!(false);
6755                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6756                         })?;
6757                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6758                 let peer_state = &mut *peer_state_lock;
6759                 match peer_state.channel_by_id.entry(msg.channel_id) {
6760                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6761                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6762                                         let pending_forward_info = match decoded_hop_res {
6763                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6764                                                         self.construct_pending_htlc_status(
6765                                                                 msg, counterparty_node_id, shared_secret, next_hop,
6766                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt,
6767                                                         ),
6768                                                 Err(e) => PendingHTLCStatus::Fail(e)
6769                                         };
6770                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6771                                                 if msg.blinding_point.is_some() {
6772                                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
6773                                                                         msgs::UpdateFailMalformedHTLC {
6774                                                                                 channel_id: msg.channel_id,
6775                                                                                 htlc_id: msg.htlc_id,
6776                                                                                 sha256_of_onion: [0; 32],
6777                                                                                 failure_code: INVALID_ONION_BLINDING,
6778                                                                         }
6779                                                         ))
6780                                                 }
6781                                                 // If the update_add is completely bogus, the call will Err and we will close,
6782                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6783                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6784                                                 match pending_forward_info {
6785                                                         PendingHTLCStatus::Forward(PendingHTLCInfo {
6786                                                                 ref incoming_shared_secret, ref routing, ..
6787                                                         }) => {
6788                                                                 let reason = if routing.blinded_failure().is_some() {
6789                                                                         HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32])
6790                                                                 } else if (error_code & 0x1000) != 0 {
6791                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6792                                                                         HTLCFailReason::reason(real_code, error_data)
6793                                                                 } else {
6794                                                                         HTLCFailReason::from_failure_code(error_code)
6795                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6796                                                                 let msg = msgs::UpdateFailHTLC {
6797                                                                         channel_id: msg.channel_id,
6798                                                                         htlc_id: msg.htlc_id,
6799                                                                         reason
6800                                                                 };
6801                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6802                                                         },
6803                                                         _ => pending_forward_info
6804                                                 }
6805                                         };
6806                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6807                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &&logger), chan_phase_entry);
6808                                 } else {
6809                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6810                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6811                                 }
6812                         },
6813                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6814                 }
6815                 Ok(())
6816         }
6817
6818         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6819                 let funding_txo;
6820                 let (htlc_source, forwarded_htlc_value, skimmed_fee_msat) = {
6821                         let per_peer_state = self.per_peer_state.read().unwrap();
6822                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6823                                 .ok_or_else(|| {
6824                                         debug_assert!(false);
6825                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6826                                 })?;
6827                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6828                         let peer_state = &mut *peer_state_lock;
6829                         match peer_state.channel_by_id.entry(msg.channel_id) {
6830                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6831                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6832                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6833                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6834                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6835                                                         log_trace!(logger,
6836                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6837                                                                 msg.channel_id);
6838                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6839                                                                 .or_insert_with(Vec::new)
6840                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6841                                                 }
6842                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6843                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6844                                                 // We do this instead in the `claim_funds_internal` by attaching a
6845                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6846                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6847                                                 // process the RAA as messages are processed from single peers serially.
6848                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6849                                                 res
6850                                         } else {
6851                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6852                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6853                                         }
6854                                 },
6855                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6856                         }
6857                 };
6858                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(),
6859                         Some(forwarded_htlc_value), skimmed_fee_msat, false, false, Some(*counterparty_node_id),
6860                         funding_txo, msg.channel_id
6861                 );
6862
6863                 Ok(())
6864         }
6865
6866         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6867                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6868                 // closing a channel), so any changes are likely to be lost on restart!
6869                 let per_peer_state = self.per_peer_state.read().unwrap();
6870                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6871                         .ok_or_else(|| {
6872                                 debug_assert!(false);
6873                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6874                         })?;
6875                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6876                 let peer_state = &mut *peer_state_lock;
6877                 match peer_state.channel_by_id.entry(msg.channel_id) {
6878                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6879                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6880                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6881                                 } else {
6882                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6883                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6884                                 }
6885                         },
6886                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6887                 }
6888                 Ok(())
6889         }
6890
6891         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6892                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6893                 // closing a channel), so any changes are likely to be lost on restart!
6894                 let per_peer_state = self.per_peer_state.read().unwrap();
6895                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6896                         .ok_or_else(|| {
6897                                 debug_assert!(false);
6898                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6899                         })?;
6900                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6901                 let peer_state = &mut *peer_state_lock;
6902                 match peer_state.channel_by_id.entry(msg.channel_id) {
6903                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6904                                 if (msg.failure_code & 0x8000) == 0 {
6905                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6906                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6907                                 }
6908                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6909                                         try_chan_phase_entry!(self, chan.update_fail_malformed_htlc(&msg, HTLCFailReason::reason(msg.failure_code, msg.sha256_of_onion.to_vec())), chan_phase_entry);
6910                                 } else {
6911                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6912                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6913                                 }
6914                                 Ok(())
6915                         },
6916                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6917                 }
6918         }
6919
6920         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6921                 let per_peer_state = self.per_peer_state.read().unwrap();
6922                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6923                         .ok_or_else(|| {
6924                                 debug_assert!(false);
6925                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6926                         })?;
6927                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6928                 let peer_state = &mut *peer_state_lock;
6929                 match peer_state.channel_by_id.entry(msg.channel_id) {
6930                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6931                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6932                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6933                                         let funding_txo = chan.context.get_funding_txo();
6934                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &&logger), chan_phase_entry);
6935                                         if let Some(monitor_update) = monitor_update_opt {
6936                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
6937                                                         peer_state, per_peer_state, chan);
6938                                         }
6939                                         Ok(())
6940                                 } else {
6941                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6942                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6943                                 }
6944                         },
6945                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
6946                 }
6947         }
6948
6949         #[inline]
6950         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6951                 for &mut (prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_user_channel_id, ref mut pending_forwards) in per_source_pending_forwards {
6952                         let mut push_forward_event = false;
6953                         let mut new_intercept_events = VecDeque::new();
6954                         let mut failed_intercept_forwards = Vec::new();
6955                         if !pending_forwards.is_empty() {
6956                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6957                                         let scid = match forward_info.routing {
6958                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6959                                                 PendingHTLCRouting::Receive { .. } => 0,
6960                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6961                                         };
6962                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6963                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6964
6965                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6966                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6967                                         match forward_htlcs.entry(scid) {
6968                                                 hash_map::Entry::Occupied(mut entry) => {
6969                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6970                                                                 prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_htlc_id, prev_user_channel_id, forward_info }));
6971                                                 },
6972                                                 hash_map::Entry::Vacant(entry) => {
6973                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6974                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6975                                                         {
6976                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).to_byte_array());
6977                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6978                                                                 match pending_intercepts.entry(intercept_id) {
6979                                                                         hash_map::Entry::Vacant(entry) => {
6980                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6981                                                                                         requested_next_hop_scid: scid,
6982                                                                                         payment_hash: forward_info.payment_hash,
6983                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6984                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6985                                                                                         intercept_id
6986                                                                                 }, None));
6987                                                                                 entry.insert(PendingAddHTLCInfo {
6988                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_htlc_id, prev_user_channel_id, forward_info });
6989                                                                         },
6990                                                                         hash_map::Entry::Occupied(_) => {
6991                                                                                 let logger = WithContext::from(&self.logger, None, Some(prev_channel_id));
6992                                                                                 log_info!(logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6993                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6994                                                                                         short_channel_id: prev_short_channel_id,
6995                                                                                         user_channel_id: Some(prev_user_channel_id),
6996                                                                                         outpoint: prev_funding_outpoint,
6997                                                                                         channel_id: prev_channel_id,
6998                                                                                         htlc_id: prev_htlc_id,
6999                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
7000                                                                                         phantom_shared_secret: None,
7001                                                                                         blinded_failure: forward_info.routing.blinded_failure(),
7002                                                                                 });
7003
7004                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
7005                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
7006                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
7007                                                                                 ));
7008                                                                         }
7009                                                                 }
7010                                                         } else {
7011                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
7012                                                                 // payments are being processed.
7013                                                                 if forward_htlcs_empty {
7014                                                                         push_forward_event = true;
7015                                                                 }
7016                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
7017                                                                         prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_htlc_id, prev_user_channel_id, forward_info })));
7018                                                         }
7019                                                 }
7020                                         }
7021                                 }
7022                         }
7023
7024                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
7025                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
7026                         }
7027
7028                         if !new_intercept_events.is_empty() {
7029                                 let mut events = self.pending_events.lock().unwrap();
7030                                 events.append(&mut new_intercept_events);
7031                         }
7032                         if push_forward_event { self.push_pending_forwards_ev() }
7033                 }
7034         }
7035
7036         fn push_pending_forwards_ev(&self) {
7037                 let mut pending_events = self.pending_events.lock().unwrap();
7038                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
7039                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
7040                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
7041                 ).count();
7042                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
7043                 // events is done in batches and they are not removed until we're done processing each
7044                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
7045                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
7046                 // payments will need an additional forwarding event before being claimed to make them look
7047                 // real by taking more time.
7048                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
7049                         pending_events.push_back((Event::PendingHTLCsForwardable {
7050                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
7051                         }, None));
7052                 }
7053         }
7054
7055         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
7056         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
7057         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
7058         /// the [`ChannelMonitorUpdate`] in question.
7059         fn raa_monitor_updates_held(&self,
7060                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
7061                 channel_funding_outpoint: OutPoint, channel_id: ChannelId, counterparty_node_id: PublicKey
7062         ) -> bool {
7063                 actions_blocking_raa_monitor_updates
7064                         .get(&channel_id).map(|v| !v.is_empty()).unwrap_or(false)
7065                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
7066                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
7067                                 channel_funding_outpoint,
7068                                 channel_id,
7069                                 counterparty_node_id,
7070                         })
7071                 })
7072         }
7073
7074         #[cfg(any(test, feature = "_test_utils"))]
7075         pub(crate) fn test_raa_monitor_updates_held(&self,
7076                 counterparty_node_id: PublicKey, channel_id: ChannelId
7077         ) -> bool {
7078                 let per_peer_state = self.per_peer_state.read().unwrap();
7079                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7080                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7081                         let peer_state = &mut *peer_state_lck;
7082
7083                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
7084                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7085                                         chan.context().get_funding_txo().unwrap(), channel_id, counterparty_node_id);
7086                         }
7087                 }
7088                 false
7089         }
7090
7091         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
7092                 let htlcs_to_fail = {
7093                         let per_peer_state = self.per_peer_state.read().unwrap();
7094                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
7095                                 .ok_or_else(|| {
7096                                         debug_assert!(false);
7097                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7098                                 }).map(|mtx| mtx.lock().unwrap())?;
7099                         let peer_state = &mut *peer_state_lock;
7100                         match peer_state.channel_by_id.entry(msg.channel_id) {
7101                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7102                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7103                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
7104                                                 let funding_txo_opt = chan.context.get_funding_txo();
7105                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
7106                                                         self.raa_monitor_updates_held(
7107                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo, msg.channel_id,
7108                                                                 *counterparty_node_id)
7109                                                 } else { false };
7110                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
7111                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &&logger, mon_update_blocked), chan_phase_entry);
7112                                                 if let Some(monitor_update) = monitor_update_opt {
7113                                                         let funding_txo = funding_txo_opt
7114                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
7115                                                         handle_new_monitor_update!(self, funding_txo, monitor_update,
7116                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7117                                                 }
7118                                                 htlcs_to_fail
7119                                         } else {
7120                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7121                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
7122                                         }
7123                                 },
7124                                 hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
7125                         }
7126                 };
7127                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
7128                 Ok(())
7129         }
7130
7131         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
7132                 let per_peer_state = self.per_peer_state.read().unwrap();
7133                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7134                         .ok_or_else(|| {
7135                                 debug_assert!(false);
7136                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7137                         })?;
7138                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7139                 let peer_state = &mut *peer_state_lock;
7140                 match peer_state.channel_by_id.entry(msg.channel_id) {
7141                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7142                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7143                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7144                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &&logger), chan_phase_entry);
7145                                 } else {
7146                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7147                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
7148                                 }
7149                         },
7150                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
7151                 }
7152                 Ok(())
7153         }
7154
7155         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
7156                 let per_peer_state = self.per_peer_state.read().unwrap();
7157                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7158                         .ok_or_else(|| {
7159                                 debug_assert!(false);
7160                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7161                         })?;
7162                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7163                 let peer_state = &mut *peer_state_lock;
7164                 match peer_state.channel_by_id.entry(msg.channel_id) {
7165                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7166                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7167                                         if !chan.context.is_usable() {
7168                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
7169                                         }
7170
7171                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7172                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
7173                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
7174                                                         msg, &self.default_configuration
7175                                                 ), chan_phase_entry),
7176                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7177                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7178                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
7179                                         });
7180                                 } else {
7181                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7182                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
7183                                 }
7184                         },
7185                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close(format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}", counterparty_node_id), msg.channel_id))
7186                 }
7187                 Ok(())
7188         }
7189
7190         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
7191         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
7192                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
7193                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
7194                         None => {
7195                                 // It's not a local channel
7196                                 return Ok(NotifyOption::SkipPersistNoEvents)
7197                         }
7198                 };
7199                 let per_peer_state = self.per_peer_state.read().unwrap();
7200                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
7201                 if peer_state_mutex_opt.is_none() {
7202                         return Ok(NotifyOption::SkipPersistNoEvents)
7203                 }
7204                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7205                 let peer_state = &mut *peer_state_lock;
7206                 match peer_state.channel_by_id.entry(chan_id) {
7207                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7208                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7209                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
7210                                                 if chan.context.should_announce() {
7211                                                         // If the announcement is about a channel of ours which is public, some
7212                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
7213                                                         // a scary-looking error message and return Ok instead.
7214                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7215                                                 }
7216                                                 return Err(MsgHandleErrInternal::send_err_msg_no_close("Got a channel_update for a channel from the wrong node - it shouldn't know about our private channels!".to_owned(), chan_id));
7217                                         }
7218                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
7219                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
7220                                         if were_node_one == msg_from_node_one {
7221                                                 return Ok(NotifyOption::SkipPersistNoEvents);
7222                                         } else {
7223                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
7224                                                 log_debug!(logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
7225                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
7226                                                 // If nothing changed after applying their update, we don't need to bother
7227                                                 // persisting.
7228                                                 if !did_change {
7229                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7230                                                 }
7231                                         }
7232                                 } else {
7233                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7234                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
7235                                 }
7236                         },
7237                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
7238                 }
7239                 Ok(NotifyOption::DoPersist)
7240         }
7241
7242         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
7243                 let htlc_forwards;
7244                 let need_lnd_workaround = {
7245                         let per_peer_state = self.per_peer_state.read().unwrap();
7246
7247                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7248                                 .ok_or_else(|| {
7249                                         debug_assert!(false);
7250                                         MsgHandleErrInternal::send_err_msg_no_close(
7251                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
7252                                                 msg.channel_id
7253                                         )
7254                                 })?;
7255                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
7256                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7257                         let peer_state = &mut *peer_state_lock;
7258                         match peer_state.channel_by_id.entry(msg.channel_id) {
7259                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7260                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7261                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
7262                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
7263                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
7264                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
7265                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
7266                                                         msg, &&logger, &self.node_signer, self.chain_hash,
7267                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
7268                                                 let mut channel_update = None;
7269                                                 if let Some(msg) = responses.shutdown_msg {
7270                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
7271                                                                 node_id: counterparty_node_id.clone(),
7272                                                                 msg,
7273                                                         });
7274                                                 } else if chan.context.is_usable() {
7275                                                         // If the channel is in a usable state (ie the channel is not being shut
7276                                                         // down), send a unicast channel_update to our counterparty to make sure
7277                                                         // they have the latest channel parameters.
7278                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7279                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7280                                                                         node_id: chan.context.get_counterparty_node_id(),
7281                                                                         msg,
7282                                                                 });
7283                                                         }
7284                                                 }
7285                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7286                                                 htlc_forwards = self.handle_channel_resumption(
7287                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7288                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7289                                                 if let Some(upd) = channel_update {
7290                                                         peer_state.pending_msg_events.push(upd);
7291                                                 }
7292                                                 need_lnd_workaround
7293                                         } else {
7294                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7295                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7296                                         }
7297                                 },
7298                                 hash_map::Entry::Vacant(_) => {
7299                                         log_debug!(logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7300                                                 msg.channel_id);
7301                                         // Unfortunately, lnd doesn't force close on errors
7302                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7303                                         // One of the few ways to get an lnd counterparty to force close is by
7304                                         // replicating what they do when restoring static channel backups (SCBs). They
7305                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7306                                         // invalid `your_last_per_commitment_secret`.
7307                                         //
7308                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7309                                         // can assume it's likely the channel closed from our point of view, but it
7310                                         // remains open on the counterparty's side. By sending this bogus
7311                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7312                                         // force close broadcasting their latest state. If the closing transaction from
7313                                         // our point of view remains unconfirmed, it'll enter a race with the
7314                                         // counterparty's to-be-broadcast latest commitment transaction.
7315                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7316                                                 node_id: *counterparty_node_id,
7317                                                 msg: msgs::ChannelReestablish {
7318                                                         channel_id: msg.channel_id,
7319                                                         next_local_commitment_number: 0,
7320                                                         next_remote_commitment_number: 0,
7321                                                         your_last_per_commitment_secret: [1u8; 32],
7322                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7323                                                         next_funding_txid: None,
7324                                                 },
7325                                         });
7326                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7327                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7328                                                         counterparty_node_id), msg.channel_id)
7329                                         )
7330                                 }
7331                         }
7332                 };
7333
7334                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7335                 if let Some(forwards) = htlc_forwards {
7336                         self.forward_htlcs(&mut [forwards][..]);
7337                         persist = NotifyOption::DoPersist;
7338                 }
7339
7340                 if let Some(channel_ready_msg) = need_lnd_workaround {
7341                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7342                 }
7343                 Ok(persist)
7344         }
7345
7346         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7347         fn process_pending_monitor_events(&self) -> bool {
7348                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7349
7350                 let mut failed_channels = Vec::new();
7351                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7352                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7353                 for (funding_outpoint, channel_id, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7354                         for monitor_event in monitor_events.drain(..) {
7355                                 match monitor_event {
7356                                         MonitorEvent::HTLCEvent(htlc_update) => {
7357                                                 let logger = WithContext::from(&self.logger, counterparty_node_id, Some(channel_id));
7358                                                 if let Some(preimage) = htlc_update.payment_preimage {
7359                                                         log_trace!(logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7360                                                         self.claim_funds_internal(htlc_update.source, preimage,
7361                                                                 htlc_update.htlc_value_satoshis.map(|v| v * 1000), None, true,
7362                                                                 false, counterparty_node_id, funding_outpoint, channel_id);
7363                                                 } else {
7364                                                         log_trace!(logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7365                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id };
7366                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7367                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7368                                                 }
7369                                         },
7370                                         MonitorEvent::HolderForceClosed(_funding_outpoint) => {
7371                                                 let counterparty_node_id_opt = match counterparty_node_id {
7372                                                         Some(cp_id) => Some(cp_id),
7373                                                         None => {
7374                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7375                                                                 // monitor event, this and the outpoint_to_peer map should be removed.
7376                                                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
7377                                                                 outpoint_to_peer.get(&funding_outpoint).cloned()
7378                                                         }
7379                                                 };
7380                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7381                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7382                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7383                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7384                                                                 let peer_state = &mut *peer_state_lock;
7385                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7386                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id) {
7387                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7388                                                                                 failed_channels.push(chan.context.force_shutdown(false, ClosureReason::HolderForceClosed));
7389                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7390                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7391                                                                                                 msg: update
7392                                                                                         });
7393                                                                                 }
7394                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7395                                                                                         node_id: chan.context.get_counterparty_node_id(),
7396                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7397                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7398                                                                                         },
7399                                                                                 });
7400                                                                         }
7401                                                                 }
7402                                                         }
7403                                                 }
7404                                         },
7405                                         MonitorEvent::Completed { funding_txo, channel_id, monitor_update_id } => {
7406                                                 self.channel_monitor_updated(&funding_txo, &channel_id, monitor_update_id, counterparty_node_id.as_ref());
7407                                         },
7408                                 }
7409                         }
7410                 }
7411
7412                 for failure in failed_channels.drain(..) {
7413                         self.finish_close_channel(failure);
7414                 }
7415
7416                 has_pending_monitor_events
7417         }
7418
7419         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7420         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7421         /// update events as a separate process method here.
7422         #[cfg(fuzzing)]
7423         pub fn process_monitor_events(&self) {
7424                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7425                 self.process_pending_monitor_events();
7426         }
7427
7428         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7429         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7430         /// update was applied.
7431         fn check_free_holding_cells(&self) -> bool {
7432                 let mut has_monitor_update = false;
7433                 let mut failed_htlcs = Vec::new();
7434
7435                 // Walk our list of channels and find any that need to update. Note that when we do find an
7436                 // update, if it includes actions that must be taken afterwards, we have to drop the
7437                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7438                 // manage to go through all our peers without finding a single channel to update.
7439                 'peer_loop: loop {
7440                         let per_peer_state = self.per_peer_state.read().unwrap();
7441                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7442                                 'chan_loop: loop {
7443                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7444                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7445                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7446                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7447                                         ) {
7448                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7449                                                 let funding_txo = chan.context.get_funding_txo();
7450                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7451                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &&WithChannelContext::from(&self.logger, &chan.context));
7452                                                 if !holding_cell_failed_htlcs.is_empty() {
7453                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7454                                                 }
7455                                                 if let Some(monitor_update) = monitor_opt {
7456                                                         has_monitor_update = true;
7457
7458                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
7459                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7460                                                         continue 'peer_loop;
7461                                                 }
7462                                         }
7463                                         break 'chan_loop;
7464                                 }
7465                         }
7466                         break 'peer_loop;
7467                 }
7468
7469                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7470                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7471                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7472                 }
7473
7474                 has_update
7475         }
7476
7477         /// When a call to a [`ChannelSigner`] method returns an error, this indicates that the signer
7478         /// is (temporarily) unavailable, and the operation should be retried later.
7479         ///
7480         /// This method allows for that retry - either checking for any signer-pending messages to be
7481         /// attempted in every channel, or in the specifically provided channel.
7482         ///
7483         /// [`ChannelSigner`]: crate::sign::ChannelSigner
7484         #[cfg(async_signing)]
7485         pub fn signer_unblocked(&self, channel_opt: Option<(PublicKey, ChannelId)>) {
7486                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7487
7488                 let unblock_chan = |phase: &mut ChannelPhase<SP>, pending_msg_events: &mut Vec<MessageSendEvent>| {
7489                         let node_id = phase.context().get_counterparty_node_id();
7490                         match phase {
7491                                 ChannelPhase::Funded(chan) => {
7492                                         let msgs = chan.signer_maybe_unblocked(&self.logger);
7493                                         if let Some(updates) = msgs.commitment_update {
7494                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
7495                                                         node_id,
7496                                                         updates,
7497                                                 });
7498                                         }
7499                                         if let Some(msg) = msgs.funding_signed {
7500                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
7501                                                         node_id,
7502                                                         msg,
7503                                                 });
7504                                         }
7505                                         if let Some(msg) = msgs.channel_ready {
7506                                                 send_channel_ready!(self, pending_msg_events, chan, msg);
7507                                         }
7508                                 }
7509                                 ChannelPhase::UnfundedOutboundV1(chan) => {
7510                                         if let Some(msg) = chan.signer_maybe_unblocked(&self.logger) {
7511                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
7512                                                         node_id,
7513                                                         msg,
7514                                                 });
7515                                         }
7516                                 }
7517                                 ChannelPhase::UnfundedInboundV1(_) => {},
7518                         }
7519                 };
7520
7521                 let per_peer_state = self.per_peer_state.read().unwrap();
7522                 if let Some((counterparty_node_id, channel_id)) = channel_opt {
7523                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7524                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7525                                 let peer_state = &mut *peer_state_lock;
7526                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
7527                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7528                                 }
7529                         }
7530                 } else {
7531                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7532                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7533                                 let peer_state = &mut *peer_state_lock;
7534                                 for (_, chan) in peer_state.channel_by_id.iter_mut() {
7535                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7536                                 }
7537                         }
7538                 }
7539         }
7540
7541         /// Check whether any channels have finished removing all pending updates after a shutdown
7542         /// exchange and can now send a closing_signed.
7543         /// Returns whether any closing_signed messages were generated.
7544         fn maybe_generate_initial_closing_signed(&self) -> bool {
7545                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7546                 let mut has_update = false;
7547                 let mut shutdown_results = Vec::new();
7548                 {
7549                         let per_peer_state = self.per_peer_state.read().unwrap();
7550
7551                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7552                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7553                                 let peer_state = &mut *peer_state_lock;
7554                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7555                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7556                                         match phase {
7557                                                 ChannelPhase::Funded(chan) => {
7558                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7559                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &&logger) {
7560                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7561                                                                         if let Some(msg) = msg_opt {
7562                                                                                 has_update = true;
7563                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7564                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7565                                                                                 });
7566                                                                         }
7567                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7568                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7569                                                                                 shutdown_results.push(shutdown_result);
7570                                                                         }
7571                                                                         if let Some(tx) = tx_opt {
7572                                                                                 // We're done with this channel. We got a closing_signed and sent back
7573                                                                                 // a closing_signed with a closing transaction to broadcast.
7574                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7575                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
7576                                                                                                 msg: update
7577                                                                                         });
7578                                                                                 }
7579
7580                                                                                 log_info!(logger, "Broadcasting {}", log_tx!(tx));
7581                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7582                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7583                                                                                 false
7584                                                                         } else { true }
7585                                                                 },
7586                                                                 Err(e) => {
7587                                                                         has_update = true;
7588                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7589                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7590                                                                         !close_channel
7591                                                                 }
7592                                                         }
7593                                                 },
7594                                                 _ => true, // Retain unfunded channels if present.
7595                                         }
7596                                 });
7597                         }
7598                 }
7599
7600                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7601                         let _ = handle_error!(self, err, counterparty_node_id);
7602                 }
7603
7604                 for shutdown_result in shutdown_results.drain(..) {
7605                         self.finish_close_channel(shutdown_result);
7606                 }
7607
7608                 has_update
7609         }
7610
7611         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7612         /// pushing the channel monitor update (if any) to the background events queue and removing the
7613         /// Channel object.
7614         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7615                 for mut failure in failed_channels.drain(..) {
7616                         // Either a commitment transactions has been confirmed on-chain or
7617                         // Channel::block_disconnected detected that the funding transaction has been
7618                         // reorganized out of the main chain.
7619                         // We cannot broadcast our latest local state via monitor update (as
7620                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7621                         // so we track the update internally and handle it when the user next calls
7622                         // timer_tick_occurred, guaranteeing we're running normally.
7623                         if let Some((counterparty_node_id, funding_txo, channel_id, update)) = failure.monitor_update.take() {
7624                                 assert_eq!(update.updates.len(), 1);
7625                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7626                                         assert!(should_broadcast);
7627                                 } else { unreachable!(); }
7628                                 self.pending_background_events.lock().unwrap().push(
7629                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7630                                                 counterparty_node_id, funding_txo, update, channel_id,
7631                                         });
7632                         }
7633                         self.finish_close_channel(failure);
7634                 }
7635         }
7636
7637         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7638         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7639         /// not have an expiration unless otherwise set on the builder.
7640         ///
7641         /// # Privacy
7642         ///
7643         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the offer.
7644         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7645         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7646         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7647         /// order to send the [`InvoiceRequest`].
7648         ///
7649         /// Also, uses a derived signing pubkey in the offer for recipient privacy.
7650         ///
7651         /// # Limitations
7652         ///
7653         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7654         /// reply path.
7655         ///
7656         /// # Errors
7657         ///
7658         /// Errors if the parameterized [`Router`] is unable to create a blinded path for the offer.
7659         ///
7660         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7661         ///
7662         /// [`Offer`]: crate::offers::offer::Offer
7663         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7664         pub fn create_offer_builder(
7665                 &self, description: String
7666         ) -> Result<OfferBuilder<DerivedMetadata, secp256k1::All>, Bolt12SemanticError> {
7667                 let node_id = self.get_our_node_id();
7668                 let expanded_key = &self.inbound_payment_key;
7669                 let entropy = &*self.entropy_source;
7670                 let secp_ctx = &self.secp_ctx;
7671
7672                 let path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7673                 let builder = OfferBuilder::deriving_signing_pubkey(
7674                         description, node_id, expanded_key, entropy, secp_ctx
7675                 )
7676                         .chain_hash(self.chain_hash)
7677                         .path(path);
7678
7679                 Ok(builder)
7680         }
7681
7682         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7683         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7684         ///
7685         /// # Payment
7686         ///
7687         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7688         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7689         ///
7690         /// The builder will have the provided expiration set. Any changes to the expiration on the
7691         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7692         /// block time minus two hours is used for the current time when determining if the refund has
7693         /// expired.
7694         ///
7695         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7696         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7697         /// with an [`Event::InvoiceRequestFailed`].
7698         ///
7699         /// If `max_total_routing_fee_msat` is not specified, The default from
7700         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7701         ///
7702         /// # Privacy
7703         ///
7704         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the refund.
7705         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7706         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7707         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7708         /// order to send the [`Bolt12Invoice`].
7709         ///
7710         /// Also, uses a derived payer id in the refund for payer privacy.
7711         ///
7712         /// # Limitations
7713         ///
7714         /// Requires a direct connection to an introduction node in the responding
7715         /// [`Bolt12Invoice::payment_paths`].
7716         ///
7717         /// # Errors
7718         ///
7719         /// Errors if:
7720         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7721         /// - `amount_msats` is invalid, or
7722         /// - the parameterized [`Router`] is unable to create a blinded path for the refund.
7723         ///
7724         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7725         ///
7726         /// [`Refund`]: crate::offers::refund::Refund
7727         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7728         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7729         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7730         pub fn create_refund_builder(
7731                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7732                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7733         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7734                 let node_id = self.get_our_node_id();
7735                 let expanded_key = &self.inbound_payment_key;
7736                 let entropy = &*self.entropy_source;
7737                 let secp_ctx = &self.secp_ctx;
7738
7739                 let path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7740                 let builder = RefundBuilder::deriving_payer_id(
7741                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7742                 )?
7743                         .chain_hash(self.chain_hash)
7744                         .absolute_expiry(absolute_expiry)
7745                         .path(path);
7746
7747                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7748                 self.pending_outbound_payments
7749                         .add_new_awaiting_invoice(
7750                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7751                         )
7752                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7753
7754                 Ok(builder)
7755         }
7756
7757         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7758         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7759         /// [`Bolt12Invoice`] once it is received.
7760         ///
7761         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7762         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7763         /// The optional parameters are used in the builder, if `Some`:
7764         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7765         ///   [`Offer::expects_quantity`] is `true`.
7766         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7767         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7768         ///
7769         /// If `max_total_routing_fee_msat` is not specified, The default from
7770         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7771         ///
7772         /// # Payment
7773         ///
7774         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7775         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7776         /// been sent.
7777         ///
7778         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7779         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7780         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7781         ///
7782         /// # Privacy
7783         ///
7784         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7785         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7786         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7787         /// in order to send the [`Bolt12Invoice`].
7788         ///
7789         /// # Limitations
7790         ///
7791         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7792         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7793         /// [`Bolt12Invoice::payment_paths`].
7794         ///
7795         /// # Errors
7796         ///
7797         /// Errors if:
7798         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7799         /// - the provided parameters are invalid for the offer,
7800         /// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
7801         ///   request.
7802         ///
7803         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7804         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7805         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7806         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7807         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7808         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7809         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7810         pub fn pay_for_offer(
7811                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7812                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7813                 max_total_routing_fee_msat: Option<u64>
7814         ) -> Result<(), Bolt12SemanticError> {
7815                 let expanded_key = &self.inbound_payment_key;
7816                 let entropy = &*self.entropy_source;
7817                 let secp_ctx = &self.secp_ctx;
7818
7819                 let builder = offer
7820                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7821                         .chain_hash(self.chain_hash)?;
7822                 let builder = match quantity {
7823                         None => builder,
7824                         Some(quantity) => builder.quantity(quantity)?,
7825                 };
7826                 let builder = match amount_msats {
7827                         None => builder,
7828                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7829                 };
7830                 let builder = match payer_note {
7831                         None => builder,
7832                         Some(payer_note) => builder.payer_note(payer_note),
7833                 };
7834                 let invoice_request = builder.build_and_sign()?;
7835                 let reply_path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7836
7837                 let expiration = StaleExpiration::TimerTicks(1);
7838                 self.pending_outbound_payments
7839                         .add_new_awaiting_invoice(
7840                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7841                         )
7842                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7843
7844                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7845                 if offer.paths().is_empty() {
7846                         let message = new_pending_onion_message(
7847                                 OffersMessage::InvoiceRequest(invoice_request),
7848                                 Destination::Node(offer.signing_pubkey()),
7849                                 Some(reply_path),
7850                         );
7851                         pending_offers_messages.push(message);
7852                 } else {
7853                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7854                         // Using only one path could result in a failure if the path no longer exists. But only
7855                         // one invoice for a given payment id will be paid, even if more than one is received.
7856                         const REQUEST_LIMIT: usize = 10;
7857                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7858                                 let message = new_pending_onion_message(
7859                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7860                                         Destination::BlindedPath(path.clone()),
7861                                         Some(reply_path.clone()),
7862                                 );
7863                                 pending_offers_messages.push(message);
7864                         }
7865                 }
7866
7867                 Ok(())
7868         }
7869
7870         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7871         /// message.
7872         ///
7873         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7874         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7875         /// [`PaymentPreimage`].
7876         ///
7877         /// # Limitations
7878         ///
7879         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7880         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7881         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7882         /// received and no retries will be made.
7883         ///
7884         /// # Errors
7885         ///
7886         /// Errors if the parameterized [`Router`] is unable to create a blinded payment path or reply
7887         /// path for the invoice.
7888         ///
7889         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7890         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7891                 let expanded_key = &self.inbound_payment_key;
7892                 let entropy = &*self.entropy_source;
7893                 let secp_ctx = &self.secp_ctx;
7894
7895                 let amount_msats = refund.amount_msats();
7896                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7897
7898                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7899                         Ok((payment_hash, payment_secret)) => {
7900                                 let payment_paths = self.create_blinded_payment_paths(amount_msats, payment_secret)
7901                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7902
7903                                 #[cfg(feature = "std")]
7904                                 let builder = refund.respond_using_derived_keys(
7905                                         payment_paths, payment_hash, expanded_key, entropy
7906                                 )?;
7907                                 #[cfg(not(feature = "std"))]
7908                                 let created_at = Duration::from_secs(
7909                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7910                                 );
7911                                 #[cfg(not(feature = "std"))]
7912                                 let builder = refund.respond_using_derived_keys_no_std(
7913                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7914                                 )?;
7915                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7916                                 let reply_path = self.create_blinded_path()
7917                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7918
7919                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7920                                 if refund.paths().is_empty() {
7921                                         let message = new_pending_onion_message(
7922                                                 OffersMessage::Invoice(invoice),
7923                                                 Destination::Node(refund.payer_id()),
7924                                                 Some(reply_path),
7925                                         );
7926                                         pending_offers_messages.push(message);
7927                                 } else {
7928                                         for path in refund.paths() {
7929                                                 let message = new_pending_onion_message(
7930                                                         OffersMessage::Invoice(invoice.clone()),
7931                                                         Destination::BlindedPath(path.clone()),
7932                                                         Some(reply_path.clone()),
7933                                                 );
7934                                                 pending_offers_messages.push(message);
7935                                         }
7936                                 }
7937
7938                                 Ok(())
7939                         },
7940                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7941                 }
7942         }
7943
7944         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7945         /// to pay us.
7946         ///
7947         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7948         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7949         ///
7950         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7951         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7952         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7953         /// passed directly to [`claim_funds`].
7954         ///
7955         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7956         ///
7957         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7958         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7959         ///
7960         /// # Note
7961         ///
7962         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7963         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7964         ///
7965         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7966         ///
7967         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7968         /// on versions of LDK prior to 0.0.114.
7969         ///
7970         /// [`claim_funds`]: Self::claim_funds
7971         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7972         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7973         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7974         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7975         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7976         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7977                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7978                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7979                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7980                         min_final_cltv_expiry_delta)
7981         }
7982
7983         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7984         /// stored external to LDK.
7985         ///
7986         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7987         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7988         /// the `min_value_msat` provided here, if one is provided.
7989         ///
7990         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7991         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7992         /// payments.
7993         ///
7994         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7995         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7996         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7997         /// sender "proof-of-payment" unless they have paid the required amount.
7998         ///
7999         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
8000         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
8001         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
8002         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
8003         /// invoices when no timeout is set.
8004         ///
8005         /// Note that we use block header time to time-out pending inbound payments (with some margin
8006         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
8007         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
8008         /// If you need exact expiry semantics, you should enforce them upon receipt of
8009         /// [`PaymentClaimable`].
8010         ///
8011         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
8012         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
8013         ///
8014         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
8015         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
8016         ///
8017         /// # Note
8018         ///
8019         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
8020         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
8021         ///
8022         /// Errors if `min_value_msat` is greater than total bitcoin supply.
8023         ///
8024         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
8025         /// on versions of LDK prior to 0.0.114.
8026         ///
8027         /// [`create_inbound_payment`]: Self::create_inbound_payment
8028         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
8029         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
8030                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
8031                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
8032                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
8033                         min_final_cltv_expiry)
8034         }
8035
8036         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
8037         /// previously returned from [`create_inbound_payment`].
8038         ///
8039         /// [`create_inbound_payment`]: Self::create_inbound_payment
8040         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
8041                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
8042         }
8043
8044         /// Creates a blinded path by delegating to [`MessageRouter::create_blinded_paths`].
8045         ///
8046         /// Errors if the `MessageRouter` errors or returns an empty `Vec`.
8047         fn create_blinded_path(&self) -> Result<BlindedPath, ()> {
8048                 let recipient = self.get_our_node_id();
8049                 let secp_ctx = &self.secp_ctx;
8050
8051                 let peers = self.per_peer_state.read().unwrap()
8052                         .iter()
8053                         .filter(|(_, peer)| peer.lock().unwrap().latest_features.supports_onion_messages())
8054                         .map(|(node_id, _)| *node_id)
8055                         .collect::<Vec<_>>();
8056
8057                 self.router
8058                         .create_blinded_paths(recipient, peers, secp_ctx)
8059                         .and_then(|paths| paths.into_iter().next().ok_or(()))
8060         }
8061
8062         /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
8063         /// [`Router::create_blinded_payment_paths`].
8064         fn create_blinded_payment_paths(
8065                 &self, amount_msats: u64, payment_secret: PaymentSecret
8066         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
8067                 let secp_ctx = &self.secp_ctx;
8068
8069                 let first_hops = self.list_usable_channels();
8070                 let payee_node_id = self.get_our_node_id();
8071                 let max_cltv_expiry = self.best_block.read().unwrap().height() + CLTV_FAR_FAR_AWAY
8072                         + LATENCY_GRACE_PERIOD_BLOCKS;
8073                 let payee_tlvs = ReceiveTlvs {
8074                         payment_secret,
8075                         payment_constraints: PaymentConstraints {
8076                                 max_cltv_expiry,
8077                                 htlc_minimum_msat: 1,
8078                         },
8079                 };
8080                 self.router.create_blinded_payment_paths(
8081                         payee_node_id, first_hops, payee_tlvs, amount_msats, secp_ctx
8082                 )
8083         }
8084
8085         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
8086         /// are used when constructing the phantom invoice's route hints.
8087         ///
8088         /// [phantom node payments]: crate::sign::PhantomKeysManager
8089         pub fn get_phantom_scid(&self) -> u64 {
8090                 let best_block_height = self.best_block.read().unwrap().height();
8091                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8092                 loop {
8093                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8094                         // Ensure the generated scid doesn't conflict with a real channel.
8095                         match short_to_chan_info.get(&scid_candidate) {
8096                                 Some(_) => continue,
8097                                 None => return scid_candidate
8098                         }
8099                 }
8100         }
8101
8102         /// Gets route hints for use in receiving [phantom node payments].
8103         ///
8104         /// [phantom node payments]: crate::sign::PhantomKeysManager
8105         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
8106                 PhantomRouteHints {
8107                         channels: self.list_usable_channels(),
8108                         phantom_scid: self.get_phantom_scid(),
8109                         real_node_pubkey: self.get_our_node_id(),
8110                 }
8111         }
8112
8113         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
8114         /// used when constructing the route hints for HTLCs intended to be intercepted. See
8115         /// [`ChannelManager::forward_intercepted_htlc`].
8116         ///
8117         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
8118         /// times to get a unique scid.
8119         pub fn get_intercept_scid(&self) -> u64 {
8120                 let best_block_height = self.best_block.read().unwrap().height();
8121                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8122                 loop {
8123                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8124                         // Ensure the generated scid doesn't conflict with a real channel.
8125                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
8126                         return scid_candidate
8127                 }
8128         }
8129
8130         /// Gets inflight HTLC information by processing pending outbound payments that are in
8131         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
8132         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
8133                 let mut inflight_htlcs = InFlightHtlcs::new();
8134
8135                 let per_peer_state = self.per_peer_state.read().unwrap();
8136                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8137                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8138                         let peer_state = &mut *peer_state_lock;
8139                         for chan in peer_state.channel_by_id.values().filter_map(
8140                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
8141                         ) {
8142                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
8143                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
8144                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
8145                                         }
8146                                 }
8147                         }
8148                 }
8149
8150                 inflight_htlcs
8151         }
8152
8153         #[cfg(any(test, feature = "_test_utils"))]
8154         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
8155                 let events = core::cell::RefCell::new(Vec::new());
8156                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
8157                 self.process_pending_events(&event_handler);
8158                 events.into_inner()
8159         }
8160
8161         #[cfg(feature = "_test_utils")]
8162         pub fn push_pending_event(&self, event: events::Event) {
8163                 let mut events = self.pending_events.lock().unwrap();
8164                 events.push_back((event, None));
8165         }
8166
8167         #[cfg(test)]
8168         pub fn pop_pending_event(&self) -> Option<events::Event> {
8169                 let mut events = self.pending_events.lock().unwrap();
8170                 events.pop_front().map(|(e, _)| e)
8171         }
8172
8173         #[cfg(test)]
8174         pub fn has_pending_payments(&self) -> bool {
8175                 self.pending_outbound_payments.has_pending_payments()
8176         }
8177
8178         #[cfg(test)]
8179         pub fn clear_pending_payments(&self) {
8180                 self.pending_outbound_payments.clear_pending_payments()
8181         }
8182
8183         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
8184         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
8185         /// operation. It will double-check that nothing *else* is also blocking the same channel from
8186         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
8187         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey,
8188                 channel_funding_outpoint: OutPoint, channel_id: ChannelId,
8189                 mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
8190
8191                 let logger = WithContext::from(
8192                         &self.logger, Some(counterparty_node_id), Some(channel_id),
8193                 );
8194                 loop {
8195                         let per_peer_state = self.per_peer_state.read().unwrap();
8196                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
8197                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
8198                                 let peer_state = &mut *peer_state_lck;
8199                                 if let Some(blocker) = completed_blocker.take() {
8200                                         // Only do this on the first iteration of the loop.
8201                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
8202                                                 .get_mut(&channel_id)
8203                                         {
8204                                                 blockers.retain(|iter| iter != &blocker);
8205                                         }
8206                                 }
8207
8208                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
8209                                         channel_funding_outpoint, channel_id, counterparty_node_id) {
8210                                         // Check that, while holding the peer lock, we don't have anything else
8211                                         // blocking monitor updates for this channel. If we do, release the monitor
8212                                         // update(s) when those blockers complete.
8213                                         log_trace!(logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
8214                                                 &channel_id);
8215                                         break;
8216                                 }
8217
8218                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(
8219                                         channel_id) {
8220                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
8221                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
8222                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
8223                                                         log_debug!(logger, "Unlocking monitor updating for channel {} and updating monitor",
8224                                                                 channel_id);
8225                                                         handle_new_monitor_update!(self, channel_funding_outpoint, monitor_update,
8226                                                                 peer_state_lck, peer_state, per_peer_state, chan);
8227                                                         if further_update_exists {
8228                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
8229                                                                 // top of the loop.
8230                                                                 continue;
8231                                                         }
8232                                                 } else {
8233                                                         log_trace!(logger, "Unlocked monitor updating for channel {} without monitors to update",
8234                                                                 channel_id);
8235                                                 }
8236                                         }
8237                                 }
8238                         } else {
8239                                 log_debug!(logger,
8240                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
8241                                         log_pubkey!(counterparty_node_id));
8242                         }
8243                         break;
8244                 }
8245         }
8246
8247         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
8248                 for action in actions {
8249                         match action {
8250                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
8251                                         channel_funding_outpoint, channel_id, counterparty_node_id
8252                                 } => {
8253                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, channel_id, None);
8254                                 }
8255                         }
8256                 }
8257         }
8258
8259         /// Processes any events asynchronously in the order they were generated since the last call
8260         /// using the given event handler.
8261         ///
8262         /// See the trait-level documentation of [`EventsProvider`] for requirements.
8263         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
8264                 &self, handler: H
8265         ) {
8266                 let mut ev;
8267                 process_events_body!(self, ev, { handler(ev).await });
8268         }
8269 }
8270
8271 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> MessageSendEventsProvider for ChannelManager<M, T, ES, NS, SP, F, R, L>
8272 where
8273         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8274         T::Target: BroadcasterInterface,
8275         ES::Target: EntropySource,
8276         NS::Target: NodeSigner,
8277         SP::Target: SignerProvider,
8278         F::Target: FeeEstimator,
8279         R::Target: Router,
8280         L::Target: Logger,
8281 {
8282         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
8283         /// The returned array will contain `MessageSendEvent`s for different peers if
8284         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
8285         /// is always placed next to each other.
8286         ///
8287         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
8288         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
8289         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
8290         /// will randomly be placed first or last in the returned array.
8291         ///
8292         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
8293         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be pleaced among
8294         /// the `MessageSendEvent`s to the specific peer they were generated under.
8295         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
8296                 let events = RefCell::new(Vec::new());
8297                 PersistenceNotifierGuard::optionally_notify(self, || {
8298                         let mut result = NotifyOption::SkipPersistNoEvents;
8299
8300                         // TODO: This behavior should be documented. It's unintuitive that we query
8301                         // ChannelMonitors when clearing other events.
8302                         if self.process_pending_monitor_events() {
8303                                 result = NotifyOption::DoPersist;
8304                         }
8305
8306                         if self.check_free_holding_cells() {
8307                                 result = NotifyOption::DoPersist;
8308                         }
8309                         if self.maybe_generate_initial_closing_signed() {
8310                                 result = NotifyOption::DoPersist;
8311                         }
8312
8313                         let mut pending_events = Vec::new();
8314                         let per_peer_state = self.per_peer_state.read().unwrap();
8315                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8316                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8317                                 let peer_state = &mut *peer_state_lock;
8318                                 if peer_state.pending_msg_events.len() > 0 {
8319                                         pending_events.append(&mut peer_state.pending_msg_events);
8320                                 }
8321                         }
8322
8323                         if !pending_events.is_empty() {
8324                                 events.replace(pending_events);
8325                         }
8326
8327                         result
8328                 });
8329                 events.into_inner()
8330         }
8331 }
8332
8333 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> EventsProvider for ChannelManager<M, T, ES, NS, SP, F, R, L>
8334 where
8335         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8336         T::Target: BroadcasterInterface,
8337         ES::Target: EntropySource,
8338         NS::Target: NodeSigner,
8339         SP::Target: SignerProvider,
8340         F::Target: FeeEstimator,
8341         R::Target: Router,
8342         L::Target: Logger,
8343 {
8344         /// Processes events that must be periodically handled.
8345         ///
8346         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8347         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8348         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8349                 let mut ev;
8350                 process_events_body!(self, ev, handler.handle_event(ev));
8351         }
8352 }
8353
8354 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> chain::Listen for ChannelManager<M, T, ES, NS, SP, F, R, L>
8355 where
8356         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8357         T::Target: BroadcasterInterface,
8358         ES::Target: EntropySource,
8359         NS::Target: NodeSigner,
8360         SP::Target: SignerProvider,
8361         F::Target: FeeEstimator,
8362         R::Target: Router,
8363         L::Target: Logger,
8364 {
8365         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
8366                 {
8367                         let best_block = self.best_block.read().unwrap();
8368                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8369                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8370                         assert_eq!(best_block.height(), height - 1,
8371                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8372                 }
8373
8374                 self.transactions_confirmed(header, txdata, height);
8375                 self.best_block_updated(header, height);
8376         }
8377
8378         fn block_disconnected(&self, header: &Header, height: u32) {
8379                 let _persistence_guard =
8380                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8381                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8382                 let new_height = height - 1;
8383                 {
8384                         let mut best_block = self.best_block.write().unwrap();
8385                         assert_eq!(best_block.block_hash(), header.block_hash(),
8386                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8387                         assert_eq!(best_block.height(), height,
8388                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8389                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8390                 }
8391
8392                 self.do_chain_event(Some(new_height), |channel| channel.best_block_updated(new_height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
8393         }
8394 }
8395
8396 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> chain::Confirm for ChannelManager<M, T, ES, NS, SP, F, R, L>
8397 where
8398         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8399         T::Target: BroadcasterInterface,
8400         ES::Target: EntropySource,
8401         NS::Target: NodeSigner,
8402         SP::Target: SignerProvider,
8403         F::Target: FeeEstimator,
8404         R::Target: Router,
8405         L::Target: Logger,
8406 {
8407         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
8408                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8409                 // during initialization prior to the chain_monitor being fully configured in some cases.
8410                 // See the docs for `ChannelManagerReadArgs` for more.
8411
8412                 let block_hash = header.block_hash();
8413                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8414
8415                 let _persistence_guard =
8416                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8417                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8418                 self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context))
8419                         .map(|(a, b)| (a, Vec::new(), b)));
8420
8421                 let last_best_block_height = self.best_block.read().unwrap().height();
8422                 if height < last_best_block_height {
8423                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8424                         self.do_chain_event(Some(last_best_block_height), |channel| channel.best_block_updated(last_best_block_height, timestamp as u32, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
8425                 }
8426         }
8427
8428         fn best_block_updated(&self, header: &Header, height: u32) {
8429                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8430                 // during initialization prior to the chain_monitor being fully configured in some cases.
8431                 // See the docs for `ChannelManagerReadArgs` for more.
8432
8433                 let block_hash = header.block_hash();
8434                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8435
8436                 let _persistence_guard =
8437                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8438                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8439                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8440
8441                 self.do_chain_event(Some(height), |channel| channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context)));
8442
8443                 macro_rules! max_time {
8444                         ($timestamp: expr) => {
8445                                 loop {
8446                                         // Update $timestamp to be the max of its current value and the block
8447                                         // timestamp. This should keep us close to the current time without relying on
8448                                         // having an explicit local time source.
8449                                         // Just in case we end up in a race, we loop until we either successfully
8450                                         // update $timestamp or decide we don't need to.
8451                                         let old_serial = $timestamp.load(Ordering::Acquire);
8452                                         if old_serial >= header.time as usize { break; }
8453                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8454                                                 break;
8455                                         }
8456                                 }
8457                         }
8458                 }
8459                 max_time!(self.highest_seen_timestamp);
8460                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8461                 payment_secrets.retain(|_, inbound_payment| {
8462                         inbound_payment.expiry_time > header.time as u64
8463                 });
8464         }
8465
8466         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
8467                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8468                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8469                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8470                         let peer_state = &mut *peer_state_lock;
8471                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8472                                 let txid_opt = chan.context.get_funding_txo();
8473                                 let height_opt = chan.context.get_funding_tx_confirmation_height();
8474                                 let hash_opt = chan.context.get_funding_tx_confirmed_in();
8475                                 if let (Some(funding_txo), Some(conf_height), Some(block_hash)) = (txid_opt, height_opt, hash_opt) {
8476                                         res.push((funding_txo.txid, conf_height, Some(block_hash)));
8477                                 }
8478                         }
8479                 }
8480                 res
8481         }
8482
8483         fn transaction_unconfirmed(&self, txid: &Txid) {
8484                 let _persistence_guard =
8485                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8486                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8487                 self.do_chain_event(None, |channel| {
8488                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8489                                 if funding_txo.txid == *txid {
8490                                         channel.funding_transaction_unconfirmed(&&WithChannelContext::from(&self.logger, &channel.context)).map(|()| (None, Vec::new(), None))
8491                                 } else { Ok((None, Vec::new(), None)) }
8492                         } else { Ok((None, Vec::new(), None)) }
8493                 });
8494         }
8495 }
8496
8497 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, L>
8498 where
8499         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8500         T::Target: BroadcasterInterface,
8501         ES::Target: EntropySource,
8502         NS::Target: NodeSigner,
8503         SP::Target: SignerProvider,
8504         F::Target: FeeEstimator,
8505         R::Target: Router,
8506         L::Target: Logger,
8507 {
8508         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8509         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8510         /// the function.
8511         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8512                         (&self, height_opt: Option<u32>, f: FN) {
8513                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8514                 // during initialization prior to the chain_monitor being fully configured in some cases.
8515                 // See the docs for `ChannelManagerReadArgs` for more.
8516
8517                 let mut failed_channels = Vec::new();
8518                 let mut timed_out_htlcs = Vec::new();
8519                 {
8520                         let per_peer_state = self.per_peer_state.read().unwrap();
8521                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8522                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8523                                 let peer_state = &mut *peer_state_lock;
8524                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8525                                 peer_state.channel_by_id.retain(|_, phase| {
8526                                         match phase {
8527                                                 // Retain unfunded channels.
8528                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8529                                                 // TODO(dual_funding): Combine this match arm with above.
8530                                                 #[cfg(dual_funding)]
8531                                                 ChannelPhase::UnfundedOutboundV2(_) | ChannelPhase::UnfundedInboundV2(_) => true,
8532                                                 ChannelPhase::Funded(channel) => {
8533                                                         let res = f(channel);
8534                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8535                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8536                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8537                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8538                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8539                                                                 }
8540                                                                 let logger = WithChannelContext::from(&self.logger, &channel.context);
8541                                                                 if let Some(channel_ready) = channel_ready_opt {
8542                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8543                                                                         if channel.context.is_usable() {
8544                                                                                 log_trace!(logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8545                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8546                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8547                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8548                                                                                                 msg,
8549                                                                                         });
8550                                                                                 }
8551                                                                         } else {
8552                                                                                 log_trace!(logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8553                                                                         }
8554                                                                 }
8555
8556                                                                 {
8557                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8558                                                                         emit_channel_ready_event!(pending_events, channel);
8559                                                                 }
8560
8561                                                                 if let Some(announcement_sigs) = announcement_sigs {
8562                                                                         log_trace!(logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8563                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8564                                                                                 node_id: channel.context.get_counterparty_node_id(),
8565                                                                                 msg: announcement_sigs,
8566                                                                         });
8567                                                                         if let Some(height) = height_opt {
8568                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8569                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8570                                                                                                 msg: announcement,
8571                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8572                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8573                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8574                                                                                         });
8575                                                                                 }
8576                                                                         }
8577                                                                 }
8578                                                                 if channel.is_our_channel_ready() {
8579                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8580                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8581                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8582                                                                                 // can relay using the real SCID at relay-time (i.e.
8583                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8584                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8585                                                                                 // is always consistent.
8586                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8587                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8588                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8589                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8590                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8591                                                                         }
8592                                                                 }
8593                                                         } else if let Err(reason) = res {
8594                                                                 update_maps_on_chan_removal!(self, &channel.context);
8595                                                                 // It looks like our counterparty went on-chain or funding transaction was
8596                                                                 // reorged out of the main chain. Close the channel.
8597                                                                 let reason_message = format!("{}", reason);
8598                                                                 failed_channels.push(channel.context.force_shutdown(true, reason));
8599                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8600                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelUpdate {
8601                                                                                 msg: update
8602                                                                         });
8603                                                                 }
8604                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8605                                                                         node_id: channel.context.get_counterparty_node_id(),
8606                                                                         action: msgs::ErrorAction::DisconnectPeer {
8607                                                                                 msg: Some(msgs::ErrorMessage {
8608                                                                                         channel_id: channel.context.channel_id(),
8609                                                                                         data: reason_message,
8610                                                                                 })
8611                                                                         },
8612                                                                 });
8613                                                                 return false;
8614                                                         }
8615                                                         true
8616                                                 }
8617                                         }
8618                                 });
8619                         }
8620                 }
8621
8622                 if let Some(height) = height_opt {
8623                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8624                                 payment.htlcs.retain(|htlc| {
8625                                         // If height is approaching the number of blocks we think it takes us to get
8626                                         // our commitment transaction confirmed before the HTLC expires, plus the
8627                                         // number of blocks we generally consider it to take to do a commitment update,
8628                                         // just give up on it and fail the HTLC.
8629                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8630                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8631                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8632
8633                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8634                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8635                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8636                                                 false
8637                                         } else { true }
8638                                 });
8639                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8640                         });
8641
8642                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8643                         intercepted_htlcs.retain(|_, htlc| {
8644                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8645                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8646                                                 short_channel_id: htlc.prev_short_channel_id,
8647                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8648                                                 htlc_id: htlc.prev_htlc_id,
8649                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8650                                                 phantom_shared_secret: None,
8651                                                 outpoint: htlc.prev_funding_outpoint,
8652                                                 channel_id: htlc.prev_channel_id,
8653                                                 blinded_failure: htlc.forward_info.routing.blinded_failure(),
8654                                         });
8655
8656                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8657                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8658                                                 _ => unreachable!(),
8659                                         };
8660                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8661                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8662                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8663                                         let logger = WithContext::from(
8664                                                 &self.logger, None, Some(htlc.prev_channel_id)
8665                                         );
8666                                         log_trace!(logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8667                                         false
8668                                 } else { true }
8669                         });
8670                 }
8671
8672                 self.handle_init_event_channel_failures(failed_channels);
8673
8674                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8675                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8676                 }
8677         }
8678
8679         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8680         /// may have events that need processing.
8681         ///
8682         /// In order to check if this [`ChannelManager`] needs persisting, call
8683         /// [`Self::get_and_clear_needs_persistence`].
8684         ///
8685         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8686         /// [`ChannelManager`] and should instead register actions to be taken later.
8687         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8688                 self.event_persist_notifier.get_future()
8689         }
8690
8691         /// Returns true if this [`ChannelManager`] needs to be persisted.
8692         pub fn get_and_clear_needs_persistence(&self) -> bool {
8693                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8694         }
8695
8696         #[cfg(any(test, feature = "_test_utils"))]
8697         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8698                 self.event_persist_notifier.notify_pending()
8699         }
8700
8701         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8702         /// [`chain::Confirm`] interfaces.
8703         pub fn current_best_block(&self) -> BestBlock {
8704                 self.best_block.read().unwrap().clone()
8705         }
8706
8707         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8708         /// [`ChannelManager`].
8709         pub fn node_features(&self) -> NodeFeatures {
8710                 provided_node_features(&self.default_configuration)
8711         }
8712
8713         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8714         /// [`ChannelManager`].
8715         ///
8716         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8717         /// or not. Thus, this method is not public.
8718         #[cfg(any(feature = "_test_utils", test))]
8719         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8720                 provided_bolt11_invoice_features(&self.default_configuration)
8721         }
8722
8723         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8724         /// [`ChannelManager`].
8725         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8726                 provided_bolt12_invoice_features(&self.default_configuration)
8727         }
8728
8729         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8730         /// [`ChannelManager`].
8731         pub fn channel_features(&self) -> ChannelFeatures {
8732                 provided_channel_features(&self.default_configuration)
8733         }
8734
8735         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8736         /// [`ChannelManager`].
8737         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8738                 provided_channel_type_features(&self.default_configuration)
8739         }
8740
8741         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8742         /// [`ChannelManager`].
8743         pub fn init_features(&self) -> InitFeatures {
8744                 provided_init_features(&self.default_configuration)
8745         }
8746 }
8747
8748 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8749         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8750 where
8751         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8752         T::Target: BroadcasterInterface,
8753         ES::Target: EntropySource,
8754         NS::Target: NodeSigner,
8755         SP::Target: SignerProvider,
8756         F::Target: FeeEstimator,
8757         R::Target: Router,
8758         L::Target: Logger,
8759 {
8760         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8761                 // Note that we never need to persist the updated ChannelManager for an inbound
8762                 // open_channel message - pre-funded channels are never written so there should be no
8763                 // change to the contents.
8764                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8765                         let res = self.internal_open_channel(counterparty_node_id, msg);
8766                         let persist = match &res {
8767                                 Err(e) if e.closes_channel() => {
8768                                         debug_assert!(false, "We shouldn't close a new channel");
8769                                         NotifyOption::DoPersist
8770                                 },
8771                                 _ => NotifyOption::SkipPersistHandleEvents,
8772                         };
8773                         let _ = handle_error!(self, res, *counterparty_node_id);
8774                         persist
8775                 });
8776         }
8777
8778         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8779                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8780                         "Dual-funded channels not supported".to_owned(),
8781                          msg.common_fields.temporary_channel_id.clone())), *counterparty_node_id);
8782         }
8783
8784         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8785                 // Note that we never need to persist the updated ChannelManager for an inbound
8786                 // accept_channel message - pre-funded channels are never written so there should be no
8787                 // change to the contents.
8788                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8789                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8790                         NotifyOption::SkipPersistHandleEvents
8791                 });
8792         }
8793
8794         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8795                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8796                         "Dual-funded channels not supported".to_owned(),
8797                          msg.common_fields.temporary_channel_id.clone())), *counterparty_node_id);
8798         }
8799
8800         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8801                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8802                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8803         }
8804
8805         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8806                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8807                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8808         }
8809
8810         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8811                 // Note that we never need to persist the updated ChannelManager for an inbound
8812                 // channel_ready message - while the channel's state will change, any channel_ready message
8813                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8814                 // will not force-close the channel on startup.
8815                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8816                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8817                         let persist = match &res {
8818                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8819                                 _ => NotifyOption::SkipPersistHandleEvents,
8820                         };
8821                         let _ = handle_error!(self, res, *counterparty_node_id);
8822                         persist
8823                 });
8824         }
8825
8826         fn handle_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) {
8827                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8828                         "Quiescence not supported".to_owned(),
8829                          msg.channel_id.clone())), *counterparty_node_id);
8830         }
8831
8832         fn handle_splice(&self, counterparty_node_id: &PublicKey, msg: &msgs::Splice) {
8833                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8834                         "Splicing not supported".to_owned(),
8835                          msg.channel_id.clone())), *counterparty_node_id);
8836         }
8837
8838         fn handle_splice_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceAck) {
8839                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8840                         "Splicing not supported (splice_ack)".to_owned(),
8841                          msg.channel_id.clone())), *counterparty_node_id);
8842         }
8843
8844         fn handle_splice_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
8845                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8846                         "Splicing not supported (splice_locked)".to_owned(),
8847                          msg.channel_id.clone())), *counterparty_node_id);
8848         }
8849
8850         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8851                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8852                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8853         }
8854
8855         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8856                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8857                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8858         }
8859
8860         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8861                 // Note that we never need to persist the updated ChannelManager for an inbound
8862                 // update_add_htlc message - the message itself doesn't change our channel state only the
8863                 // `commitment_signed` message afterwards will.
8864                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8865                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8866                         let persist = match &res {
8867                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8868                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8869                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8870                         };
8871                         let _ = handle_error!(self, res, *counterparty_node_id);
8872                         persist
8873                 });
8874         }
8875
8876         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8877                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8878                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8879         }
8880
8881         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8882                 // Note that we never need to persist the updated ChannelManager for an inbound
8883                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8884                 // `commitment_signed` message afterwards will.
8885                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8886                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8887                         let persist = match &res {
8888                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8889                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8890                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8891                         };
8892                         let _ = handle_error!(self, res, *counterparty_node_id);
8893                         persist
8894                 });
8895         }
8896
8897         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8898                 // Note that we never need to persist the updated ChannelManager for an inbound
8899                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8900                 // only the `commitment_signed` message afterwards will.
8901                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8902                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8903                         let persist = match &res {
8904                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8905                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8906                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8907                         };
8908                         let _ = handle_error!(self, res, *counterparty_node_id);
8909                         persist
8910                 });
8911         }
8912
8913         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8914                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8915                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8916         }
8917
8918         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8919                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8920                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8921         }
8922
8923         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8924                 // Note that we never need to persist the updated ChannelManager for an inbound
8925                 // update_fee message - the message itself doesn't change our channel state only the
8926                 // `commitment_signed` message afterwards will.
8927                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8928                         let res = self.internal_update_fee(counterparty_node_id, msg);
8929                         let persist = match &res {
8930                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8931                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8932                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8933                         };
8934                         let _ = handle_error!(self, res, *counterparty_node_id);
8935                         persist
8936                 });
8937         }
8938
8939         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8940                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8941                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8942         }
8943
8944         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8945                 PersistenceNotifierGuard::optionally_notify(self, || {
8946                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8947                                 persist
8948                         } else {
8949                                 NotifyOption::DoPersist
8950                         }
8951                 });
8952         }
8953
8954         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8955                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8956                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8957                         let persist = match &res {
8958                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8959                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8960                                 Ok(persist) => *persist,
8961                         };
8962                         let _ = handle_error!(self, res, *counterparty_node_id);
8963                         persist
8964                 });
8965         }
8966
8967         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8968                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8969                         self, || NotifyOption::SkipPersistHandleEvents);
8970                 let mut failed_channels = Vec::new();
8971                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8972                 let remove_peer = {
8973                         log_debug!(
8974                                 WithContext::from(&self.logger, Some(*counterparty_node_id), None),
8975                                 "Marking channels with {} disconnected and generating channel_updates.",
8976                                 log_pubkey!(counterparty_node_id)
8977                         );
8978                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8979                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8980                                 let peer_state = &mut *peer_state_lock;
8981                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8982                                 peer_state.channel_by_id.retain(|_, phase| {
8983                                         let context = match phase {
8984                                                 ChannelPhase::Funded(chan) => {
8985                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
8986                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok() {
8987                                                                 // We only retain funded channels that are not shutdown.
8988                                                                 return true;
8989                                                         }
8990                                                         &mut chan.context
8991                                                 },
8992                                                 // We retain UnfundedOutboundV1 channel for some time in case
8993                                                 // peer unexpectedly disconnects, and intends to reconnect again.
8994                                                 ChannelPhase::UnfundedOutboundV1(_) => {
8995                                                         return true;
8996                                                 },
8997                                                 // Unfunded inbound channels will always be removed.
8998                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8999                                                         &mut chan.context
9000                                                 },
9001                                                 #[cfg(dual_funding)]
9002                                                 ChannelPhase::UnfundedOutboundV2(chan) => {
9003                                                         &mut chan.context
9004                                                 },
9005                                                 #[cfg(dual_funding)]
9006                                                 ChannelPhase::UnfundedInboundV2(chan) => {
9007                                                         &mut chan.context
9008                                                 },
9009                                         };
9010                                         // Clean up for removal.
9011                                         update_maps_on_chan_removal!(self, &context);
9012                                         failed_channels.push(context.force_shutdown(false, ClosureReason::DisconnectedPeer));
9013                                         false
9014                                 });
9015                                 // Note that we don't bother generating any events for pre-accept channels -
9016                                 // they're not considered "channels" yet from the PoV of our events interface.
9017                                 peer_state.inbound_channel_request_by_id.clear();
9018                                 pending_msg_events.retain(|msg| {
9019                                         match msg {
9020                                                 // V1 Channel Establishment
9021                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
9022                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
9023                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
9024                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
9025                                                 // V2 Channel Establishment
9026                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
9027                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
9028                                                 // Common Channel Establishment
9029                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
9030                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
9031                                                 // Quiescence
9032                                                 &events::MessageSendEvent::SendStfu { .. } => false,
9033                                                 // Splicing
9034                                                 &events::MessageSendEvent::SendSplice { .. } => false,
9035                                                 &events::MessageSendEvent::SendSpliceAck { .. } => false,
9036                                                 &events::MessageSendEvent::SendSpliceLocked { .. } => false,
9037                                                 // Interactive Transaction Construction
9038                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
9039                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
9040                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
9041                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
9042                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
9043                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
9044                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
9045                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
9046                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
9047                                                 // Channel Operations
9048                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
9049                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
9050                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
9051                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
9052                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
9053                                                 &events::MessageSendEvent::HandleError { .. } => false,
9054                                                 // Gossip
9055                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
9056                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
9057                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => true,
9058                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
9059                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
9060                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
9061                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
9062                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
9063                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
9064                                         }
9065                                 });
9066                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
9067                                 peer_state.is_connected = false;
9068                                 peer_state.ok_to_remove(true)
9069                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
9070                 };
9071                 if remove_peer {
9072                         per_peer_state.remove(counterparty_node_id);
9073                 }
9074                 mem::drop(per_peer_state);
9075
9076                 for failure in failed_channels.drain(..) {
9077                         self.finish_close_channel(failure);
9078                 }
9079         }
9080
9081         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
9082                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), None);
9083                 if !init_msg.features.supports_static_remote_key() {
9084                         log_debug!(logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
9085                         return Err(());
9086                 }
9087
9088                 let mut res = Ok(());
9089
9090                 PersistenceNotifierGuard::optionally_notify(self, || {
9091                         // If we have too many peers connected which don't have funded channels, disconnect the
9092                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
9093                         // unfunded channels taking up space in memory for disconnected peers, we still let new
9094                         // peers connect, but we'll reject new channels from them.
9095                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
9096                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
9097
9098                         {
9099                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
9100                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
9101                                         hash_map::Entry::Vacant(e) => {
9102                                                 if inbound_peer_limited {
9103                                                         res = Err(());
9104                                                         return NotifyOption::SkipPersistNoEvents;
9105                                                 }
9106                                                 e.insert(Mutex::new(PeerState {
9107                                                         channel_by_id: new_hash_map(),
9108                                                         inbound_channel_request_by_id: new_hash_map(),
9109                                                         latest_features: init_msg.features.clone(),
9110                                                         pending_msg_events: Vec::new(),
9111                                                         in_flight_monitor_updates: BTreeMap::new(),
9112                                                         monitor_update_blocked_actions: BTreeMap::new(),
9113                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
9114                                                         is_connected: true,
9115                                                 }));
9116                                         },
9117                                         hash_map::Entry::Occupied(e) => {
9118                                                 let mut peer_state = e.get().lock().unwrap();
9119                                                 peer_state.latest_features = init_msg.features.clone();
9120
9121                                                 let best_block_height = self.best_block.read().unwrap().height();
9122                                                 if inbound_peer_limited &&
9123                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
9124                                                         peer_state.channel_by_id.len()
9125                                                 {
9126                                                         res = Err(());
9127                                                         return NotifyOption::SkipPersistNoEvents;
9128                                                 }
9129
9130                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
9131                                                 peer_state.is_connected = true;
9132                                         },
9133                                 }
9134                         }
9135
9136                         log_debug!(logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
9137
9138                         let per_peer_state = self.per_peer_state.read().unwrap();
9139                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
9140                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9141                                 let peer_state = &mut *peer_state_lock;
9142                                 let pending_msg_events = &mut peer_state.pending_msg_events;
9143
9144                                 for (_, phase) in peer_state.channel_by_id.iter_mut() {
9145                                         match phase {
9146                                                 ChannelPhase::Funded(chan) => {
9147                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
9148                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
9149                                                                 node_id: chan.context.get_counterparty_node_id(),
9150                                                                 msg: chan.get_channel_reestablish(&&logger),
9151                                                         });
9152                                                 }
9153
9154                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
9155                                                         pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
9156                                                                 node_id: chan.context.get_counterparty_node_id(),
9157                                                                 msg: chan.get_open_channel(self.chain_hash),
9158                                                         });
9159                                                 }
9160
9161                                                 // TODO(dual_funding): Combine this match arm with above once #[cfg(dual_funding)] is removed.
9162                                                 #[cfg(dual_funding)]
9163                                                 ChannelPhase::UnfundedOutboundV2(chan) => {
9164                                                         pending_msg_events.push(events::MessageSendEvent::SendOpenChannelV2 {
9165                                                                 node_id: chan.context.get_counterparty_node_id(),
9166                                                                 msg: chan.get_open_channel_v2(self.chain_hash),
9167                                                         });
9168                                                 },
9169
9170                                                 ChannelPhase::UnfundedInboundV1(_) => {
9171                                                         // Since unfunded inbound channel maps are cleared upon disconnecting a peer,
9172                                                         // they are not persisted and won't be recovered after a crash.
9173                                                         // Therefore, they shouldn't exist at this point.
9174                                                         debug_assert!(false);
9175                                                 }
9176
9177                                                 // TODO(dual_funding): Combine this match arm with above once #[cfg(dual_funding)] is removed.
9178                                                 #[cfg(dual_funding)]
9179                                                 ChannelPhase::UnfundedInboundV2(channel) => {
9180                                                         // Since unfunded inbound channel maps are cleared upon disconnecting a peer,
9181                                                         // they are not persisted and won't be recovered after a crash.
9182                                                         // Therefore, they shouldn't exist at this point.
9183                                                         debug_assert!(false);
9184                                                 },
9185                                         }
9186                                 }
9187                         }
9188
9189                         return NotifyOption::SkipPersistHandleEvents;
9190                         //TODO: Also re-broadcast announcement_signatures
9191                 });
9192                 res
9193         }
9194
9195         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
9196                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9197
9198                 match &msg.data as &str {
9199                         "cannot co-op close channel w/ active htlcs"|
9200                         "link failed to shutdown" =>
9201                         {
9202                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
9203                                 // send one while HTLCs are still present. The issue is tracked at
9204                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
9205                                 // to fix it but none so far have managed to land upstream. The issue appears to be
9206                                 // very low priority for the LND team despite being marked "P1".
9207                                 // We're not going to bother handling this in a sensible way, instead simply
9208                                 // repeating the Shutdown message on repeat until morale improves.
9209                                 if !msg.channel_id.is_zero() {
9210                                         let per_peer_state = self.per_peer_state.read().unwrap();
9211                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9212                                         if peer_state_mutex_opt.is_none() { return; }
9213                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
9214                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
9215                                                 if let Some(msg) = chan.get_outbound_shutdown() {
9216                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
9217                                                                 node_id: *counterparty_node_id,
9218                                                                 msg,
9219                                                         });
9220                                                 }
9221                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
9222                                                         node_id: *counterparty_node_id,
9223                                                         action: msgs::ErrorAction::SendWarningMessage {
9224                                                                 msg: msgs::WarningMessage {
9225                                                                         channel_id: msg.channel_id,
9226                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
9227                                                                 },
9228                                                                 log_level: Level::Trace,
9229                                                         }
9230                                                 });
9231                                         }
9232                                 }
9233                                 return;
9234                         }
9235                         _ => {}
9236                 }
9237
9238                 if msg.channel_id.is_zero() {
9239                         let channel_ids: Vec<ChannelId> = {
9240                                 let per_peer_state = self.per_peer_state.read().unwrap();
9241                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9242                                 if peer_state_mutex_opt.is_none() { return; }
9243                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9244                                 let peer_state = &mut *peer_state_lock;
9245                                 // Note that we don't bother generating any events for pre-accept channels -
9246                                 // they're not considered "channels" yet from the PoV of our events interface.
9247                                 peer_state.inbound_channel_request_by_id.clear();
9248                                 peer_state.channel_by_id.keys().cloned().collect()
9249                         };
9250                         for channel_id in channel_ids {
9251                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9252                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
9253                         }
9254                 } else {
9255                         {
9256                                 // First check if we can advance the channel type and try again.
9257                                 let per_peer_state = self.per_peer_state.read().unwrap();
9258                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9259                                 if peer_state_mutex_opt.is_none() { return; }
9260                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9261                                 let peer_state = &mut *peer_state_lock;
9262                                 match peer_state.channel_by_id.get_mut(&msg.channel_id) {
9263                                         Some(ChannelPhase::UnfundedOutboundV1(ref mut chan)) => {
9264                                                 if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
9265                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
9266                                                                 node_id: *counterparty_node_id,
9267                                                                 msg,
9268                                                         });
9269                                                         return;
9270                                                 }
9271                                         },
9272                                         #[cfg(dual_funding)]
9273                                         Some(ChannelPhase::UnfundedOutboundV2(ref mut chan)) => {
9274                                                 if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
9275                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannelV2 {
9276                                                                 node_id: *counterparty_node_id,
9277                                                                 msg,
9278                                                         });
9279                                                         return;
9280                                                 }
9281                                         },
9282                                         None | Some(ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::Funded(_)) => (),
9283                                         #[cfg(dual_funding)]
9284                                         Some(ChannelPhase::UnfundedInboundV2(_)) => (),
9285                                 }
9286                         }
9287
9288                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9289                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
9290                 }
9291         }
9292
9293         fn provided_node_features(&self) -> NodeFeatures {
9294                 provided_node_features(&self.default_configuration)
9295         }
9296
9297         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
9298                 provided_init_features(&self.default_configuration)
9299         }
9300
9301         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
9302                 Some(vec![self.chain_hash])
9303         }
9304
9305         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
9306                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9307                         "Dual-funded channels not supported".to_owned(),
9308                          msg.channel_id.clone())), *counterparty_node_id);
9309         }
9310
9311         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
9312                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9313                         "Dual-funded channels not supported".to_owned(),
9314                          msg.channel_id.clone())), *counterparty_node_id);
9315         }
9316
9317         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
9318                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9319                         "Dual-funded channels not supported".to_owned(),
9320                          msg.channel_id.clone())), *counterparty_node_id);
9321         }
9322
9323         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
9324                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9325                         "Dual-funded channels not supported".to_owned(),
9326                          msg.channel_id.clone())), *counterparty_node_id);
9327         }
9328
9329         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
9330                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9331                         "Dual-funded channels not supported".to_owned(),
9332                          msg.channel_id.clone())), *counterparty_node_id);
9333         }
9334
9335         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
9336                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9337                         "Dual-funded channels not supported".to_owned(),
9338                          msg.channel_id.clone())), *counterparty_node_id);
9339         }
9340
9341         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
9342                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9343                         "Dual-funded channels not supported".to_owned(),
9344                          msg.channel_id.clone())), *counterparty_node_id);
9345         }
9346
9347         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
9348                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9349                         "Dual-funded channels not supported".to_owned(),
9350                          msg.channel_id.clone())), *counterparty_node_id);
9351         }
9352
9353         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
9354                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9355                         "Dual-funded channels not supported".to_owned(),
9356                          msg.channel_id.clone())), *counterparty_node_id);
9357         }
9358 }
9359
9360 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9361 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9362 where
9363         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9364         T::Target: BroadcasterInterface,
9365         ES::Target: EntropySource,
9366         NS::Target: NodeSigner,
9367         SP::Target: SignerProvider,
9368         F::Target: FeeEstimator,
9369         R::Target: Router,
9370         L::Target: Logger,
9371 {
9372         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9373                 let secp_ctx = &self.secp_ctx;
9374                 let expanded_key = &self.inbound_payment_key;
9375
9376                 match message {
9377                         OffersMessage::InvoiceRequest(invoice_request) => {
9378                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9379                                         &invoice_request
9380                                 ) {
9381                                         Ok(amount_msats) => amount_msats,
9382                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9383                                 };
9384                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9385                                         Ok(invoice_request) => invoice_request,
9386                                         Err(()) => {
9387                                                 let error = Bolt12SemanticError::InvalidMetadata;
9388                                                 return Some(OffersMessage::InvoiceError(error.into()));
9389                                         },
9390                                 };
9391
9392                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9393                                 let (payment_hash, payment_secret) = match self.create_inbound_payment(
9394                                         Some(amount_msats), relative_expiry, None
9395                                 ) {
9396                                         Ok((payment_hash, payment_secret)) => (payment_hash, payment_secret),
9397                                         Err(()) => {
9398                                                 let error = Bolt12SemanticError::InvalidAmount;
9399                                                 return Some(OffersMessage::InvoiceError(error.into()));
9400                                         },
9401                                 };
9402
9403                                 let payment_paths = match self.create_blinded_payment_paths(
9404                                         amount_msats, payment_secret
9405                                 ) {
9406                                         Ok(payment_paths) => payment_paths,
9407                                         Err(()) => {
9408                                                 let error = Bolt12SemanticError::MissingPaths;
9409                                                 return Some(OffersMessage::InvoiceError(error.into()));
9410                                         },
9411                                 };
9412
9413                                 #[cfg(not(feature = "std"))]
9414                                 let created_at = Duration::from_secs(
9415                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9416                                 );
9417
9418                                 if invoice_request.keys.is_some() {
9419                                         #[cfg(feature = "std")]
9420                                         let builder = invoice_request.respond_using_derived_keys(
9421                                                 payment_paths, payment_hash
9422                                         );
9423                                         #[cfg(not(feature = "std"))]
9424                                         let builder = invoice_request.respond_using_derived_keys_no_std(
9425                                                 payment_paths, payment_hash, created_at
9426                                         );
9427                                         match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9428                                                 Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9429                                                 Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9430                                         }
9431                                 } else {
9432                                         #[cfg(feature = "std")]
9433                                         let builder = invoice_request.respond_with(payment_paths, payment_hash);
9434                                         #[cfg(not(feature = "std"))]
9435                                         let builder = invoice_request.respond_with_no_std(
9436                                                 payment_paths, payment_hash, created_at
9437                                         );
9438                                         let response = builder.and_then(|builder| builder.allow_mpp().build())
9439                                                 .map_err(|e| OffersMessage::InvoiceError(e.into()))
9440                                                 .and_then(|invoice|
9441                                                         match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9442                                                                 Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9443                                                                 Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9444                                                                                 InvoiceError::from_string("Failed signing invoice".to_string())
9445                                                                 )),
9446                                                                 Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9447                                                                                 InvoiceError::from_string("Failed invoice signature verification".to_string())
9448                                                                 )),
9449                                                         });
9450                                         match response {
9451                                                 Ok(invoice) => Some(invoice),
9452                                                 Err(error) => Some(error),
9453                                         }
9454                                 }
9455                         },
9456                         OffersMessage::Invoice(invoice) => {
9457                                 match invoice.verify(expanded_key, secp_ctx) {
9458                                         Err(()) => {
9459                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9460                                         },
9461                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9462                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9463                                         },
9464                                         Ok(payment_id) => {
9465                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9466                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9467                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9468                                                 } else {
9469                                                         None
9470                                                 }
9471                                         },
9472                                 }
9473                         },
9474                         OffersMessage::InvoiceError(invoice_error) => {
9475                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9476                                 None
9477                         },
9478                 }
9479         }
9480
9481         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9482                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9483         }
9484 }
9485
9486 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9487 /// [`ChannelManager`].
9488 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9489         let mut node_features = provided_init_features(config).to_context();
9490         node_features.set_keysend_optional();
9491         node_features
9492 }
9493
9494 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9495 /// [`ChannelManager`].
9496 ///
9497 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9498 /// or not. Thus, this method is not public.
9499 #[cfg(any(feature = "_test_utils", test))]
9500 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9501         provided_init_features(config).to_context()
9502 }
9503
9504 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9505 /// [`ChannelManager`].
9506 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9507         provided_init_features(config).to_context()
9508 }
9509
9510 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9511 /// [`ChannelManager`].
9512 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9513         provided_init_features(config).to_context()
9514 }
9515
9516 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9517 /// [`ChannelManager`].
9518 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9519         ChannelTypeFeatures::from_init(&provided_init_features(config))
9520 }
9521
9522 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9523 /// [`ChannelManager`].
9524 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9525         // Note that if new features are added here which other peers may (eventually) require, we
9526         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9527         // [`ErroringMessageHandler`].
9528         let mut features = InitFeatures::empty();
9529         features.set_data_loss_protect_required();
9530         features.set_upfront_shutdown_script_optional();
9531         features.set_variable_length_onion_required();
9532         features.set_static_remote_key_required();
9533         features.set_payment_secret_required();
9534         features.set_basic_mpp_optional();
9535         features.set_wumbo_optional();
9536         features.set_shutdown_any_segwit_optional();
9537         features.set_channel_type_optional();
9538         features.set_scid_privacy_optional();
9539         features.set_zero_conf_optional();
9540         features.set_route_blinding_optional();
9541         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9542                 features.set_anchors_zero_fee_htlc_tx_optional();
9543         }
9544         features
9545 }
9546
9547 const SERIALIZATION_VERSION: u8 = 1;
9548 const MIN_SERIALIZATION_VERSION: u8 = 1;
9549
9550 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9551         (2, fee_base_msat, required),
9552         (4, fee_proportional_millionths, required),
9553         (6, cltv_expiry_delta, required),
9554 });
9555
9556 impl_writeable_tlv_based!(ChannelCounterparty, {
9557         (2, node_id, required),
9558         (4, features, required),
9559         (6, unspendable_punishment_reserve, required),
9560         (8, forwarding_info, option),
9561         (9, outbound_htlc_minimum_msat, option),
9562         (11, outbound_htlc_maximum_msat, option),
9563 });
9564
9565 impl Writeable for ChannelDetails {
9566         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9567                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9568                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9569                 let user_channel_id_low = self.user_channel_id as u64;
9570                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9571                 write_tlv_fields!(writer, {
9572                         (1, self.inbound_scid_alias, option),
9573                         (2, self.channel_id, required),
9574                         (3, self.channel_type, option),
9575                         (4, self.counterparty, required),
9576                         (5, self.outbound_scid_alias, option),
9577                         (6, self.funding_txo, option),
9578                         (7, self.config, option),
9579                         (8, self.short_channel_id, option),
9580                         (9, self.confirmations, option),
9581                         (10, self.channel_value_satoshis, required),
9582                         (12, self.unspendable_punishment_reserve, option),
9583                         (14, user_channel_id_low, required),
9584                         (16, self.balance_msat, required),
9585                         (18, self.outbound_capacity_msat, required),
9586                         (19, self.next_outbound_htlc_limit_msat, required),
9587                         (20, self.inbound_capacity_msat, required),
9588                         (21, self.next_outbound_htlc_minimum_msat, required),
9589                         (22, self.confirmations_required, option),
9590                         (24, self.force_close_spend_delay, option),
9591                         (26, self.is_outbound, required),
9592                         (28, self.is_channel_ready, required),
9593                         (30, self.is_usable, required),
9594                         (32, self.is_public, required),
9595                         (33, self.inbound_htlc_minimum_msat, option),
9596                         (35, self.inbound_htlc_maximum_msat, option),
9597                         (37, user_channel_id_high_opt, option),
9598                         (39, self.feerate_sat_per_1000_weight, option),
9599                         (41, self.channel_shutdown_state, option),
9600                         (43, self.pending_inbound_htlcs, optional_vec),
9601                         (45, self.pending_outbound_htlcs, optional_vec),
9602                 });
9603                 Ok(())
9604         }
9605 }
9606
9607 impl Readable for ChannelDetails {
9608         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9609                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9610                         (1, inbound_scid_alias, option),
9611                         (2, channel_id, required),
9612                         (3, channel_type, option),
9613                         (4, counterparty, required),
9614                         (5, outbound_scid_alias, option),
9615                         (6, funding_txo, option),
9616                         (7, config, option),
9617                         (8, short_channel_id, option),
9618                         (9, confirmations, option),
9619                         (10, channel_value_satoshis, required),
9620                         (12, unspendable_punishment_reserve, option),
9621                         (14, user_channel_id_low, required),
9622                         (16, balance_msat, required),
9623                         (18, outbound_capacity_msat, required),
9624                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9625                         // filled in, so we can safely unwrap it here.
9626                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9627                         (20, inbound_capacity_msat, required),
9628                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9629                         (22, confirmations_required, option),
9630                         (24, force_close_spend_delay, option),
9631                         (26, is_outbound, required),
9632                         (28, is_channel_ready, required),
9633                         (30, is_usable, required),
9634                         (32, is_public, required),
9635                         (33, inbound_htlc_minimum_msat, option),
9636                         (35, inbound_htlc_maximum_msat, option),
9637                         (37, user_channel_id_high_opt, option),
9638                         (39, feerate_sat_per_1000_weight, option),
9639                         (41, channel_shutdown_state, option),
9640                         (43, pending_inbound_htlcs, optional_vec),
9641                         (45, pending_outbound_htlcs, optional_vec),
9642                 });
9643
9644                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9645                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9646                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9647                 let user_channel_id = user_channel_id_low as u128 +
9648                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9649
9650                 Ok(Self {
9651                         inbound_scid_alias,
9652                         channel_id: channel_id.0.unwrap(),
9653                         channel_type,
9654                         counterparty: counterparty.0.unwrap(),
9655                         outbound_scid_alias,
9656                         funding_txo,
9657                         config,
9658                         short_channel_id,
9659                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9660                         unspendable_punishment_reserve,
9661                         user_channel_id,
9662                         balance_msat: balance_msat.0.unwrap(),
9663                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9664                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9665                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9666                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9667                         confirmations_required,
9668                         confirmations,
9669                         force_close_spend_delay,
9670                         is_outbound: is_outbound.0.unwrap(),
9671                         is_channel_ready: is_channel_ready.0.unwrap(),
9672                         is_usable: is_usable.0.unwrap(),
9673                         is_public: is_public.0.unwrap(),
9674                         inbound_htlc_minimum_msat,
9675                         inbound_htlc_maximum_msat,
9676                         feerate_sat_per_1000_weight,
9677                         channel_shutdown_state,
9678                         pending_inbound_htlcs: pending_inbound_htlcs.unwrap_or(Vec::new()),
9679                         pending_outbound_htlcs: pending_outbound_htlcs.unwrap_or(Vec::new()),
9680                 })
9681         }
9682 }
9683
9684 impl_writeable_tlv_based!(PhantomRouteHints, {
9685         (2, channels, required_vec),
9686         (4, phantom_scid, required),
9687         (6, real_node_pubkey, required),
9688 });
9689
9690 impl_writeable_tlv_based!(BlindedForward, {
9691         (0, inbound_blinding_point, required),
9692         (1, failure, (default_value, BlindedFailure::FromIntroductionNode)),
9693 });
9694
9695 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9696         (0, Forward) => {
9697                 (0, onion_packet, required),
9698                 (1, blinded, option),
9699                 (2, short_channel_id, required),
9700         },
9701         (1, Receive) => {
9702                 (0, payment_data, required),
9703                 (1, phantom_shared_secret, option),
9704                 (2, incoming_cltv_expiry, required),
9705                 (3, payment_metadata, option),
9706                 (5, custom_tlvs, optional_vec),
9707                 (7, requires_blinded_error, (default_value, false)),
9708         },
9709         (2, ReceiveKeysend) => {
9710                 (0, payment_preimage, required),
9711                 (2, incoming_cltv_expiry, required),
9712                 (3, payment_metadata, option),
9713                 (4, payment_data, option), // Added in 0.0.116
9714                 (5, custom_tlvs, optional_vec),
9715         },
9716 ;);
9717
9718 impl_writeable_tlv_based!(PendingHTLCInfo, {
9719         (0, routing, required),
9720         (2, incoming_shared_secret, required),
9721         (4, payment_hash, required),
9722         (6, outgoing_amt_msat, required),
9723         (8, outgoing_cltv_value, required),
9724         (9, incoming_amt_msat, option),
9725         (10, skimmed_fee_msat, option),
9726 });
9727
9728
9729 impl Writeable for HTLCFailureMsg {
9730         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9731                 match self {
9732                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9733                                 0u8.write(writer)?;
9734                                 channel_id.write(writer)?;
9735                                 htlc_id.write(writer)?;
9736                                 reason.write(writer)?;
9737                         },
9738                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9739                                 channel_id, htlc_id, sha256_of_onion, failure_code
9740                         }) => {
9741                                 1u8.write(writer)?;
9742                                 channel_id.write(writer)?;
9743                                 htlc_id.write(writer)?;
9744                                 sha256_of_onion.write(writer)?;
9745                                 failure_code.write(writer)?;
9746                         },
9747                 }
9748                 Ok(())
9749         }
9750 }
9751
9752 impl Readable for HTLCFailureMsg {
9753         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9754                 let id: u8 = Readable::read(reader)?;
9755                 match id {
9756                         0 => {
9757                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9758                                         channel_id: Readable::read(reader)?,
9759                                         htlc_id: Readable::read(reader)?,
9760                                         reason: Readable::read(reader)?,
9761                                 }))
9762                         },
9763                         1 => {
9764                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9765                                         channel_id: Readable::read(reader)?,
9766                                         htlc_id: Readable::read(reader)?,
9767                                         sha256_of_onion: Readable::read(reader)?,
9768                                         failure_code: Readable::read(reader)?,
9769                                 }))
9770                         },
9771                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9772                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9773                         // messages contained in the variants.
9774                         // In version 0.0.101, support for reading the variants with these types was added, and
9775                         // we should migrate to writing these variants when UpdateFailHTLC or
9776                         // UpdateFailMalformedHTLC get TLV fields.
9777                         2 => {
9778                                 let length: BigSize = Readable::read(reader)?;
9779                                 let mut s = FixedLengthReader::new(reader, length.0);
9780                                 let res = Readable::read(&mut s)?;
9781                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9782                                 Ok(HTLCFailureMsg::Relay(res))
9783                         },
9784                         3 => {
9785                                 let length: BigSize = Readable::read(reader)?;
9786                                 let mut s = FixedLengthReader::new(reader, length.0);
9787                                 let res = Readable::read(&mut s)?;
9788                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9789                                 Ok(HTLCFailureMsg::Malformed(res))
9790                         },
9791                         _ => Err(DecodeError::UnknownRequiredFeature),
9792                 }
9793         }
9794 }
9795
9796 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9797         (0, Forward),
9798         (1, Fail),
9799 );
9800
9801 impl_writeable_tlv_based_enum!(BlindedFailure,
9802         (0, FromIntroductionNode) => {},
9803         (2, FromBlindedNode) => {}, ;
9804 );
9805
9806 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9807         (0, short_channel_id, required),
9808         (1, phantom_shared_secret, option),
9809         (2, outpoint, required),
9810         (3, blinded_failure, option),
9811         (4, htlc_id, required),
9812         (6, incoming_packet_shared_secret, required),
9813         (7, user_channel_id, option),
9814         // Note that by the time we get past the required read for type 2 above, outpoint will be
9815         // filled in, so we can safely unwrap it here.
9816         (9, channel_id, (default_value, ChannelId::v1_from_funding_outpoint(outpoint.0.unwrap()))),
9817 });
9818
9819 impl Writeable for ClaimableHTLC {
9820         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9821                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9822                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9823                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9824                 };
9825                 write_tlv_fields!(writer, {
9826                         (0, self.prev_hop, required),
9827                         (1, self.total_msat, required),
9828                         (2, self.value, required),
9829                         (3, self.sender_intended_value, required),
9830                         (4, payment_data, option),
9831                         (5, self.total_value_received, option),
9832                         (6, self.cltv_expiry, required),
9833                         (8, keysend_preimage, option),
9834                         (10, self.counterparty_skimmed_fee_msat, option),
9835                 });
9836                 Ok(())
9837         }
9838 }
9839
9840 impl Readable for ClaimableHTLC {
9841         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9842                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9843                         (0, prev_hop, required),
9844                         (1, total_msat, option),
9845                         (2, value_ser, required),
9846                         (3, sender_intended_value, option),
9847                         (4, payment_data_opt, option),
9848                         (5, total_value_received, option),
9849                         (6, cltv_expiry, required),
9850                         (8, keysend_preimage, option),
9851                         (10, counterparty_skimmed_fee_msat, option),
9852                 });
9853                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9854                 let value = value_ser.0.unwrap();
9855                 let onion_payload = match keysend_preimage {
9856                         Some(p) => {
9857                                 if payment_data.is_some() {
9858                                         return Err(DecodeError::InvalidValue)
9859                                 }
9860                                 if total_msat.is_none() {
9861                                         total_msat = Some(value);
9862                                 }
9863                                 OnionPayload::Spontaneous(p)
9864                         },
9865                         None => {
9866                                 if total_msat.is_none() {
9867                                         if payment_data.is_none() {
9868                                                 return Err(DecodeError::InvalidValue)
9869                                         }
9870                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9871                                 }
9872                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9873                         },
9874                 };
9875                 Ok(Self {
9876                         prev_hop: prev_hop.0.unwrap(),
9877                         timer_ticks: 0,
9878                         value,
9879                         sender_intended_value: sender_intended_value.unwrap_or(value),
9880                         total_value_received,
9881                         total_msat: total_msat.unwrap(),
9882                         onion_payload,
9883                         cltv_expiry: cltv_expiry.0.unwrap(),
9884                         counterparty_skimmed_fee_msat,
9885                 })
9886         }
9887 }
9888
9889 impl Readable for HTLCSource {
9890         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9891                 let id: u8 = Readable::read(reader)?;
9892                 match id {
9893                         0 => {
9894                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9895                                 let mut first_hop_htlc_msat: u64 = 0;
9896                                 let mut path_hops = Vec::new();
9897                                 let mut payment_id = None;
9898                                 let mut payment_params: Option<PaymentParameters> = None;
9899                                 let mut blinded_tail: Option<BlindedTail> = None;
9900                                 read_tlv_fields!(reader, {
9901                                         (0, session_priv, required),
9902                                         (1, payment_id, option),
9903                                         (2, first_hop_htlc_msat, required),
9904                                         (4, path_hops, required_vec),
9905                                         (5, payment_params, (option: ReadableArgs, 0)),
9906                                         (6, blinded_tail, option),
9907                                 });
9908                                 if payment_id.is_none() {
9909                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9910                                         // instead.
9911                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9912                                 }
9913                                 let path = Path { hops: path_hops, blinded_tail };
9914                                 if path.hops.len() == 0 {
9915                                         return Err(DecodeError::InvalidValue);
9916                                 }
9917                                 if let Some(params) = payment_params.as_mut() {
9918                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9919                                                 if final_cltv_expiry_delta == &0 {
9920                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9921                                                 }
9922                                         }
9923                                 }
9924                                 Ok(HTLCSource::OutboundRoute {
9925                                         session_priv: session_priv.0.unwrap(),
9926                                         first_hop_htlc_msat,
9927                                         path,
9928                                         payment_id: payment_id.unwrap(),
9929                                 })
9930                         }
9931                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9932                         _ => Err(DecodeError::UnknownRequiredFeature),
9933                 }
9934         }
9935 }
9936
9937 impl Writeable for HTLCSource {
9938         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9939                 match self {
9940                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9941                                 0u8.write(writer)?;
9942                                 let payment_id_opt = Some(payment_id);
9943                                 write_tlv_fields!(writer, {
9944                                         (0, session_priv, required),
9945                                         (1, payment_id_opt, option),
9946                                         (2, first_hop_htlc_msat, required),
9947                                         // 3 was previously used to write a PaymentSecret for the payment.
9948                                         (4, path.hops, required_vec),
9949                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9950                                         (6, path.blinded_tail, option),
9951                                  });
9952                         }
9953                         HTLCSource::PreviousHopData(ref field) => {
9954                                 1u8.write(writer)?;
9955                                 field.write(writer)?;
9956                         }
9957                 }
9958                 Ok(())
9959         }
9960 }
9961
9962 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9963         (0, forward_info, required),
9964         (1, prev_user_channel_id, (default_value, 0)),
9965         (2, prev_short_channel_id, required),
9966         (4, prev_htlc_id, required),
9967         (6, prev_funding_outpoint, required),
9968         // Note that by the time we get past the required read for type 6 above, prev_funding_outpoint will be
9969         // filled in, so we can safely unwrap it here.
9970         (7, prev_channel_id, (default_value, ChannelId::v1_from_funding_outpoint(prev_funding_outpoint.0.unwrap()))),
9971 });
9972
9973 impl Writeable for HTLCForwardInfo {
9974         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9975                 const FAIL_HTLC_VARIANT_ID: u8 = 1;
9976                 match self {
9977                         Self::AddHTLC(info) => {
9978                                 0u8.write(w)?;
9979                                 info.write(w)?;
9980                         },
9981                         Self::FailHTLC { htlc_id, err_packet } => {
9982                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9983                                 write_tlv_fields!(w, {
9984                                         (0, htlc_id, required),
9985                                         (2, err_packet, required),
9986                                 });
9987                         },
9988                         Self::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
9989                                 // Since this variant was added in 0.0.119, write this as `::FailHTLC` with an empty error
9990                                 // packet so older versions have something to fail back with, but serialize the real data as
9991                                 // optional TLVs for the benefit of newer versions.
9992                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9993                                 let dummy_err_packet = msgs::OnionErrorPacket { data: Vec::new() };
9994                                 write_tlv_fields!(w, {
9995                                         (0, htlc_id, required),
9996                                         (1, failure_code, required),
9997                                         (2, dummy_err_packet, required),
9998                                         (3, sha256_of_onion, required),
9999                                 });
10000                         },
10001                 }
10002                 Ok(())
10003         }
10004 }
10005
10006 impl Readable for HTLCForwardInfo {
10007         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
10008                 let id: u8 = Readable::read(r)?;
10009                 Ok(match id {
10010                         0 => Self::AddHTLC(Readable::read(r)?),
10011                         1 => {
10012                                 _init_and_read_len_prefixed_tlv_fields!(r, {
10013                                         (0, htlc_id, required),
10014                                         (1, malformed_htlc_failure_code, option),
10015                                         (2, err_packet, required),
10016                                         (3, sha256_of_onion, option),
10017                                 });
10018                                 if let Some(failure_code) = malformed_htlc_failure_code {
10019                                         Self::FailMalformedHTLC {
10020                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
10021                                                 failure_code,
10022                                                 sha256_of_onion: sha256_of_onion.ok_or(DecodeError::InvalidValue)?,
10023                                         }
10024                                 } else {
10025                                         Self::FailHTLC {
10026                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
10027                                                 err_packet: _init_tlv_based_struct_field!(err_packet, required),
10028                                         }
10029                                 }
10030                         },
10031                         _ => return Err(DecodeError::InvalidValue),
10032                 })
10033         }
10034 }
10035
10036 impl_writeable_tlv_based!(PendingInboundPayment, {
10037         (0, payment_secret, required),
10038         (2, expiry_time, required),
10039         (4, user_payment_id, required),
10040         (6, payment_preimage, required),
10041         (8, min_value_msat, required),
10042 });
10043
10044 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> Writeable for ChannelManager<M, T, ES, NS, SP, F, R, L>
10045 where
10046         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10047         T::Target: BroadcasterInterface,
10048         ES::Target: EntropySource,
10049         NS::Target: NodeSigner,
10050         SP::Target: SignerProvider,
10051         F::Target: FeeEstimator,
10052         R::Target: Router,
10053         L::Target: Logger,
10054 {
10055         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
10056                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
10057
10058                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
10059
10060                 self.chain_hash.write(writer)?;
10061                 {
10062                         let best_block = self.best_block.read().unwrap();
10063                         best_block.height().write(writer)?;
10064                         best_block.block_hash().write(writer)?;
10065                 }
10066
10067                 let mut serializable_peer_count: u64 = 0;
10068                 {
10069                         let per_peer_state = self.per_peer_state.read().unwrap();
10070                         let mut number_of_funded_channels = 0;
10071                         for (_, peer_state_mutex) in per_peer_state.iter() {
10072                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10073                                 let peer_state = &mut *peer_state_lock;
10074                                 if !peer_state.ok_to_remove(false) {
10075                                         serializable_peer_count += 1;
10076                                 }
10077
10078                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
10079                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
10080                                 ).count();
10081                         }
10082
10083                         (number_of_funded_channels as u64).write(writer)?;
10084
10085                         for (_, peer_state_mutex) in per_peer_state.iter() {
10086                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
10087                                 let peer_state = &mut *peer_state_lock;
10088                                 for channel in peer_state.channel_by_id.iter().filter_map(
10089                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
10090                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
10091                                         } else { None }
10092                                 ) {
10093                                         channel.write(writer)?;
10094                                 }
10095                         }
10096                 }
10097
10098                 {
10099                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
10100                         (forward_htlcs.len() as u64).write(writer)?;
10101                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
10102                                 short_channel_id.write(writer)?;
10103                                 (pending_forwards.len() as u64).write(writer)?;
10104                                 for forward in pending_forwards {
10105                                         forward.write(writer)?;
10106                                 }
10107                         }
10108                 }
10109
10110                 let per_peer_state = self.per_peer_state.write().unwrap();
10111
10112                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
10113                 let claimable_payments = self.claimable_payments.lock().unwrap();
10114                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
10115
10116                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
10117                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
10118                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
10119                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
10120                         payment_hash.write(writer)?;
10121                         (payment.htlcs.len() as u64).write(writer)?;
10122                         for htlc in payment.htlcs.iter() {
10123                                 htlc.write(writer)?;
10124                         }
10125                         htlc_purposes.push(&payment.purpose);
10126                         htlc_onion_fields.push(&payment.onion_fields);
10127                 }
10128
10129                 let mut monitor_update_blocked_actions_per_peer = None;
10130                 let mut peer_states = Vec::new();
10131                 for (_, peer_state_mutex) in per_peer_state.iter() {
10132                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
10133                         // of a lockorder violation deadlock - no other thread can be holding any
10134                         // per_peer_state lock at all.
10135                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
10136                 }
10137
10138                 (serializable_peer_count).write(writer)?;
10139                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
10140                         // Peers which we have no channels to should be dropped once disconnected. As we
10141                         // disconnect all peers when shutting down and serializing the ChannelManager, we
10142                         // consider all peers as disconnected here. There's therefore no need write peers with
10143                         // no channels.
10144                         if !peer_state.ok_to_remove(false) {
10145                                 peer_pubkey.write(writer)?;
10146                                 peer_state.latest_features.write(writer)?;
10147                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
10148                                         monitor_update_blocked_actions_per_peer
10149                                                 .get_or_insert_with(Vec::new)
10150                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
10151                                 }
10152                         }
10153                 }
10154
10155                 let events = self.pending_events.lock().unwrap();
10156                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
10157                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
10158                 // refuse to read the new ChannelManager.
10159                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
10160                 if events_not_backwards_compatible {
10161                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
10162                         // well save the space and not write any events here.
10163                         0u64.write(writer)?;
10164                 } else {
10165                         (events.len() as u64).write(writer)?;
10166                         for (event, _) in events.iter() {
10167                                 event.write(writer)?;
10168                         }
10169                 }
10170
10171                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
10172                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
10173                 // the closing monitor updates were always effectively replayed on startup (either directly
10174                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
10175                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
10176                 0u64.write(writer)?;
10177
10178                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
10179                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
10180                 // likely to be identical.
10181                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10182                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10183
10184                 (pending_inbound_payments.len() as u64).write(writer)?;
10185                 for (hash, pending_payment) in pending_inbound_payments.iter() {
10186                         hash.write(writer)?;
10187                         pending_payment.write(writer)?;
10188                 }
10189
10190                 // For backwards compat, write the session privs and their total length.
10191                 let mut num_pending_outbounds_compat: u64 = 0;
10192                 for (_, outbound) in pending_outbound_payments.iter() {
10193                         if !outbound.is_fulfilled() && !outbound.abandoned() {
10194                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
10195                         }
10196                 }
10197                 num_pending_outbounds_compat.write(writer)?;
10198                 for (_, outbound) in pending_outbound_payments.iter() {
10199                         match outbound {
10200                                 PendingOutboundPayment::Legacy { session_privs } |
10201                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10202                                         for session_priv in session_privs.iter() {
10203                                                 session_priv.write(writer)?;
10204                                         }
10205                                 }
10206                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
10207                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
10208                                 PendingOutboundPayment::Fulfilled { .. } => {},
10209                                 PendingOutboundPayment::Abandoned { .. } => {},
10210                         }
10211                 }
10212
10213                 // Encode without retry info for 0.0.101 compatibility.
10214                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = new_hash_map();
10215                 for (id, outbound) in pending_outbound_payments.iter() {
10216                         match outbound {
10217                                 PendingOutboundPayment::Legacy { session_privs } |
10218                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10219                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
10220                                 },
10221                                 _ => {},
10222                         }
10223                 }
10224
10225                 let mut pending_intercepted_htlcs = None;
10226                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
10227                 if our_pending_intercepts.len() != 0 {
10228                         pending_intercepted_htlcs = Some(our_pending_intercepts);
10229                 }
10230
10231                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
10232                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
10233                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
10234                         // map. Thus, if there are no entries we skip writing a TLV for it.
10235                         pending_claiming_payments = None;
10236                 }
10237
10238                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
10239                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
10240                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
10241                                 if !updates.is_empty() {
10242                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(new_hash_map()); }
10243                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
10244                                 }
10245                         }
10246                 }
10247
10248                 write_tlv_fields!(writer, {
10249                         (1, pending_outbound_payments_no_retry, required),
10250                         (2, pending_intercepted_htlcs, option),
10251                         (3, pending_outbound_payments, required),
10252                         (4, pending_claiming_payments, option),
10253                         (5, self.our_network_pubkey, required),
10254                         (6, monitor_update_blocked_actions_per_peer, option),
10255                         (7, self.fake_scid_rand_bytes, required),
10256                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
10257                         (9, htlc_purposes, required_vec),
10258                         (10, in_flight_monitor_updates, option),
10259                         (11, self.probing_cookie_secret, required),
10260                         (13, htlc_onion_fields, optional_vec),
10261                 });
10262
10263                 Ok(())
10264         }
10265 }
10266
10267 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
10268         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
10269                 (self.len() as u64).write(w)?;
10270                 for (event, action) in self.iter() {
10271                         event.write(w)?;
10272                         action.write(w)?;
10273                         #[cfg(debug_assertions)] {
10274                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
10275                                 // be persisted and are regenerated on restart. However, if such an event has a
10276                                 // post-event-handling action we'll write nothing for the event and would have to
10277                                 // either forget the action or fail on deserialization (which we do below). Thus,
10278                                 // check that the event is sane here.
10279                                 let event_encoded = event.encode();
10280                                 let event_read: Option<Event> =
10281                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
10282                                 if action.is_some() { assert!(event_read.is_some()); }
10283                         }
10284                 }
10285                 Ok(())
10286         }
10287 }
10288 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
10289         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
10290                 let len: u64 = Readable::read(reader)?;
10291                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
10292                 let mut events: Self = VecDeque::with_capacity(cmp::min(
10293                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
10294                         len) as usize);
10295                 for _ in 0..len {
10296                         let ev_opt = MaybeReadable::read(reader)?;
10297                         let action = Readable::read(reader)?;
10298                         if let Some(ev) = ev_opt {
10299                                 events.push_back((ev, action));
10300                         } else if action.is_some() {
10301                                 return Err(DecodeError::InvalidValue);
10302                         }
10303                 }
10304                 Ok(events)
10305         }
10306 }
10307
10308 impl_writeable_tlv_based_enum!(ChannelShutdownState,
10309         (0, NotShuttingDown) => {},
10310         (2, ShutdownInitiated) => {},
10311         (4, ResolvingHTLCs) => {},
10312         (6, NegotiatingClosingFee) => {},
10313         (8, ShutdownComplete) => {}, ;
10314 );
10315
10316 /// Arguments for the creation of a ChannelManager that are not deserialized.
10317 ///
10318 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
10319 /// is:
10320 /// 1) Deserialize all stored [`ChannelMonitor`]s.
10321 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
10322 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
10323 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
10324 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
10325 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
10326 ///    same way you would handle a [`chain::Filter`] call using
10327 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
10328 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
10329 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
10330 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
10331 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
10332 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
10333 ///    the next step.
10334 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
10335 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
10336 ///
10337 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
10338 /// call any other methods on the newly-deserialized [`ChannelManager`].
10339 ///
10340 /// Note that because some channels may be closed during deserialization, it is critical that you
10341 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
10342 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
10343 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
10344 /// not force-close the same channels but consider them live), you may end up revoking a state for
10345 /// which you've already broadcasted the transaction.
10346 ///
10347 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
10348 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10349 where
10350         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10351         T::Target: BroadcasterInterface,
10352         ES::Target: EntropySource,
10353         NS::Target: NodeSigner,
10354         SP::Target: SignerProvider,
10355         F::Target: FeeEstimator,
10356         R::Target: Router,
10357         L::Target: Logger,
10358 {
10359         /// A cryptographically secure source of entropy.
10360         pub entropy_source: ES,
10361
10362         /// A signer that is able to perform node-scoped cryptographic operations.
10363         pub node_signer: NS,
10364
10365         /// The keys provider which will give us relevant keys. Some keys will be loaded during
10366         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
10367         /// signing data.
10368         pub signer_provider: SP,
10369
10370         /// The fee_estimator for use in the ChannelManager in the future.
10371         ///
10372         /// No calls to the FeeEstimator will be made during deserialization.
10373         pub fee_estimator: F,
10374         /// The chain::Watch for use in the ChannelManager in the future.
10375         ///
10376         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
10377         /// you have deserialized ChannelMonitors separately and will add them to your
10378         /// chain::Watch after deserializing this ChannelManager.
10379         pub chain_monitor: M,
10380
10381         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
10382         /// used to broadcast the latest local commitment transactions of channels which must be
10383         /// force-closed during deserialization.
10384         pub tx_broadcaster: T,
10385         /// The router which will be used in the ChannelManager in the future for finding routes
10386         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
10387         ///
10388         /// No calls to the router will be made during deserialization.
10389         pub router: R,
10390         /// The Logger for use in the ChannelManager and which may be used to log information during
10391         /// deserialization.
10392         pub logger: L,
10393         /// Default settings used for new channels. Any existing channels will continue to use the
10394         /// runtime settings which were stored when the ChannelManager was serialized.
10395         pub default_config: UserConfig,
10396
10397         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
10398         /// value.context.get_funding_txo() should be the key).
10399         ///
10400         /// If a monitor is inconsistent with the channel state during deserialization the channel will
10401         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
10402         /// is true for missing channels as well. If there is a monitor missing for which we find
10403         /// channel data Err(DecodeError::InvalidValue) will be returned.
10404         ///
10405         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
10406         /// this struct.
10407         ///
10408         /// This is not exported to bindings users because we have no HashMap bindings
10409         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>,
10410 }
10411
10412 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10413                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
10414 where
10415         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10416         T::Target: BroadcasterInterface,
10417         ES::Target: EntropySource,
10418         NS::Target: NodeSigner,
10419         SP::Target: SignerProvider,
10420         F::Target: FeeEstimator,
10421         R::Target: Router,
10422         L::Target: Logger,
10423 {
10424         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
10425         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
10426         /// populate a HashMap directly from C.
10427         pub fn new(entropy_source: ES, node_signer: NS, signer_provider: SP, fee_estimator: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, default_config: UserConfig,
10428                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>) -> Self {
10429                 Self {
10430                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10431                         channel_monitors: hash_map_from_iter(
10432                                 channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) })
10433                         ),
10434                 }
10435         }
10436 }
10437
10438 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10439 // SipmleArcChannelManager type:
10440 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10441         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10442 where
10443         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10444         T::Target: BroadcasterInterface,
10445         ES::Target: EntropySource,
10446         NS::Target: NodeSigner,
10447         SP::Target: SignerProvider,
10448         F::Target: FeeEstimator,
10449         R::Target: Router,
10450         L::Target: Logger,
10451 {
10452         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10453                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10454                 Ok((blockhash, Arc::new(chan_manager)))
10455         }
10456 }
10457
10458 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10459         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10460 where
10461         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10462         T::Target: BroadcasterInterface,
10463         ES::Target: EntropySource,
10464         NS::Target: NodeSigner,
10465         SP::Target: SignerProvider,
10466         F::Target: FeeEstimator,
10467         R::Target: Router,
10468         L::Target: Logger,
10469 {
10470         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10471                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10472
10473                 let chain_hash: ChainHash = Readable::read(reader)?;
10474                 let best_block_height: u32 = Readable::read(reader)?;
10475                 let best_block_hash: BlockHash = Readable::read(reader)?;
10476
10477                 let mut failed_htlcs = Vec::new();
10478
10479                 let channel_count: u64 = Readable::read(reader)?;
10480                 let mut funding_txo_set = hash_set_with_capacity(cmp::min(channel_count as usize, 128));
10481                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = hash_map_with_capacity(cmp::min(channel_count as usize, 128));
10482                 let mut outpoint_to_peer = hash_map_with_capacity(cmp::min(channel_count as usize, 128));
10483                 let mut short_to_chan_info = hash_map_with_capacity(cmp::min(channel_count as usize, 128));
10484                 let mut channel_closures = VecDeque::new();
10485                 let mut close_background_events = Vec::new();
10486                 let mut funding_txo_to_channel_id = hash_map_with_capacity(channel_count as usize);
10487                 for _ in 0..channel_count {
10488                         let mut channel: Channel<SP> = Channel::read(reader, (
10489                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10490                         ))?;
10491                         let logger = WithChannelContext::from(&args.logger, &channel.context);
10492                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10493                         funding_txo_to_channel_id.insert(funding_txo, channel.context.channel_id());
10494                         funding_txo_set.insert(funding_txo.clone());
10495                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10496                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10497                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10498                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10499                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10500                                         // But if the channel is behind of the monitor, close the channel:
10501                                         log_error!(logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10502                                         log_error!(logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10503                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10504                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10505                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10506                                         }
10507                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10508                                                 log_error!(logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10509                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10510                                         }
10511                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10512                                                 log_error!(logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10513                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10514                                         }
10515                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10516                                                 log_error!(logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10517                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10518                                         }
10519                                         let mut shutdown_result = channel.context.force_shutdown(true, ClosureReason::OutdatedChannelManager);
10520                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10521                                                 return Err(DecodeError::InvalidValue);
10522                                         }
10523                                         if let Some((counterparty_node_id, funding_txo, channel_id, update)) = shutdown_result.monitor_update {
10524                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10525                                                         counterparty_node_id, funding_txo, channel_id, update
10526                                                 });
10527                                         }
10528                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10529                                         channel_closures.push_back((events::Event::ChannelClosed {
10530                                                 channel_id: channel.context.channel_id(),
10531                                                 user_channel_id: channel.context.get_user_id(),
10532                                                 reason: ClosureReason::OutdatedChannelManager,
10533                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10534                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10535                                                 channel_funding_txo: channel.context.get_funding_txo(),
10536                                         }, None));
10537                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10538                                                 let mut found_htlc = false;
10539                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10540                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10541                                                 }
10542                                                 if !found_htlc {
10543                                                         // If we have some HTLCs in the channel which are not present in the newer
10544                                                         // ChannelMonitor, they have been removed and should be failed back to
10545                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10546                                                         // were actually claimed we'd have generated and ensured the previous-hop
10547                                                         // claim update ChannelMonitor updates were persisted prior to persising
10548                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10549                                                         // backwards leg of the HTLC will simply be rejected.
10550                                                         log_info!(logger,
10551                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10552                                                                 &channel.context.channel_id(), &payment_hash);
10553                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10554                                                 }
10555                                         }
10556                                 } else {
10557                                         log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10558                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10559                                                 monitor.get_latest_update_id());
10560                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10561                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10562                                         }
10563                                         if let Some(funding_txo) = channel.context.get_funding_txo() {
10564                                                 outpoint_to_peer.insert(funding_txo, channel.context.get_counterparty_node_id());
10565                                         }
10566                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10567                                                 hash_map::Entry::Occupied(mut entry) => {
10568                                                         let by_id_map = entry.get_mut();
10569                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10570                                                 },
10571                                                 hash_map::Entry::Vacant(entry) => {
10572                                                         let mut by_id_map = new_hash_map();
10573                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10574                                                         entry.insert(by_id_map);
10575                                                 }
10576                                         }
10577                                 }
10578                         } else if channel.is_awaiting_initial_mon_persist() {
10579                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10580                                 // was in-progress, we never broadcasted the funding transaction and can still
10581                                 // safely discard the channel.
10582                                 let _ = channel.context.force_shutdown(false, ClosureReason::DisconnectedPeer);
10583                                 channel_closures.push_back((events::Event::ChannelClosed {
10584                                         channel_id: channel.context.channel_id(),
10585                                         user_channel_id: channel.context.get_user_id(),
10586                                         reason: ClosureReason::DisconnectedPeer,
10587                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10588                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10589                                         channel_funding_txo: channel.context.get_funding_txo(),
10590                                 }, None));
10591                         } else {
10592                                 log_error!(logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10593                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10594                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10595                                 log_error!(logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10596                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10597                                 return Err(DecodeError::InvalidValue);
10598                         }
10599                 }
10600
10601                 for (funding_txo, monitor) in args.channel_monitors.iter() {
10602                         if !funding_txo_set.contains(funding_txo) {
10603                                 let logger = WithChannelMonitor::from(&args.logger, monitor);
10604                                 let channel_id = monitor.channel_id();
10605                                 log_info!(logger, "Queueing monitor update to ensure missing channel {} is force closed",
10606                                         &channel_id);
10607                                 let monitor_update = ChannelMonitorUpdate {
10608                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10609                                         counterparty_node_id: None,
10610                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10611                                         channel_id: Some(monitor.channel_id()),
10612                                 };
10613                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, channel_id, monitor_update)));
10614                         }
10615                 }
10616
10617                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10618                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10619                 let mut forward_htlcs = hash_map_with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10620                 for _ in 0..forward_htlcs_count {
10621                         let short_channel_id = Readable::read(reader)?;
10622                         let pending_forwards_count: u64 = Readable::read(reader)?;
10623                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10624                         for _ in 0..pending_forwards_count {
10625                                 pending_forwards.push(Readable::read(reader)?);
10626                         }
10627                         forward_htlcs.insert(short_channel_id, pending_forwards);
10628                 }
10629
10630                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10631                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10632                 for _ in 0..claimable_htlcs_count {
10633                         let payment_hash = Readable::read(reader)?;
10634                         let previous_hops_len: u64 = Readable::read(reader)?;
10635                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10636                         for _ in 0..previous_hops_len {
10637                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10638                         }
10639                         claimable_htlcs_list.push((payment_hash, previous_hops));
10640                 }
10641
10642                 let peer_state_from_chans = |channel_by_id| {
10643                         PeerState {
10644                                 channel_by_id,
10645                                 inbound_channel_request_by_id: new_hash_map(),
10646                                 latest_features: InitFeatures::empty(),
10647                                 pending_msg_events: Vec::new(),
10648                                 in_flight_monitor_updates: BTreeMap::new(),
10649                                 monitor_update_blocked_actions: BTreeMap::new(),
10650                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10651                                 is_connected: false,
10652                         }
10653                 };
10654
10655                 let peer_count: u64 = Readable::read(reader)?;
10656                 let mut per_peer_state = hash_map_with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10657                 for _ in 0..peer_count {
10658                         let peer_pubkey = Readable::read(reader)?;
10659                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(new_hash_map());
10660                         let mut peer_state = peer_state_from_chans(peer_chans);
10661                         peer_state.latest_features = Readable::read(reader)?;
10662                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10663                 }
10664
10665                 let event_count: u64 = Readable::read(reader)?;
10666                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10667                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10668                 for _ in 0..event_count {
10669                         match MaybeReadable::read(reader)? {
10670                                 Some(event) => pending_events_read.push_back((event, None)),
10671                                 None => continue,
10672                         }
10673                 }
10674
10675                 let background_event_count: u64 = Readable::read(reader)?;
10676                 for _ in 0..background_event_count {
10677                         match <u8 as Readable>::read(reader)? {
10678                                 0 => {
10679                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10680                                         // however we really don't (and never did) need them - we regenerate all
10681                                         // on-startup monitor updates.
10682                                         let _: OutPoint = Readable::read(reader)?;
10683                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10684                                 }
10685                                 _ => return Err(DecodeError::InvalidValue),
10686                         }
10687                 }
10688
10689                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10690                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10691
10692                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10693                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = hash_map_with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10694                 for _ in 0..pending_inbound_payment_count {
10695                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10696                                 return Err(DecodeError::InvalidValue);
10697                         }
10698                 }
10699
10700                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10701                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10702                         hash_map_with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10703                 for _ in 0..pending_outbound_payments_count_compat {
10704                         let session_priv = Readable::read(reader)?;
10705                         let payment = PendingOutboundPayment::Legacy {
10706                                 session_privs: hash_set_from_iter([session_priv]),
10707                         };
10708                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10709                                 return Err(DecodeError::InvalidValue)
10710                         };
10711                 }
10712
10713                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10714                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10715                 let mut pending_outbound_payments = None;
10716                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(new_hash_map());
10717                 let mut received_network_pubkey: Option<PublicKey> = None;
10718                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10719                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10720                 let mut claimable_htlc_purposes = None;
10721                 let mut claimable_htlc_onion_fields = None;
10722                 let mut pending_claiming_payments = Some(new_hash_map());
10723                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10724                 let mut events_override = None;
10725                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10726                 read_tlv_fields!(reader, {
10727                         (1, pending_outbound_payments_no_retry, option),
10728                         (2, pending_intercepted_htlcs, option),
10729                         (3, pending_outbound_payments, option),
10730                         (4, pending_claiming_payments, option),
10731                         (5, received_network_pubkey, option),
10732                         (6, monitor_update_blocked_actions_per_peer, option),
10733                         (7, fake_scid_rand_bytes, option),
10734                         (8, events_override, option),
10735                         (9, claimable_htlc_purposes, optional_vec),
10736                         (10, in_flight_monitor_updates, option),
10737                         (11, probing_cookie_secret, option),
10738                         (13, claimable_htlc_onion_fields, optional_vec),
10739                 });
10740                 if fake_scid_rand_bytes.is_none() {
10741                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10742                 }
10743
10744                 if probing_cookie_secret.is_none() {
10745                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10746                 }
10747
10748                 if let Some(events) = events_override {
10749                         pending_events_read = events;
10750                 }
10751
10752                 if !channel_closures.is_empty() {
10753                         pending_events_read.append(&mut channel_closures);
10754                 }
10755
10756                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10757                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10758                 } else if pending_outbound_payments.is_none() {
10759                         let mut outbounds = new_hash_map();
10760                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10761                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10762                         }
10763                         pending_outbound_payments = Some(outbounds);
10764                 }
10765                 let pending_outbounds = OutboundPayments {
10766                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10767                         retry_lock: Mutex::new(())
10768                 };
10769
10770                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10771                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10772                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10773                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10774                 // `ChannelMonitor` for it.
10775                 //
10776                 // In order to do so we first walk all of our live channels (so that we can check their
10777                 // state immediately after doing the update replays, when we have the `update_id`s
10778                 // available) and then walk any remaining in-flight updates.
10779                 //
10780                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10781                 let mut pending_background_events = Vec::new();
10782                 macro_rules! handle_in_flight_updates {
10783                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10784                          $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr
10785                         ) => { {
10786                                 let mut max_in_flight_update_id = 0;
10787                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10788                                 for update in $chan_in_flight_upds.iter() {
10789                                         log_trace!($logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10790                                                 update.update_id, $channel_info_log, &$monitor.channel_id());
10791                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10792                                         pending_background_events.push(
10793                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10794                                                         counterparty_node_id: $counterparty_node_id,
10795                                                         funding_txo: $funding_txo,
10796                                                         channel_id: $monitor.channel_id(),
10797                                                         update: update.clone(),
10798                                                 });
10799                                 }
10800                                 if $chan_in_flight_upds.is_empty() {
10801                                         // We had some updates to apply, but it turns out they had completed before we
10802                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10803                                         // the completion actions for any monitor updates, but otherwise are done.
10804                                         pending_background_events.push(
10805                                                 BackgroundEvent::MonitorUpdatesComplete {
10806                                                         counterparty_node_id: $counterparty_node_id,
10807                                                         channel_id: $monitor.channel_id(),
10808                                                 });
10809                                 }
10810                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10811                                         log_error!($logger, "Duplicate in-flight monitor update set for the same channel!");
10812                                         return Err(DecodeError::InvalidValue);
10813                                 }
10814                                 max_in_flight_update_id
10815                         } }
10816                 }
10817
10818                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10819                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10820                         let peer_state = &mut *peer_state_lock;
10821                         for phase in peer_state.channel_by_id.values() {
10822                                 if let ChannelPhase::Funded(chan) = phase {
10823                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10824
10825                                         // Channels that were persisted have to be funded, otherwise they should have been
10826                                         // discarded.
10827                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10828                                         let monitor = args.channel_monitors.get(&funding_txo)
10829                                                 .expect("We already checked for monitor presence when loading channels");
10830                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10831                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10832                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10833                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10834                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10835                                                                         funding_txo, monitor, peer_state, logger, ""));
10836                                                 }
10837                                         }
10838                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10839                                                 // If the channel is ahead of the monitor, return InvalidValue:
10840                                                 log_error!(logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10841                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10842                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10843                                                 log_error!(logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10844                                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10845                                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10846                                                 log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10847                                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10848                                                 return Err(DecodeError::InvalidValue);
10849                                         }
10850                                 } else {
10851                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10852                                         // created in this `channel_by_id` map.
10853                                         debug_assert!(false);
10854                                         return Err(DecodeError::InvalidValue);
10855                                 }
10856                         }
10857                 }
10858
10859                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10860                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10861                                 let channel_id = funding_txo_to_channel_id.get(&funding_txo).copied();
10862                                 let logger = WithContext::from(&args.logger, Some(counterparty_id), channel_id);
10863                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10864                                         // Now that we've removed all the in-flight monitor updates for channels that are
10865                                         // still open, we need to replay any monitor updates that are for closed channels,
10866                                         // creating the neccessary peer_state entries as we go.
10867                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10868                                                 Mutex::new(peer_state_from_chans(new_hash_map()))
10869                                         });
10870                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10871                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10872                                                 funding_txo, monitor, peer_state, logger, "closed ");
10873                                 } else {
10874                                         log_error!(logger, "A ChannelMonitor is missing even though we have in-flight updates for it! This indicates a potentially-critical violation of the chain::Watch API!");
10875                                         log_error!(logger, " The ChannelMonitor for channel {} is missing.", if let Some(channel_id) =
10876                                                 channel_id { channel_id.to_string() } else { format!("with outpoint {}", funding_txo) } );
10877                                         log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10878                                         log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10879                                         log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10880                                         log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10881                                         return Err(DecodeError::InvalidValue);
10882                                 }
10883                         }
10884                 }
10885
10886                 // Note that we have to do the above replays before we push new monitor updates.
10887                 pending_background_events.append(&mut close_background_events);
10888
10889                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10890                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10891                 // have a fully-constructed `ChannelManager` at the end.
10892                 let mut pending_claims_to_replay = Vec::new();
10893
10894                 {
10895                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10896                         // ChannelMonitor data for any channels for which we do not have authorative state
10897                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10898                         // corresponding `Channel` at all).
10899                         // This avoids several edge-cases where we would otherwise "forget" about pending
10900                         // payments which are still in-flight via their on-chain state.
10901                         // We only rebuild the pending payments map if we were most recently serialized by
10902                         // 0.0.102+
10903                         for (_, monitor) in args.channel_monitors.iter() {
10904                                 let counterparty_opt = outpoint_to_peer.get(&monitor.get_funding_txo().0);
10905                                 if counterparty_opt.is_none() {
10906                                         let logger = WithChannelMonitor::from(&args.logger, monitor);
10907                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10908                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10909                                                         if path.hops.is_empty() {
10910                                                                 log_error!(logger, "Got an empty path for a pending payment");
10911                                                                 return Err(DecodeError::InvalidValue);
10912                                                         }
10913
10914                                                         let path_amt = path.final_value_msat();
10915                                                         let mut session_priv_bytes = [0; 32];
10916                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10917                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10918                                                                 hash_map::Entry::Occupied(mut entry) => {
10919                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10920                                                                         log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10921                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), htlc.payment_hash);
10922                                                                 },
10923                                                                 hash_map::Entry::Vacant(entry) => {
10924                                                                         let path_fee = path.fee_msat();
10925                                                                         entry.insert(PendingOutboundPayment::Retryable {
10926                                                                                 retry_strategy: None,
10927                                                                                 attempts: PaymentAttempts::new(),
10928                                                                                 payment_params: None,
10929                                                                                 session_privs: hash_set_from_iter([session_priv_bytes]),
10930                                                                                 payment_hash: htlc.payment_hash,
10931                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10932                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10933                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10934                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10935                                                                                 pending_amt_msat: path_amt,
10936                                                                                 pending_fee_msat: Some(path_fee),
10937                                                                                 total_msat: path_amt,
10938                                                                                 starting_block_height: best_block_height,
10939                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10940                                                                         });
10941                                                                         log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10942                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10943                                                                 }
10944                                                         }
10945                                                 }
10946                                         }
10947                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10948                                                 match htlc_source {
10949                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10950                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10951                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10952                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10953                                                                 };
10954                                                                 // The ChannelMonitor is now responsible for this HTLC's
10955                                                                 // failure/success and will let us know what its outcome is. If we
10956                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10957                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10958                                                                 // the monitor was when forwarding the payment.
10959                                                                 forward_htlcs.retain(|_, forwards| {
10960                                                                         forwards.retain(|forward| {
10961                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10962                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10963                                                                                                 log_info!(logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10964                                                                                                         &htlc.payment_hash, &monitor.channel_id());
10965                                                                                                 false
10966                                                                                         } else { true }
10967                                                                                 } else { true }
10968                                                                         });
10969                                                                         !forwards.is_empty()
10970                                                                 });
10971                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10972                                                                         if pending_forward_matches_htlc(&htlc_info) {
10973                                                                                 log_info!(logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10974                                                                                         &htlc.payment_hash, &monitor.channel_id());
10975                                                                                 pending_events_read.retain(|(event, _)| {
10976                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10977                                                                                                 intercepted_id != ev_id
10978                                                                                         } else { true }
10979                                                                                 });
10980                                                                                 false
10981                                                                         } else { true }
10982                                                                 });
10983                                                         },
10984                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10985                                                                 if let Some(preimage) = preimage_opt {
10986                                                                         let pending_events = Mutex::new(pending_events_read);
10987                                                                         // Note that we set `from_onchain` to "false" here,
10988                                                                         // deliberately keeping the pending payment around forever.
10989                                                                         // Given it should only occur when we have a channel we're
10990                                                                         // force-closing for being stale that's okay.
10991                                                                         // The alternative would be to wipe the state when claiming,
10992                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10993                                                                         // it and the `PaymentSent` on every restart until the
10994                                                                         // `ChannelMonitor` is removed.
10995                                                                         let compl_action =
10996                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10997                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10998                                                                                         channel_id: monitor.channel_id(),
10999                                                                                         counterparty_node_id: path.hops[0].pubkey,
11000                                                                                 };
11001                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
11002                                                                                 path, false, compl_action, &pending_events, &&logger);
11003                                                                         pending_events_read = pending_events.into_inner().unwrap();
11004                                                                 }
11005                                                         },
11006                                                 }
11007                                         }
11008                                 }
11009
11010                                 // Whether the downstream channel was closed or not, try to re-apply any payment
11011                                 // preimages from it which may be needed in upstream channels for forwarded
11012                                 // payments.
11013                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
11014                                         .into_iter()
11015                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
11016                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
11017                                                         if let Some(payment_preimage) = preimage_opt {
11018                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
11019                                                                         // Check if `counterparty_opt.is_none()` to see if the
11020                                                                         // downstream chan is closed (because we don't have a
11021                                                                         // channel_id -> peer map entry).
11022                                                                         counterparty_opt.is_none(),
11023                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
11024                                                                         monitor.get_funding_txo().0, monitor.channel_id()))
11025                                                         } else { None }
11026                                                 } else {
11027                                                         // If it was an outbound payment, we've handled it above - if a preimage
11028                                                         // came in and we persisted the `ChannelManager` we either handled it and
11029                                                         // are good to go or the channel force-closed - we don't have to handle the
11030                                                         // channel still live case here.
11031                                                         None
11032                                                 }
11033                                         });
11034                                 for tuple in outbound_claimed_htlcs_iter {
11035                                         pending_claims_to_replay.push(tuple);
11036                                 }
11037                         }
11038                 }
11039
11040                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
11041                         // If we have pending HTLCs to forward, assume we either dropped a
11042                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
11043                         // shut down before the timer hit. Either way, set the time_forwardable to a small
11044                         // constant as enough time has likely passed that we should simply handle the forwards
11045                         // now, or at least after the user gets a chance to reconnect to our peers.
11046                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
11047                                 time_forwardable: Duration::from_secs(2),
11048                         }, None));
11049                 }
11050
11051                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
11052                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
11053
11054                 let mut claimable_payments = hash_map_with_capacity(claimable_htlcs_list.len());
11055                 if let Some(purposes) = claimable_htlc_purposes {
11056                         if purposes.len() != claimable_htlcs_list.len() {
11057                                 return Err(DecodeError::InvalidValue);
11058                         }
11059                         if let Some(onion_fields) = claimable_htlc_onion_fields {
11060                                 if onion_fields.len() != claimable_htlcs_list.len() {
11061                                         return Err(DecodeError::InvalidValue);
11062                                 }
11063                                 for (purpose, (onion, (payment_hash, htlcs))) in
11064                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
11065                                 {
11066                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
11067                                                 purpose, htlcs, onion_fields: onion,
11068                                         });
11069                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
11070                                 }
11071                         } else {
11072                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
11073                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
11074                                                 purpose, htlcs, onion_fields: None,
11075                                         });
11076                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
11077                                 }
11078                         }
11079                 } else {
11080                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
11081                         // include a `_legacy_hop_data` in the `OnionPayload`.
11082                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
11083                                 if htlcs.is_empty() {
11084                                         return Err(DecodeError::InvalidValue);
11085                                 }
11086                                 let purpose = match &htlcs[0].onion_payload {
11087                                         OnionPayload::Invoice { _legacy_hop_data } => {
11088                                                 if let Some(hop_data) = _legacy_hop_data {
11089                                                         events::PaymentPurpose::InvoicePayment {
11090                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
11091                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
11092                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
11093                                                                                 Ok((payment_preimage, _)) => payment_preimage,
11094                                                                                 Err(()) => {
11095                                                                                         log_error!(args.logger, "Failed to read claimable payment data for HTLC with payment hash {} - was not a pending inbound payment and didn't match our payment key", &payment_hash);
11096                                                                                         return Err(DecodeError::InvalidValue);
11097                                                                                 }
11098                                                                         }
11099                                                                 },
11100                                                                 payment_secret: hop_data.payment_secret,
11101                                                         }
11102                                                 } else { return Err(DecodeError::InvalidValue); }
11103                                         },
11104                                         OnionPayload::Spontaneous(payment_preimage) =>
11105                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
11106                                 };
11107                                 claimable_payments.insert(payment_hash, ClaimablePayment {
11108                                         purpose, htlcs, onion_fields: None,
11109                                 });
11110                         }
11111                 }
11112
11113                 let mut secp_ctx = Secp256k1::new();
11114                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
11115
11116                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
11117                         Ok(key) => key,
11118                         Err(()) => return Err(DecodeError::InvalidValue)
11119                 };
11120                 if let Some(network_pubkey) = received_network_pubkey {
11121                         if network_pubkey != our_network_pubkey {
11122                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
11123                                 return Err(DecodeError::InvalidValue);
11124                         }
11125                 }
11126
11127                 let mut outbound_scid_aliases = new_hash_set();
11128                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
11129                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
11130                         let peer_state = &mut *peer_state_lock;
11131                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
11132                                 if let ChannelPhase::Funded(chan) = phase {
11133                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
11134                                         if chan.context.outbound_scid_alias() == 0 {
11135                                                 let mut outbound_scid_alias;
11136                                                 loop {
11137                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
11138                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
11139                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
11140                                                 }
11141                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
11142                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
11143                                                 // Note that in rare cases its possible to hit this while reading an older
11144                                                 // channel if we just happened to pick a colliding outbound alias above.
11145                                                 log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
11146                                                 return Err(DecodeError::InvalidValue);
11147                                         }
11148                                         if chan.context.is_usable() {
11149                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
11150                                                         // Note that in rare cases its possible to hit this while reading an older
11151                                                         // channel if we just happened to pick a colliding outbound alias above.
11152                                                         log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
11153                                                         return Err(DecodeError::InvalidValue);
11154                                                 }
11155                                         }
11156                                 } else {
11157                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
11158                                         // created in this `channel_by_id` map.
11159                                         debug_assert!(false);
11160                                         return Err(DecodeError::InvalidValue);
11161                                 }
11162                         }
11163                 }
11164
11165                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
11166
11167                 for (_, monitor) in args.channel_monitors.iter() {
11168                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
11169                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
11170                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
11171                                         let mut claimable_amt_msat = 0;
11172                                         let mut receiver_node_id = Some(our_network_pubkey);
11173                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
11174                                         if phantom_shared_secret.is_some() {
11175                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
11176                                                         .expect("Failed to get node_id for phantom node recipient");
11177                                                 receiver_node_id = Some(phantom_pubkey)
11178                                         }
11179                                         for claimable_htlc in &payment.htlcs {
11180                                                 claimable_amt_msat += claimable_htlc.value;
11181
11182                                                 // Add a holding-cell claim of the payment to the Channel, which should be
11183                                                 // applied ~immediately on peer reconnection. Because it won't generate a
11184                                                 // new commitment transaction we can just provide the payment preimage to
11185                                                 // the corresponding ChannelMonitor and nothing else.
11186                                                 //
11187                                                 // We do so directly instead of via the normal ChannelMonitor update
11188                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
11189                                                 // we're not allowed to call it directly yet. Further, we do the update
11190                                                 // without incrementing the ChannelMonitor update ID as there isn't any
11191                                                 // reason to.
11192                                                 // If we were to generate a new ChannelMonitor update ID here and then
11193                                                 // crash before the user finishes block connect we'd end up force-closing
11194                                                 // this channel as well. On the flip side, there's no harm in restarting
11195                                                 // without the new monitor persisted - we'll end up right back here on
11196                                                 // restart.
11197                                                 let previous_channel_id = claimable_htlc.prev_hop.channel_id;
11198                                                 if let Some(peer_node_id) = outpoint_to_peer.get(&claimable_htlc.prev_hop.outpoint) {
11199                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
11200                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
11201                                                         let peer_state = &mut *peer_state_lock;
11202                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
11203                                                                 let logger = WithChannelContext::from(&args.logger, &channel.context);
11204                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &&logger);
11205                                                         }
11206                                                 }
11207                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
11208                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
11209                                                 }
11210                                         }
11211                                         pending_events_read.push_back((events::Event::PaymentClaimed {
11212                                                 receiver_node_id,
11213                                                 payment_hash,
11214                                                 purpose: payment.purpose,
11215                                                 amount_msat: claimable_amt_msat,
11216                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
11217                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
11218                                         }, None));
11219                                 }
11220                         }
11221                 }
11222
11223                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
11224                         if let Some(peer_state) = per_peer_state.get(&node_id) {
11225                                 for (channel_id, actions) in monitor_update_blocked_actions.iter() {
11226                                         let logger = WithContext::from(&args.logger, Some(node_id), Some(*channel_id));
11227                                         for action in actions.iter() {
11228                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
11229                                                         downstream_counterparty_and_funding_outpoint:
11230                                                                 Some((blocked_node_id, _blocked_channel_outpoint, blocked_channel_id, blocking_action)), ..
11231                                                 } = action {
11232                                                         if let Some(blocked_peer_state) = per_peer_state.get(blocked_node_id) {
11233                                                                 log_trace!(logger,
11234                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
11235                                                                         blocked_channel_id);
11236                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
11237                                                                         .entry(*blocked_channel_id)
11238                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
11239                                                         } else {
11240                                                                 // If the channel we were blocking has closed, we don't need to
11241                                                                 // worry about it - the blocked monitor update should never have
11242                                                                 // been released from the `Channel` object so it can't have
11243                                                                 // completed, and if the channel closed there's no reason to bother
11244                                                                 // anymore.
11245                                                         }
11246                                                 }
11247                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
11248                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
11249                                                 }
11250                                         }
11251                                 }
11252                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
11253                         } else {
11254                                 log_error!(WithContext::from(&args.logger, Some(node_id), None), "Got blocked actions without a per-peer-state for {}", node_id);
11255                                 return Err(DecodeError::InvalidValue);
11256                         }
11257                 }
11258
11259                 let channel_manager = ChannelManager {
11260                         chain_hash,
11261                         fee_estimator: bounded_fee_estimator,
11262                         chain_monitor: args.chain_monitor,
11263                         tx_broadcaster: args.tx_broadcaster,
11264                         router: args.router,
11265
11266                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
11267
11268                         inbound_payment_key: expanded_inbound_key,
11269                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
11270                         pending_outbound_payments: pending_outbounds,
11271                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
11272
11273                         forward_htlcs: Mutex::new(forward_htlcs),
11274                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
11275                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
11276                         outpoint_to_peer: Mutex::new(outpoint_to_peer),
11277                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
11278                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
11279
11280                         probing_cookie_secret: probing_cookie_secret.unwrap(),
11281
11282                         our_network_pubkey,
11283                         secp_ctx,
11284
11285                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
11286
11287                         per_peer_state: FairRwLock::new(per_peer_state),
11288
11289                         pending_events: Mutex::new(pending_events_read),
11290                         pending_events_processor: AtomicBool::new(false),
11291                         pending_background_events: Mutex::new(pending_background_events),
11292                         total_consistency_lock: RwLock::new(()),
11293                         background_events_processed_since_startup: AtomicBool::new(false),
11294
11295                         event_persist_notifier: Notifier::new(),
11296                         needs_persist_flag: AtomicBool::new(false),
11297
11298                         funding_batch_states: Mutex::new(BTreeMap::new()),
11299
11300                         pending_offers_messages: Mutex::new(Vec::new()),
11301
11302                         entropy_source: args.entropy_source,
11303                         node_signer: args.node_signer,
11304                         signer_provider: args.signer_provider,
11305
11306                         logger: args.logger,
11307                         default_configuration: args.default_config,
11308                 };
11309
11310                 for htlc_source in failed_htlcs.drain(..) {
11311                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
11312                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
11313                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
11314                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
11315                 }
11316
11317                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding, downstream_channel_id) in pending_claims_to_replay {
11318                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
11319                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
11320                         // channel is closed we just assume that it probably came from an on-chain claim.
11321                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value), None,
11322                                 downstream_closed, true, downstream_node_id, downstream_funding, downstream_channel_id);
11323                 }
11324
11325                 //TODO: Broadcast channel update for closed channels, but only after we've made a
11326                 //connection or two.
11327
11328                 Ok((best_block_hash.clone(), channel_manager))
11329         }
11330 }
11331
11332 #[cfg(test)]
11333 mod tests {
11334         use bitcoin::hashes::Hash;
11335         use bitcoin::hashes::sha256::Hash as Sha256;
11336         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
11337         use core::sync::atomic::Ordering;
11338         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
11339         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
11340         use crate::ln::ChannelId;
11341         use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
11342         use crate::ln::functional_test_utils::*;
11343         use crate::ln::msgs::{self, ErrorAction};
11344         use crate::ln::msgs::ChannelMessageHandler;
11345         use crate::prelude::*;
11346         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
11347         use crate::util::errors::APIError;
11348         use crate::util::ser::Writeable;
11349         use crate::util::test_utils;
11350         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
11351         use crate::sign::EntropySource;
11352
11353         #[test]
11354         fn test_notify_limits() {
11355                 // Check that a few cases which don't require the persistence of a new ChannelManager,
11356                 // indeed, do not cause the persistence of a new ChannelManager.
11357                 let chanmon_cfgs = create_chanmon_cfgs(3);
11358                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11359                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11360                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11361
11362                 // All nodes start with a persistable update pending as `create_network` connects each node
11363                 // with all other nodes to make most tests simpler.
11364                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11365                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11366                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11367
11368                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11369
11370                 // We check that the channel info nodes have doesn't change too early, even though we try
11371                 // to connect messages with new values
11372                 chan.0.contents.fee_base_msat *= 2;
11373                 chan.1.contents.fee_base_msat *= 2;
11374                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
11375                         &nodes[1].node.get_our_node_id()).pop().unwrap();
11376                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
11377                         &nodes[0].node.get_our_node_id()).pop().unwrap();
11378
11379                 // The first two nodes (which opened a channel) should now require fresh persistence
11380                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11381                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11382                 // ... but the last node should not.
11383                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11384                 // After persisting the first two nodes they should no longer need fresh persistence.
11385                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11386                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11387
11388                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
11389                 // about the channel.
11390                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
11391                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
11392                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11393
11394                 // The nodes which are a party to the channel should also ignore messages from unrelated
11395                 // parties.
11396                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11397                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11398                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11399                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11400                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11401                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11402
11403                 // At this point the channel info given by peers should still be the same.
11404                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11405                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11406
11407                 // An earlier version of handle_channel_update didn't check the directionality of the
11408                 // update message and would always update the local fee info, even if our peer was
11409                 // (spuriously) forwarding us our own channel_update.
11410                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
11411                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
11412                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
11413
11414                 // First deliver each peers' own message, checking that the node doesn't need to be
11415                 // persisted and that its channel info remains the same.
11416                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
11417                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
11418                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11419                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11420                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11421                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11422
11423                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
11424                 // the channel info has updated.
11425                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
11426                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
11427                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11428                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11429                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
11430                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
11431         }
11432
11433         #[test]
11434         fn test_keysend_dup_hash_partial_mpp() {
11435                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
11436                 // expected.
11437                 let chanmon_cfgs = create_chanmon_cfgs(2);
11438                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11439                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11440                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11441                 create_announced_chan_between_nodes(&nodes, 0, 1);
11442
11443                 // First, send a partial MPP payment.
11444                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11445                 let mut mpp_route = route.clone();
11446                 mpp_route.paths.push(mpp_route.paths[0].clone());
11447
11448                 let payment_id = PaymentId([42; 32]);
11449                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11450                 // indicates there are more HTLCs coming.
11451                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
11452                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11453                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11454                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11455                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11456                 check_added_monitors!(nodes[0], 1);
11457                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11458                 assert_eq!(events.len(), 1);
11459                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11460
11461                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11462                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11463                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11464                 check_added_monitors!(nodes[0], 1);
11465                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11466                 assert_eq!(events.len(), 1);
11467                 let ev = events.drain(..).next().unwrap();
11468                 let payment_event = SendEvent::from_event(ev);
11469                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11470                 check_added_monitors!(nodes[1], 0);
11471                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11472                 expect_pending_htlcs_forwardable!(nodes[1]);
11473                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11474                 check_added_monitors!(nodes[1], 1);
11475                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11476                 assert!(updates.update_add_htlcs.is_empty());
11477                 assert!(updates.update_fulfill_htlcs.is_empty());
11478                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11479                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11480                 assert!(updates.update_fee.is_none());
11481                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11482                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11483                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11484
11485                 // Send the second half of the original MPP payment.
11486                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11487                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11488                 check_added_monitors!(nodes[0], 1);
11489                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11490                 assert_eq!(events.len(), 1);
11491                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11492
11493                 // Claim the full MPP payment. Note that we can't use a test utility like
11494                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11495                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11496                 // lightning messages manually.
11497                 nodes[1].node.claim_funds(payment_preimage);
11498                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11499                 check_added_monitors!(nodes[1], 2);
11500
11501                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11502                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11503                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11504                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11505                 check_added_monitors!(nodes[0], 1);
11506                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11507                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11508                 check_added_monitors!(nodes[1], 1);
11509                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11510                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11511                 check_added_monitors!(nodes[1], 1);
11512                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11513                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11514                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11515                 check_added_monitors!(nodes[0], 1);
11516                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11517                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11518                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11519                 check_added_monitors!(nodes[0], 1);
11520                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11521                 check_added_monitors!(nodes[1], 1);
11522                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11523                 check_added_monitors!(nodes[1], 1);
11524                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11525                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11526                 check_added_monitors!(nodes[0], 1);
11527
11528                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11529                 // path's success and a PaymentPathSuccessful event for each path's success.
11530                 let events = nodes[0].node.get_and_clear_pending_events();
11531                 assert_eq!(events.len(), 2);
11532                 match events[0] {
11533                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11534                                 assert_eq!(payment_id, *actual_payment_id);
11535                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11536                                 assert_eq!(route.paths[0], *path);
11537                         },
11538                         _ => panic!("Unexpected event"),
11539                 }
11540                 match events[1] {
11541                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11542                                 assert_eq!(payment_id, *actual_payment_id);
11543                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11544                                 assert_eq!(route.paths[0], *path);
11545                         },
11546                         _ => panic!("Unexpected event"),
11547                 }
11548         }
11549
11550         #[test]
11551         fn test_keysend_dup_payment_hash() {
11552                 do_test_keysend_dup_payment_hash(false);
11553                 do_test_keysend_dup_payment_hash(true);
11554         }
11555
11556         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11557                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11558                 //      outbound regular payment fails as expected.
11559                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11560                 //      fails as expected.
11561                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11562                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11563                 //      reject MPP keysend payments, since in this case where the payment has no payment
11564                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11565                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11566                 //      payment secrets and reject otherwise.
11567                 let chanmon_cfgs = create_chanmon_cfgs(2);
11568                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11569                 let mut mpp_keysend_cfg = test_default_channel_config();
11570                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11571                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11572                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11573                 create_announced_chan_between_nodes(&nodes, 0, 1);
11574                 let scorer = test_utils::TestScorer::new();
11575                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11576
11577                 // To start (1), send a regular payment but don't claim it.
11578                 let expected_route = [&nodes[1]];
11579                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11580
11581                 // Next, attempt a keysend payment and make sure it fails.
11582                 let route_params = RouteParameters::from_payment_params_and_value(
11583                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11584                         TEST_FINAL_CLTV, false), 100_000);
11585                 let route = find_route(
11586                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11587                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11588                 ).unwrap();
11589                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11590                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11591                 check_added_monitors!(nodes[0], 1);
11592                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11593                 assert_eq!(events.len(), 1);
11594                 let ev = events.drain(..).next().unwrap();
11595                 let payment_event = SendEvent::from_event(ev);
11596                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11597                 check_added_monitors!(nodes[1], 0);
11598                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11599                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11600                 // fails), the second will process the resulting failure and fail the HTLC backward
11601                 expect_pending_htlcs_forwardable!(nodes[1]);
11602                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11603                 check_added_monitors!(nodes[1], 1);
11604                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11605                 assert!(updates.update_add_htlcs.is_empty());
11606                 assert!(updates.update_fulfill_htlcs.is_empty());
11607                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11608                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11609                 assert!(updates.update_fee.is_none());
11610                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11611                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11612                 expect_payment_failed!(nodes[0], payment_hash, true);
11613
11614                 // Finally, claim the original payment.
11615                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11616
11617                 // To start (2), send a keysend payment but don't claim it.
11618                 let payment_preimage = PaymentPreimage([42; 32]);
11619                 let route = find_route(
11620                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11621                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11622                 ).unwrap();
11623                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11624                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11625                 check_added_monitors!(nodes[0], 1);
11626                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11627                 assert_eq!(events.len(), 1);
11628                 let event = events.pop().unwrap();
11629                 let path = vec![&nodes[1]];
11630                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11631
11632                 // Next, attempt a regular payment and make sure it fails.
11633                 let payment_secret = PaymentSecret([43; 32]);
11634                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11635                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11636                 check_added_monitors!(nodes[0], 1);
11637                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11638                 assert_eq!(events.len(), 1);
11639                 let ev = events.drain(..).next().unwrap();
11640                 let payment_event = SendEvent::from_event(ev);
11641                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11642                 check_added_monitors!(nodes[1], 0);
11643                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11644                 expect_pending_htlcs_forwardable!(nodes[1]);
11645                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11646                 check_added_monitors!(nodes[1], 1);
11647                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11648                 assert!(updates.update_add_htlcs.is_empty());
11649                 assert!(updates.update_fulfill_htlcs.is_empty());
11650                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11651                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11652                 assert!(updates.update_fee.is_none());
11653                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11654                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11655                 expect_payment_failed!(nodes[0], payment_hash, true);
11656
11657                 // Finally, succeed the keysend payment.
11658                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11659
11660                 // To start (3), send a keysend payment but don't claim it.
11661                 let payment_id_1 = PaymentId([44; 32]);
11662                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11663                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11664                 check_added_monitors!(nodes[0], 1);
11665                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11666                 assert_eq!(events.len(), 1);
11667                 let event = events.pop().unwrap();
11668                 let path = vec![&nodes[1]];
11669                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11670
11671                 // Next, attempt a keysend payment and make sure it fails.
11672                 let route_params = RouteParameters::from_payment_params_and_value(
11673                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11674                         100_000
11675                 );
11676                 let route = find_route(
11677                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11678                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11679                 ).unwrap();
11680                 let payment_id_2 = PaymentId([45; 32]);
11681                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11682                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11683                 check_added_monitors!(nodes[0], 1);
11684                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11685                 assert_eq!(events.len(), 1);
11686                 let ev = events.drain(..).next().unwrap();
11687                 let payment_event = SendEvent::from_event(ev);
11688                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11689                 check_added_monitors!(nodes[1], 0);
11690                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11691                 expect_pending_htlcs_forwardable!(nodes[1]);
11692                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11693                 check_added_monitors!(nodes[1], 1);
11694                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11695                 assert!(updates.update_add_htlcs.is_empty());
11696                 assert!(updates.update_fulfill_htlcs.is_empty());
11697                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11698                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11699                 assert!(updates.update_fee.is_none());
11700                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11701                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11702                 expect_payment_failed!(nodes[0], payment_hash, true);
11703
11704                 // Finally, claim the original payment.
11705                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11706         }
11707
11708         #[test]
11709         fn test_keysend_hash_mismatch() {
11710                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11711                 // preimage doesn't match the msg's payment hash.
11712                 let chanmon_cfgs = create_chanmon_cfgs(2);
11713                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11714                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11715                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11716
11717                 let payer_pubkey = nodes[0].node.get_our_node_id();
11718                 let payee_pubkey = nodes[1].node.get_our_node_id();
11719
11720                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11721                 let route_params = RouteParameters::from_payment_params_and_value(
11722                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11723                 let network_graph = nodes[0].network_graph;
11724                 let first_hops = nodes[0].node.list_usable_channels();
11725                 let scorer = test_utils::TestScorer::new();
11726                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11727                 let route = find_route(
11728                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11729                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11730                 ).unwrap();
11731
11732                 let test_preimage = PaymentPreimage([42; 32]);
11733                 let mismatch_payment_hash = PaymentHash([43; 32]);
11734                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11735                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11736                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11737                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11738                 check_added_monitors!(nodes[0], 1);
11739
11740                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11741                 assert_eq!(updates.update_add_htlcs.len(), 1);
11742                 assert!(updates.update_fulfill_htlcs.is_empty());
11743                 assert!(updates.update_fail_htlcs.is_empty());
11744                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11745                 assert!(updates.update_fee.is_none());
11746                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11747
11748                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11749         }
11750
11751         #[test]
11752         fn test_keysend_msg_with_secret_err() {
11753                 // Test that we error as expected if we receive a keysend payment that includes a payment
11754                 // secret when we don't support MPP keysend.
11755                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11756                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11757                 let chanmon_cfgs = create_chanmon_cfgs(2);
11758                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11759                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11760                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11761
11762                 let payer_pubkey = nodes[0].node.get_our_node_id();
11763                 let payee_pubkey = nodes[1].node.get_our_node_id();
11764
11765                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11766                 let route_params = RouteParameters::from_payment_params_and_value(
11767                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11768                 let network_graph = nodes[0].network_graph;
11769                 let first_hops = nodes[0].node.list_usable_channels();
11770                 let scorer = test_utils::TestScorer::new();
11771                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11772                 let route = find_route(
11773                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11774                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11775                 ).unwrap();
11776
11777                 let test_preimage = PaymentPreimage([42; 32]);
11778                 let test_secret = PaymentSecret([43; 32]);
11779                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).to_byte_array());
11780                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11781                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11782                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11783                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11784                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11785                 check_added_monitors!(nodes[0], 1);
11786
11787                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11788                 assert_eq!(updates.update_add_htlcs.len(), 1);
11789                 assert!(updates.update_fulfill_htlcs.is_empty());
11790                 assert!(updates.update_fail_htlcs.is_empty());
11791                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11792                 assert!(updates.update_fee.is_none());
11793                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11794
11795                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11796         }
11797
11798         #[test]
11799         fn test_multi_hop_missing_secret() {
11800                 let chanmon_cfgs = create_chanmon_cfgs(4);
11801                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11802                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11803                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11804
11805                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11806                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11807                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11808                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11809
11810                 // Marshall an MPP route.
11811                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11812                 let path = route.paths[0].clone();
11813                 route.paths.push(path);
11814                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11815                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11816                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11817                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11818                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11819                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11820
11821                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11822                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11823                 .unwrap_err() {
11824                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11825                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11826                         },
11827                         _ => panic!("unexpected error")
11828                 }
11829         }
11830
11831         #[test]
11832         fn test_drop_disconnected_peers_when_removing_channels() {
11833                 let chanmon_cfgs = create_chanmon_cfgs(2);
11834                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11835                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11836                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11837
11838                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11839
11840                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11841                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11842
11843                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11844                 check_closed_broadcast!(nodes[0], true);
11845                 check_added_monitors!(nodes[0], 1);
11846                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11847
11848                 {
11849                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11850                         // disconnected and the channel between has been force closed.
11851                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11852                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11853                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11854                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11855                 }
11856
11857                 nodes[0].node.timer_tick_occurred();
11858
11859                 {
11860                         // Assert that nodes[1] has now been removed.
11861                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11862                 }
11863         }
11864
11865         #[test]
11866         fn bad_inbound_payment_hash() {
11867                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11868                 let chanmon_cfgs = create_chanmon_cfgs(2);
11869                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11870                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11871                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11872
11873                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11874                 let payment_data = msgs::FinalOnionHopData {
11875                         payment_secret,
11876                         total_msat: 100_000,
11877                 };
11878
11879                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11880                 // payment verification fails as expected.
11881                 let mut bad_payment_hash = payment_hash.clone();
11882                 bad_payment_hash.0[0] += 1;
11883                 match inbound_payment::verify(bad_payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger) {
11884                         Ok(_) => panic!("Unexpected ok"),
11885                         Err(()) => {
11886                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11887                         }
11888                 }
11889
11890                 // Check that using the original payment hash succeeds.
11891                 assert!(inbound_payment::verify(payment_hash, &payment_data, nodes[0].node.highest_seen_timestamp.load(Ordering::Acquire) as u64, &nodes[0].node.inbound_payment_key, &nodes[0].logger).is_ok());
11892         }
11893
11894         #[test]
11895         fn test_outpoint_to_peer_coverage() {
11896                 // Test that the `ChannelManager:outpoint_to_peer` contains channels which have been assigned
11897                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11898                 // the channel is successfully closed.
11899                 let chanmon_cfgs = create_chanmon_cfgs(2);
11900                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11901                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11902                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11903
11904                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
11905                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11906                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11907                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11908                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11909
11910                 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11911                 let channel_id = ChannelId::from_bytes(tx.txid().to_byte_array());
11912                 {
11913                         // Ensure that the `outpoint_to_peer` map is empty until either party has received the
11914                         // funding transaction, and have the real `channel_id`.
11915                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11916                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11917                 }
11918
11919                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11920                 {
11921                         // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as
11922                         // as it has the funding transaction.
11923                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11924                         assert_eq!(nodes_0_lock.len(), 1);
11925                         assert!(nodes_0_lock.contains_key(&funding_output));
11926                 }
11927
11928                 assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11929
11930                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11931
11932                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11933                 {
11934                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11935                         assert_eq!(nodes_0_lock.len(), 1);
11936                         assert!(nodes_0_lock.contains_key(&funding_output));
11937                 }
11938                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11939
11940                 {
11941                         // Assert that `nodes[1]`'s `outpoint_to_peer` map is populated with the channel as
11942                         // soon as it has the funding transaction.
11943                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11944                         assert_eq!(nodes_1_lock.len(), 1);
11945                         assert!(nodes_1_lock.contains_key(&funding_output));
11946                 }
11947                 check_added_monitors!(nodes[1], 1);
11948                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11949                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11950                 check_added_monitors!(nodes[0], 1);
11951                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11952                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11953                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11954                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11955
11956                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11957                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id()));
11958                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11959                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11960
11961                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11962                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11963                 {
11964                         // Assert that the channel is kept in the `outpoint_to_peer` map for both nodes until the
11965                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11966                         // fee for the closing transaction has been negotiated and the parties has the other
11967                         // party's signature for the fee negotiated closing transaction.)
11968                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11969                         assert_eq!(nodes_0_lock.len(), 1);
11970                         assert!(nodes_0_lock.contains_key(&funding_output));
11971                 }
11972
11973                 {
11974                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11975                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11976                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11977                         // kept in the `nodes[1]`'s `outpoint_to_peer` map.
11978                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11979                         assert_eq!(nodes_1_lock.len(), 1);
11980                         assert!(nodes_1_lock.contains_key(&funding_output));
11981                 }
11982
11983                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendClosingSigned, nodes[0].node.get_our_node_id()));
11984                 {
11985                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11986                         // therefore has all it needs to fully close the channel (both signatures for the
11987                         // closing transaction).
11988                         // Assert that the channel is removed from `nodes[0]`'s `outpoint_to_peer` map as it can be
11989                         // fully closed by `nodes[0]`.
11990                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11991
11992                         // Assert that the channel is still in `nodes[1]`'s  `outpoint_to_peer` map, as `nodes[1]`
11993                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11994                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11995                         assert_eq!(nodes_1_lock.len(), 1);
11996                         assert!(nodes_1_lock.contains_key(&funding_output));
11997                 }
11998
11999                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
12000
12001                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
12002                 {
12003                         // Assert that the channel has now been removed from both parties `outpoint_to_peer` map once
12004                         // they both have everything required to fully close the channel.
12005                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
12006                 }
12007                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
12008
12009                 check_closed_event!(nodes[0], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
12010                 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
12011         }
12012
12013         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
12014                 let expected_message = format!("Not connected to node: {}", expected_public_key);
12015                 check_api_error_message(expected_message, res_err)
12016         }
12017
12018         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
12019                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
12020                 check_api_error_message(expected_message, res_err)
12021         }
12022
12023         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
12024                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
12025                 check_api_error_message(expected_message, res_err)
12026         }
12027
12028         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
12029                 let expected_message = "No such channel awaiting to be accepted.".to_string();
12030                 check_api_error_message(expected_message, res_err)
12031         }
12032
12033         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
12034                 match res_err {
12035                         Err(APIError::APIMisuseError { err }) => {
12036                                 assert_eq!(err, expected_err_message);
12037                         },
12038                         Err(APIError::ChannelUnavailable { err }) => {
12039                                 assert_eq!(err, expected_err_message);
12040                         },
12041                         Ok(_) => panic!("Unexpected Ok"),
12042                         Err(_) => panic!("Unexpected Error"),
12043                 }
12044         }
12045
12046         #[test]
12047         fn test_api_calls_with_unkown_counterparty_node() {
12048                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
12049                 // expected if the `counterparty_node_id` is an unkown peer in the
12050                 // `ChannelManager::per_peer_state` map.
12051                 let chanmon_cfg = create_chanmon_cfgs(2);
12052                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12053                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
12054                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12055
12056                 // Dummy values
12057                 let channel_id = ChannelId::from_bytes([4; 32]);
12058                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
12059                 let intercept_id = InterceptId([0; 32]);
12060
12061                 // Test the API functions.
12062                 check_not_connected_to_peer_error(nodes[0].node.create_channel(unkown_public_key, 1_000_000, 500_000_000, 42, None, None), unkown_public_key);
12063
12064                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
12065
12066                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
12067
12068                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
12069
12070                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
12071
12072                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
12073
12074                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
12075         }
12076
12077         #[test]
12078         fn test_api_calls_with_unavailable_channel() {
12079                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
12080                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
12081                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
12082                 // the given `channel_id`.
12083                 let chanmon_cfg = create_chanmon_cfgs(2);
12084                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12085                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
12086                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12087
12088                 let counterparty_node_id = nodes[1].node.get_our_node_id();
12089
12090                 // Dummy values
12091                 let channel_id = ChannelId::from_bytes([4; 32]);
12092
12093                 // Test the API functions.
12094                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
12095
12096                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
12097
12098                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
12099
12100                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
12101
12102                 check_channel_unavailable_error(nodes[0].node.forward_intercepted_htlc(InterceptId([0; 32]), &channel_id, counterparty_node_id, 1_000_000), channel_id, counterparty_node_id);
12103
12104                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
12105         }
12106
12107         #[test]
12108         fn test_connection_limiting() {
12109                 // Test that we limit un-channel'd peers and un-funded channels properly.
12110                 let chanmon_cfgs = create_chanmon_cfgs(2);
12111                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12112                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
12113                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12114
12115                 // Note that create_network connects the nodes together for us
12116
12117                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12118                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12119
12120                 let mut funding_tx = None;
12121                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
12122                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12123                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12124
12125                         if idx == 0 {
12126                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
12127                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
12128                                 funding_tx = Some(tx.clone());
12129                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
12130                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
12131
12132                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
12133                                 check_added_monitors!(nodes[1], 1);
12134                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
12135
12136                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
12137
12138                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
12139                                 check_added_monitors!(nodes[0], 1);
12140                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
12141                         }
12142                         open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12143                 }
12144
12145                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
12146                 open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(
12147                         &nodes[0].keys_manager);
12148                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12149                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12150                         open_channel_msg.common_fields.temporary_channel_id);
12151
12152                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
12153                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
12154                 // limit.
12155                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
12156                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
12157                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12158                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12159                         peer_pks.push(random_pk);
12160                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
12161                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12162                         }, true).unwrap();
12163                 }
12164                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12165                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12166                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12167                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12168                 }, true).unwrap_err();
12169
12170                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
12171                 // them if we have too many un-channel'd peers.
12172                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12173                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
12174                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
12175                 for ev in chan_closed_events {
12176                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
12177                 }
12178                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12179                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12180                 }, true).unwrap();
12181                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12182                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12183                 }, true).unwrap_err();
12184
12185                 // but of course if the connection is outbound its allowed...
12186                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12187                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12188                 }, false).unwrap();
12189                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12190
12191                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
12192                 // Even though we accept one more connection from new peers, we won't actually let them
12193                 // open channels.
12194                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
12195                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12196                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
12197                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
12198                         open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12199                 }
12200                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12201                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12202                         open_channel_msg.common_fields.temporary_channel_id);
12203
12204                 // Of course, however, outbound channels are always allowed
12205                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap();
12206                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
12207
12208                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
12209                 // "protected" and can connect again.
12210                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
12211                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12212                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12213                 }, true).unwrap();
12214                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
12215
12216                 // Further, because the first channel was funded, we can open another channel with
12217                 // last_random_pk.
12218                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12219                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12220         }
12221
12222         #[test]
12223         fn test_outbound_chans_unlimited() {
12224                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
12225                 let chanmon_cfgs = create_chanmon_cfgs(2);
12226                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12227                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
12228                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12229
12230                 // Note that create_network connects the nodes together for us
12231
12232                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12233                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12234
12235                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
12236                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12237                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12238                         open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12239                 }
12240
12241                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
12242                 // rejected.
12243                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12244                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12245                         open_channel_msg.common_fields.temporary_channel_id);
12246
12247                 // but we can still open an outbound channel.
12248                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12249                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
12250
12251                 // but even with such an outbound channel, additional inbound channels will still fail.
12252                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12253                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12254                         open_channel_msg.common_fields.temporary_channel_id);
12255         }
12256
12257         #[test]
12258         fn test_0conf_limiting() {
12259                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12260                 // flag set and (sometimes) accept channels as 0conf.
12261                 let chanmon_cfgs = create_chanmon_cfgs(2);
12262                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12263                 let mut settings = test_default_channel_config();
12264                 settings.manually_accept_inbound_channels = true;
12265                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
12266                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12267
12268                 // Note that create_network connects the nodes together for us
12269
12270                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12271                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12272
12273                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
12274                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12275                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12276                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12277                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
12278                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12279                         }, true).unwrap();
12280
12281                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
12282                         let events = nodes[1].node.get_and_clear_pending_events();
12283                         match events[0] {
12284                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
12285                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
12286                                 }
12287                                 _ => panic!("Unexpected event"),
12288                         }
12289                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
12290                         open_channel_msg.common_fields.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12291                 }
12292
12293                 // If we try to accept a channel from another peer non-0conf it will fail.
12294                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12295                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12296                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12297                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12298                 }, true).unwrap();
12299                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12300                 let events = nodes[1].node.get_and_clear_pending_events();
12301                 match events[0] {
12302                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12303                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
12304                                         Err(APIError::APIMisuseError { err }) =>
12305                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
12306                                         _ => panic!(),
12307                                 }
12308                         }
12309                         _ => panic!("Unexpected event"),
12310                 }
12311                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12312                         open_channel_msg.common_fields.temporary_channel_id);
12313
12314                 // ...however if we accept the same channel 0conf it should work just fine.
12315                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12316                 let events = nodes[1].node.get_and_clear_pending_events();
12317                 match events[0] {
12318                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12319                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
12320                         }
12321                         _ => panic!("Unexpected event"),
12322                 }
12323                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12324         }
12325
12326         #[test]
12327         fn reject_excessively_underpaying_htlcs() {
12328                 let chanmon_cfg = create_chanmon_cfgs(1);
12329                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12330                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12331                 let node = create_network(1, &node_cfg, &node_chanmgr);
12332                 let sender_intended_amt_msat = 100;
12333                 let extra_fee_msat = 10;
12334                 let hop_data = msgs::InboundOnionPayload::Receive {
12335                         sender_intended_htlc_amt_msat: 100,
12336                         cltv_expiry_height: 42,
12337                         payment_metadata: None,
12338                         keysend_preimage: None,
12339                         payment_data: Some(msgs::FinalOnionHopData {
12340                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12341                         }),
12342                         custom_tlvs: Vec::new(),
12343                 };
12344                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
12345                 // intended amount, we fail the payment.
12346                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12347                 if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) =
12348                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12349                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
12350                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
12351                 {
12352                         assert_eq!(err_code, 19);
12353                 } else { panic!(); }
12354
12355                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
12356                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
12357                         sender_intended_htlc_amt_msat: 100,
12358                         cltv_expiry_height: 42,
12359                         payment_metadata: None,
12360                         keysend_preimage: None,
12361                         payment_data: Some(msgs::FinalOnionHopData {
12362                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12363                         }),
12364                         custom_tlvs: Vec::new(),
12365                 };
12366                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12367                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12368                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
12369                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
12370         }
12371
12372         #[test]
12373         fn test_final_incorrect_cltv(){
12374                 let chanmon_cfg = create_chanmon_cfgs(1);
12375                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12376                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12377                 let node = create_network(1, &node_cfg, &node_chanmgr);
12378
12379                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12380                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
12381                         sender_intended_htlc_amt_msat: 100,
12382                         cltv_expiry_height: 22,
12383                         payment_metadata: None,
12384                         keysend_preimage: None,
12385                         payment_data: Some(msgs::FinalOnionHopData {
12386                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
12387                         }),
12388                         custom_tlvs: Vec::new(),
12389                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
12390                         node[0].node.default_configuration.accept_mpp_keysend);
12391
12392                 // Should not return an error as this condition:
12393                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
12394                 // is not satisfied.
12395                 assert!(result.is_ok());
12396         }
12397
12398         #[test]
12399         fn test_inbound_anchors_manual_acceptance() {
12400                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12401                 // flag set and (sometimes) accept channels as 0conf.
12402                 let mut anchors_cfg = test_default_channel_config();
12403                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12404
12405                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
12406                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
12407
12408                 let chanmon_cfgs = create_chanmon_cfgs(3);
12409                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
12410                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
12411                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
12412                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
12413
12414                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12415                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12416
12417                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12418                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12419                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
12420                 match &msg_events[0] {
12421                         MessageSendEvent::HandleError { node_id, action } => {
12422                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
12423                                 match action {
12424                                         ErrorAction::SendErrorMessage { msg } =>
12425                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
12426                                         _ => panic!("Unexpected error action"),
12427                                 }
12428                         }
12429                         _ => panic!("Unexpected event"),
12430                 }
12431
12432                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12433                 let events = nodes[2].node.get_and_clear_pending_events();
12434                 match events[0] {
12435                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
12436                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
12437                         _ => panic!("Unexpected event"),
12438                 }
12439                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12440         }
12441
12442         #[test]
12443         fn test_anchors_zero_fee_htlc_tx_fallback() {
12444                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12445                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12446                 // the channel without the anchors feature.
12447                 let chanmon_cfgs = create_chanmon_cfgs(2);
12448                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12449                 let mut anchors_config = test_default_channel_config();
12450                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12451                 anchors_config.manually_accept_inbound_channels = true;
12452                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12453                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12454
12455                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap();
12456                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12457                 assert!(open_channel_msg.common_fields.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12458
12459                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12460                 let events = nodes[1].node.get_and_clear_pending_events();
12461                 match events[0] {
12462                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12463                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12464                         }
12465                         _ => panic!("Unexpected event"),
12466                 }
12467
12468                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12469                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12470
12471                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12472                 assert!(!open_channel_msg.common_fields.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12473
12474                 // Since nodes[1] should not have accepted the channel, it should
12475                 // not have generated any events.
12476                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12477         }
12478
12479         #[test]
12480         fn test_update_channel_config() {
12481                 let chanmon_cfg = create_chanmon_cfgs(2);
12482                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12483                 let mut user_config = test_default_channel_config();
12484                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12485                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12486                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12487                 let channel = &nodes[0].node.list_channels()[0];
12488
12489                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12490                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12491                 assert_eq!(events.len(), 0);
12492
12493                 user_config.channel_config.forwarding_fee_base_msat += 10;
12494                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12495                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12496                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12497                 assert_eq!(events.len(), 1);
12498                 match &events[0] {
12499                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12500                         _ => panic!("expected BroadcastChannelUpdate event"),
12501                 }
12502
12503                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12504                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12505                 assert_eq!(events.len(), 0);
12506
12507                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12508                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12509                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12510                         ..Default::default()
12511                 }).unwrap();
12512                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12513                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12514                 assert_eq!(events.len(), 1);
12515                 match &events[0] {
12516                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12517                         _ => panic!("expected BroadcastChannelUpdate event"),
12518                 }
12519
12520                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12521                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12522                         forwarding_fee_proportional_millionths: Some(new_fee),
12523                         ..Default::default()
12524                 }).unwrap();
12525                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12526                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12527                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12528                 assert_eq!(events.len(), 1);
12529                 match &events[0] {
12530                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12531                         _ => panic!("expected BroadcastChannelUpdate event"),
12532                 }
12533
12534                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12535                 // should be applied to ensure update atomicity as specified in the API docs.
12536                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12537                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12538                 let new_fee = current_fee + 100;
12539                 assert!(
12540                         matches!(
12541                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12542                                         forwarding_fee_proportional_millionths: Some(new_fee),
12543                                         ..Default::default()
12544                                 }),
12545                                 Err(APIError::ChannelUnavailable { err: _ }),
12546                         )
12547                 );
12548                 // Check that the fee hasn't changed for the channel that exists.
12549                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12550                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12551                 assert_eq!(events.len(), 0);
12552         }
12553
12554         #[test]
12555         fn test_payment_display() {
12556                 let payment_id = PaymentId([42; 32]);
12557                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12558                 let payment_hash = PaymentHash([42; 32]);
12559                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12560                 let payment_preimage = PaymentPreimage([42; 32]);
12561                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12562         }
12563
12564         #[test]
12565         fn test_trigger_lnd_force_close() {
12566                 let chanmon_cfg = create_chanmon_cfgs(2);
12567                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12568                 let user_config = test_default_channel_config();
12569                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12570                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12571
12572                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12573                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12574                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12575                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12576                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12577                 check_closed_broadcast(&nodes[0], 1, true);
12578                 check_added_monitors(&nodes[0], 1);
12579                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12580                 {
12581                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12582                         assert_eq!(txn.len(), 1);
12583                         check_spends!(txn[0], funding_tx);
12584                 }
12585
12586                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12587                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12588                 // their side.
12589                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12590                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12591                 }, true).unwrap();
12592                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12593                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12594                 }, false).unwrap();
12595                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12596                 let channel_reestablish = get_event_msg!(
12597                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12598                 );
12599                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12600
12601                 // Alice should respond with an error since the channel isn't known, but a bogus
12602                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12603                 // close even if it was an lnd node.
12604                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12605                 assert_eq!(msg_events.len(), 2);
12606                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12607                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12608                         assert_eq!(msg.next_local_commitment_number, 0);
12609                         assert_eq!(msg.next_remote_commitment_number, 0);
12610                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12611                 } else { panic!() };
12612                 check_closed_broadcast(&nodes[1], 1, true);
12613                 check_added_monitors(&nodes[1], 1);
12614                 let expected_close_reason = ClosureReason::ProcessingError {
12615                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12616                 };
12617                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12618                 {
12619                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12620                         assert_eq!(txn.len(), 1);
12621                         check_spends!(txn[0], funding_tx);
12622                 }
12623         }
12624
12625         #[test]
12626         fn test_malformed_forward_htlcs_ser() {
12627                 // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly.
12628                 let chanmon_cfg = create_chanmon_cfgs(1);
12629                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12630                 let persister;
12631                 let chain_monitor;
12632                 let chanmgrs = create_node_chanmgrs(1, &node_cfg, &[None]);
12633                 let deserialized_chanmgr;
12634                 let mut nodes = create_network(1, &node_cfg, &chanmgrs);
12635
12636                 let dummy_failed_htlc = |htlc_id| {
12637                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42] }, }
12638                 };
12639                 let dummy_malformed_htlc = |htlc_id| {
12640                         HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code: 0x4000, sha256_of_onion: [0; 32] }
12641                 };
12642
12643                 let dummy_htlcs_1: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12644                         if htlc_id % 2 == 0 {
12645                                 dummy_failed_htlc(htlc_id)
12646                         } else {
12647                                 dummy_malformed_htlc(htlc_id)
12648                         }
12649                 }).collect();
12650
12651                 let dummy_htlcs_2: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12652                         if htlc_id % 2 == 1 {
12653                                 dummy_failed_htlc(htlc_id)
12654                         } else {
12655                                 dummy_malformed_htlc(htlc_id)
12656                         }
12657                 }).collect();
12658
12659
12660                 let (scid_1, scid_2) = (42, 43);
12661                 let mut forward_htlcs = new_hash_map();
12662                 forward_htlcs.insert(scid_1, dummy_htlcs_1.clone());
12663                 forward_htlcs.insert(scid_2, dummy_htlcs_2.clone());
12664
12665                 let mut chanmgr_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12666                 *chanmgr_fwd_htlcs = forward_htlcs.clone();
12667                 core::mem::drop(chanmgr_fwd_htlcs);
12668
12669                 reload_node!(nodes[0], nodes[0].node.encode(), &[], persister, chain_monitor, deserialized_chanmgr);
12670
12671                 let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12672                 for scid in [scid_1, scid_2].iter() {
12673                         let deserialized_htlcs = deserialized_fwd_htlcs.remove(scid).unwrap();
12674                         assert_eq!(forward_htlcs.remove(scid).unwrap(), deserialized_htlcs);
12675                 }
12676                 assert!(deserialized_fwd_htlcs.is_empty());
12677                 core::mem::drop(deserialized_fwd_htlcs);
12678
12679                 expect_pending_htlcs_forwardable!(nodes[0]);
12680         }
12681 }
12682
12683 #[cfg(ldk_bench)]
12684 pub mod bench {
12685         use crate::chain::Listen;
12686         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12687         use crate::sign::{KeysManager, InMemorySigner};
12688         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12689         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12690         use crate::ln::functional_test_utils::*;
12691         use crate::ln::msgs::{ChannelMessageHandler, Init};
12692         use crate::routing::gossip::NetworkGraph;
12693         use crate::routing::router::{PaymentParameters, RouteParameters};
12694         use crate::util::test_utils;
12695         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12696
12697         use bitcoin::blockdata::locktime::absolute::LockTime;
12698         use bitcoin::hashes::Hash;
12699         use bitcoin::hashes::sha256::Hash as Sha256;
12700         use bitcoin::{Transaction, TxOut};
12701
12702         use crate::sync::{Arc, Mutex, RwLock};
12703
12704         use criterion::Criterion;
12705
12706         type Manager<'a, P> = ChannelManager<
12707                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12708                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12709                         &'a test_utils::TestLogger, &'a P>,
12710                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12711                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12712                 &'a test_utils::TestLogger>;
12713
12714         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12715                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12716         }
12717         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12718                 type CM = Manager<'chan_mon_cfg, P>;
12719                 #[inline]
12720                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12721                 #[inline]
12722                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12723         }
12724
12725         pub fn bench_sends(bench: &mut Criterion) {
12726                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12727         }
12728
12729         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12730                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12731                 // Note that this is unrealistic as each payment send will require at least two fsync
12732                 // calls per node.
12733                 let network = bitcoin::Network::Testnet;
12734                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12735
12736                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12737                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12738                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12739                 let scorer = RwLock::new(test_utils::TestScorer::new());
12740                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &logger_a, &scorer);
12741
12742                 let mut config: UserConfig = Default::default();
12743                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12744                 config.channel_handshake_config.minimum_depth = 1;
12745
12746                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12747                 let seed_a = [1u8; 32];
12748                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12749                 let node_a = ChannelManager::new(&fee_estimator, &chain_monitor_a, &tx_broadcaster, &router, &logger_a, &keys_manager_a, &keys_manager_a, &keys_manager_a, config.clone(), ChainParameters {
12750                         network,
12751                         best_block: BestBlock::from_network(network),
12752                 }, genesis_block.header.time);
12753                 let node_a_holder = ANodeHolder { node: &node_a };
12754
12755                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12756                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12757                 let seed_b = [2u8; 32];
12758                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12759                 let node_b = ChannelManager::new(&fee_estimator, &chain_monitor_b, &tx_broadcaster, &router, &logger_b, &keys_manager_b, &keys_manager_b, &keys_manager_b, config.clone(), ChainParameters {
12760                         network,
12761                         best_block: BestBlock::from_network(network),
12762                 }, genesis_block.header.time);
12763                 let node_b_holder = ANodeHolder { node: &node_b };
12764
12765                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12766                         features: node_b.init_features(), networks: None, remote_network_address: None
12767                 }, true).unwrap();
12768                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12769                         features: node_a.init_features(), networks: None, remote_network_address: None
12770                 }, false).unwrap();
12771                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None, None).unwrap();
12772                 node_b.handle_open_channel(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendOpenChannel, node_b.get_our_node_id()));
12773                 node_a.handle_accept_channel(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendAcceptChannel, node_a.get_our_node_id()));
12774
12775                 let tx;
12776                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12777                         tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12778                                 value: 8_000_000, script_pubkey: output_script,
12779                         }]};
12780                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12781                 } else { panic!(); }
12782
12783                 node_b.handle_funding_created(&node_a.get_our_node_id(), &get_event_msg!(node_a_holder, MessageSendEvent::SendFundingCreated, node_b.get_our_node_id()));
12784                 let events_b = node_b.get_and_clear_pending_events();
12785                 assert_eq!(events_b.len(), 1);
12786                 match events_b[0] {
12787                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12788                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12789                         },
12790                         _ => panic!("Unexpected event"),
12791                 }
12792
12793                 node_a.handle_funding_signed(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendFundingSigned, node_a.get_our_node_id()));
12794                 let events_a = node_a.get_and_clear_pending_events();
12795                 assert_eq!(events_a.len(), 1);
12796                 match events_a[0] {
12797                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12798                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12799                         },
12800                         _ => panic!("Unexpected event"),
12801                 }
12802
12803                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12804
12805                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12806                 Listen::block_connected(&node_a, &block, 1);
12807                 Listen::block_connected(&node_b, &block, 1);
12808
12809                 node_a.handle_channel_ready(&node_b.get_our_node_id(), &get_event_msg!(node_b_holder, MessageSendEvent::SendChannelReady, node_a.get_our_node_id()));
12810                 let msg_events = node_a.get_and_clear_pending_msg_events();
12811                 assert_eq!(msg_events.len(), 2);
12812                 match msg_events[0] {
12813                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12814                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12815                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12816                         },
12817                         _ => panic!(),
12818                 }
12819                 match msg_events[1] {
12820                         MessageSendEvent::SendChannelUpdate { .. } => {},
12821                         _ => panic!(),
12822                 }
12823
12824                 let events_a = node_a.get_and_clear_pending_events();
12825                 assert_eq!(events_a.len(), 1);
12826                 match events_a[0] {
12827                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12828                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12829                         },
12830                         _ => panic!("Unexpected event"),
12831                 }
12832
12833                 let events_b = node_b.get_and_clear_pending_events();
12834                 assert_eq!(events_b.len(), 1);
12835                 match events_b[0] {
12836                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12837                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12838                         },
12839                         _ => panic!("Unexpected event"),
12840                 }
12841
12842                 let mut payment_count: u64 = 0;
12843                 macro_rules! send_payment {
12844                         ($node_a: expr, $node_b: expr) => {
12845                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12846                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12847                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12848                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12849                                 payment_count += 1;
12850                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
12851                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12852
12853                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12854                                         PaymentId(payment_hash.0),
12855                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12856                                         Retry::Attempts(0)).unwrap();
12857                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12858                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12859                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12860                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12861                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12862                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12863                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &get_event_msg!(ANodeHolder { node: &$node_a }, MessageSendEvent::SendRevokeAndACK, $node_b.get_our_node_id()));
12864
12865                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12866                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12867                                 $node_b.claim_funds(payment_preimage);
12868                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12869
12870                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12871                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12872                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12873                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12874                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12875                                         },
12876                                         _ => panic!("Failed to generate claim event"),
12877                                 }
12878
12879                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12880                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12881                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12882                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &get_event_msg!(ANodeHolder { node: &$node_b }, MessageSendEvent::SendRevokeAndACK, $node_a.get_our_node_id()));
12883
12884                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12885                         }
12886                 }
12887
12888                 bench.bench_function(bench_name, |b| b.iter(|| {
12889                         send_payment!(node_a, node_b);
12890                         send_payment!(node_b, node_a);
12891                 }));
12892         }
12893 }