Delay broadcasting Channel Updates until connected to peers
[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 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
48 #[cfg(any(feature = "_test_utils", test))]
49 use crate::ln::features::Bolt11InvoiceFeatures;
50 use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, Payee, PaymentParameters, Route, RouteParameters, Router};
51 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};
52 use crate::ln::msgs;
53 use crate::ln::onion_utils;
54 use crate::ln::onion_utils::{HTLCFailReason, INVALID_ONION_BLINDING};
55 use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
56 #[cfg(test)]
57 use crate::ln::outbound_payment;
58 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs, StaleExpiration};
59 use crate::ln::wire::Encode;
60 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder};
61 use crate::offers::invoice_error::InvoiceError;
62 use crate::offers::merkle::SignError;
63 use crate::offers::offer::{DerivedMetadata, Offer, OfferBuilder};
64 use crate::offers::parse::Bolt12SemanticError;
65 use crate::offers::refund::{Refund, RefundBuilder};
66 use crate::onion_message::messenger::{Destination, MessageRouter, PendingOnionMessage, new_pending_onion_message};
67 use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
68 use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
69 use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
70 use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
71 use crate::util::wakers::{Future, Notifier};
72 use crate::util::scid_utils::fake_scid;
73 use crate::util::string::UntrustedString;
74 use crate::util::ser::{BigSize, FixedLengthReader, Readable, ReadableArgs, MaybeReadable, Writeable, Writer, VecWriter};
75 use crate::util::logger::{Level, Logger, WithContext};
76 use crate::util::errors::APIError;
77 #[cfg(not(c_bindings))]
78 use {
79         crate::routing::router::DefaultRouter,
80         crate::routing::gossip::NetworkGraph,
81         crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters},
82         crate::sign::KeysManager,
83 };
84
85 use alloc::collections::{btree_map, BTreeMap};
86
87 use crate::io;
88 use crate::prelude::*;
89 use core::{cmp, mem};
90 use core::cell::RefCell;
91 use crate::io::Read;
92 use crate::sync::{Arc, Mutex, RwLock, RwLockReadGuard, FairRwLock, LockTestExt, LockHeldState};
93 use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
94 use core::time::Duration;
95 use core::ops::Deref;
96
97 // Re-export this for use in the public API.
98 pub use crate::ln::outbound_payment::{PaymentSendFailure, ProbeSendFailure, Retry, RetryableSendFailure, RecipientOnionFields};
99 use crate::ln::script::ShutdownScript;
100
101 // We hold various information about HTLC relay in the HTLC objects in Channel itself:
102 //
103 // Upon receipt of an HTLC from a peer, we'll give it a PendingHTLCStatus indicating if it should
104 // forward the HTLC with information it will give back to us when it does so, or if it should Fail
105 // the HTLC with the relevant message for the Channel to handle giving to the remote peer.
106 //
107 // Once said HTLC is committed in the Channel, if the PendingHTLCStatus indicated Forward, the
108 // Channel will return the PendingHTLCInfo back to us, and we will create an HTLCForwardInfo
109 // with it to track where it came from (in case of onwards-forward error), waiting a random delay
110 // before we forward it.
111 //
112 // We will then use HTLCForwardInfo's PendingHTLCInfo to construct an outbound HTLC, with a
113 // relevant HTLCSource::PreviousHopData filled in to indicate where it came from (which we can use
114 // to either fail-backwards or fulfill the HTLC backwards along the relevant path).
115 // Alternatively, we can fill an outbound HTLC with a HTLCSource::OutboundRoute indicating this is
116 // our payment, which we can use to decode errors or inform the user that the payment was sent.
117
118 /// Information about where a received HTLC('s onion) has indicated the HTLC should go.
119 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
120 #[cfg_attr(test, derive(Debug, PartialEq))]
121 pub enum PendingHTLCRouting {
122         /// An HTLC which should be forwarded on to another node.
123         Forward {
124                 /// The onion which should be included in the forwarded HTLC, telling the next hop what to
125                 /// do with the HTLC.
126                 onion_packet: msgs::OnionPacket,
127                 /// The short channel ID of the channel which we were instructed to forward this HTLC to.
128                 ///
129                 /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning
130                 /// to the receiving node, such as one returned from
131                 /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`].
132                 short_channel_id: u64, // This should be NonZero<u64> eventually when we bump MSRV
133                 /// Set if this HTLC is being forwarded within a blinded path.
134                 blinded: Option<BlindedForward>,
135         },
136         /// The onion indicates that this is a payment for an invoice (supposedly) generated by us.
137         ///
138         /// Note that at this point, we have not checked that the invoice being paid was actually
139         /// generated by us, but rather it's claiming to pay an invoice of ours.
140         Receive {
141                 /// Information about the amount the sender intended to pay and (potential) proof that this
142                 /// is a payment for an invoice we generated. This proof of payment is is also used for
143                 /// linking MPP parts of a larger payment.
144                 payment_data: msgs::FinalOnionHopData,
145                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
146                 ///
147                 /// For HTLCs received by LDK, this will ultimately be exposed in
148                 /// [`Event::PaymentClaimable::onion_fields`] as
149                 /// [`RecipientOnionFields::payment_metadata`].
150                 payment_metadata: Option<Vec<u8>>,
151                 /// CLTV expiry of the received HTLC.
152                 ///
153                 /// Used to track when we should expire pending HTLCs that go unclaimed.
154                 incoming_cltv_expiry: u32,
155                 /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will
156                 /// provide the onion shared secret used to decrypt the next level of forwarding
157                 /// instructions.
158                 phantom_shared_secret: Option<[u8; 32]>,
159                 /// Custom TLVs which were set by the sender.
160                 ///
161                 /// For HTLCs received by LDK, this will ultimately be exposed in
162                 /// [`Event::PaymentClaimable::onion_fields`] as
163                 /// [`RecipientOnionFields::custom_tlvs`].
164                 custom_tlvs: Vec<(u64, Vec<u8>)>,
165                 /// Set if this HTLC is the final hop in a multi-hop blinded path.
166                 requires_blinded_error: bool,
167         },
168         /// The onion indicates that this is for payment to us but which contains the preimage for
169         /// claiming included, and is unrelated to any invoice we'd previously generated (aka a
170         /// "keysend" or "spontaneous" payment).
171         ReceiveKeysend {
172                 /// Information about the amount the sender intended to pay and possibly a token to
173                 /// associate MPP parts of a larger payment.
174                 ///
175                 /// This will only be filled in if receiving MPP keysend payments is enabled, and it being
176                 /// present will cause deserialization to fail on versions of LDK prior to 0.0.116.
177                 payment_data: Option<msgs::FinalOnionHopData>,
178                 /// Preimage for this onion payment. This preimage is provided by the sender and will be
179                 /// used to settle the spontaneous payment.
180                 payment_preimage: PaymentPreimage,
181                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
182                 ///
183                 /// For HTLCs received by LDK, this will ultimately bubble back up as
184                 /// [`RecipientOnionFields::payment_metadata`].
185                 payment_metadata: Option<Vec<u8>>,
186                 /// CLTV expiry of the received HTLC.
187                 ///
188                 /// Used to track when we should expire pending HTLCs that go unclaimed.
189                 incoming_cltv_expiry: u32,
190                 /// Custom TLVs which were set by the sender.
191                 ///
192                 /// For HTLCs received by LDK, these will ultimately bubble back up as
193                 /// [`RecipientOnionFields::custom_tlvs`].
194                 custom_tlvs: Vec<(u64, Vec<u8>)>,
195         },
196 }
197
198 /// Information used to forward or fail this HTLC that is being forwarded within a blinded path.
199 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
200 pub struct BlindedForward {
201         /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
202         /// onion payload if we're the introduction node. Useful for calculating the next hop's
203         /// [`msgs::UpdateAddHTLC::blinding_point`].
204         pub inbound_blinding_point: PublicKey,
205         /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
206         /// the introduction node.
207         pub failure: BlindedFailure,
208 }
209
210 impl PendingHTLCRouting {
211         // Used to override the onion failure code and data if the HTLC is blinded.
212         fn blinded_failure(&self) -> Option<BlindedFailure> {
213                 match self {
214                         Self::Forward { blinded: Some(BlindedForward { failure, .. }), .. } => Some(*failure),
215                         Self::Receive { requires_blinded_error: true, .. } => Some(BlindedFailure::FromBlindedNode),
216                         _ => None,
217                 }
218         }
219 }
220
221 /// Information about an incoming HTLC, including the [`PendingHTLCRouting`] describing where it
222 /// should go next.
223 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
224 #[cfg_attr(test, derive(Debug, PartialEq))]
225 pub struct PendingHTLCInfo {
226         /// Further routing details based on whether the HTLC is being forwarded or received.
227         pub routing: PendingHTLCRouting,
228         /// The onion shared secret we build with the sender used to decrypt the onion.
229         ///
230         /// This is later used to encrypt failure packets in the event that the HTLC is failed.
231         pub incoming_shared_secret: [u8; 32],
232         /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
233         pub payment_hash: PaymentHash,
234         /// Amount received in the incoming HTLC.
235         ///
236         /// This field was added in LDK 0.0.113 and will be `None` for objects written by prior
237         /// versions.
238         pub incoming_amt_msat: Option<u64>,
239         /// The amount the sender indicated should be forwarded on to the next hop or amount the sender
240         /// intended for us to receive for received payments.
241         ///
242         /// If the received amount is less than this for received payments, an intermediary hop has
243         /// attempted to steal some of our funds and we should fail the HTLC (the sender should retry
244         /// it along another path).
245         ///
246         /// Because nodes can take less than their required fees, and because senders may wish to
247         /// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for
248         /// received payments. In such cases, recipients must handle this HTLC as if it had received
249         /// [`Self::outgoing_amt_msat`].
250         pub outgoing_amt_msat: u64,
251         /// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated
252         /// should have been set on the received HTLC for received payments).
253         pub outgoing_cltv_value: u32,
254         /// The fee taken for this HTLC in addition to the standard protocol HTLC fees.
255         ///
256         /// If this is a payment for forwarding, this is the fee we are taking before forwarding the
257         /// HTLC.
258         ///
259         /// If this is a received payment, this is the fee that our counterparty took.
260         ///
261         /// This is used to allow LSPs to take fees as a part of payments, without the sender having to
262         /// shoulder them.
263         pub skimmed_fee_msat: Option<u64>,
264 }
265
266 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
267 pub(super) enum HTLCFailureMsg {
268         Relay(msgs::UpdateFailHTLC),
269         Malformed(msgs::UpdateFailMalformedHTLC),
270 }
271
272 /// Stores whether we can't forward an HTLC or relevant forwarding info
273 #[derive(Clone)] // See Channel::revoke_and_ack for why, tl;dr: Rust bug
274 pub(super) enum PendingHTLCStatus {
275         Forward(PendingHTLCInfo),
276         Fail(HTLCFailureMsg),
277 }
278
279 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
280 pub(super) struct PendingAddHTLCInfo {
281         pub(super) forward_info: PendingHTLCInfo,
282
283         // These fields are produced in `forward_htlcs()` and consumed in
284         // `process_pending_htlc_forwards()` for constructing the
285         // `HTLCSource::PreviousHopData` for failed and forwarded
286         // HTLCs.
287         //
288         // Note that this may be an outbound SCID alias for the associated channel.
289         prev_short_channel_id: u64,
290         prev_htlc_id: u64,
291         prev_channel_id: ChannelId,
292         prev_funding_outpoint: OutPoint,
293         prev_user_channel_id: u128,
294 }
295
296 #[cfg_attr(test, derive(Clone, Debug, PartialEq))]
297 pub(super) enum HTLCForwardInfo {
298         AddHTLC(PendingAddHTLCInfo),
299         FailHTLC {
300                 htlc_id: u64,
301                 err_packet: msgs::OnionErrorPacket,
302         },
303         FailMalformedHTLC {
304                 htlc_id: u64,
305                 failure_code: u16,
306                 sha256_of_onion: [u8; 32],
307         },
308 }
309
310 /// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node,
311 /// which determines the failure message that should be used.
312 #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
313 pub enum BlindedFailure {
314         /// This HTLC is being failed backwards by the introduction node, and thus should be failed with
315         /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`.
316         FromIntroductionNode,
317         /// This HTLC is being failed backwards by a blinded node within the path, and thus should be
318         /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`.
319         FromBlindedNode,
320 }
321
322 /// Tracks the inbound corresponding to an outbound HTLC
323 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
324 pub(crate) struct HTLCPreviousHopData {
325         // Note that this may be an outbound SCID alias for the associated channel.
326         short_channel_id: u64,
327         user_channel_id: Option<u128>,
328         htlc_id: u64,
329         incoming_packet_shared_secret: [u8; 32],
330         phantom_shared_secret: Option<[u8; 32]>,
331         blinded_failure: Option<BlindedFailure>,
332         channel_id: ChannelId,
333
334         // This field is consumed by `claim_funds_from_hop()` when updating a force-closed backwards
335         // channel with a preimage provided by the forward channel.
336         outpoint: OutPoint,
337 }
338
339 enum OnionPayload {
340         /// Indicates this incoming onion payload is for the purpose of paying an invoice.
341         Invoice {
342                 /// This is only here for backwards-compatibility in serialization, in the future it can be
343                 /// removed, breaking clients running 0.0.106 and earlier.
344                 _legacy_hop_data: Option<msgs::FinalOnionHopData>,
345         },
346         /// Contains the payer-provided preimage.
347         Spontaneous(PaymentPreimage),
348 }
349
350 /// HTLCs that are to us and can be failed/claimed by the user
351 struct ClaimableHTLC {
352         prev_hop: HTLCPreviousHopData,
353         cltv_expiry: u32,
354         /// The amount (in msats) of this MPP part
355         value: u64,
356         /// The amount (in msats) that the sender intended to be sent in this MPP
357         /// part (used for validating total MPP amount)
358         sender_intended_value: u64,
359         onion_payload: OnionPayload,
360         timer_ticks: u8,
361         /// The total value received for a payment (sum of all MPP parts if the payment is a MPP).
362         /// Gets set to the amount reported when pushing [`Event::PaymentClaimable`].
363         total_value_received: Option<u64>,
364         /// The sender intended sum total of all MPP parts specified in the onion
365         total_msat: u64,
366         /// The extra fee our counterparty skimmed off the top of this HTLC.
367         counterparty_skimmed_fee_msat: Option<u64>,
368 }
369
370 impl From<&ClaimableHTLC> for events::ClaimedHTLC {
371         fn from(val: &ClaimableHTLC) -> Self {
372                 events::ClaimedHTLC {
373                         channel_id: val.prev_hop.channel_id,
374                         user_channel_id: val.prev_hop.user_channel_id.unwrap_or(0),
375                         cltv_expiry: val.cltv_expiry,
376                         value_msat: val.value,
377                         counterparty_skimmed_fee_msat: val.counterparty_skimmed_fee_msat.unwrap_or(0),
378                 }
379         }
380 }
381
382 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
383 /// a payment and ensure idempotency in LDK.
384 ///
385 /// This is not exported to bindings users as we just use [u8; 32] directly
386 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
387 pub struct PaymentId(pub [u8; Self::LENGTH]);
388
389 impl PaymentId {
390         /// Number of bytes in the id.
391         pub const LENGTH: usize = 32;
392 }
393
394 impl Writeable for PaymentId {
395         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
396                 self.0.write(w)
397         }
398 }
399
400 impl Readable for PaymentId {
401         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
402                 let buf: [u8; 32] = Readable::read(r)?;
403                 Ok(PaymentId(buf))
404         }
405 }
406
407 impl core::fmt::Display for PaymentId {
408         fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
409                 crate::util::logger::DebugBytes(&self.0).fmt(f)
410         }
411 }
412
413 /// An identifier used to uniquely identify an intercepted HTLC to LDK.
414 ///
415 /// This is not exported to bindings users as we just use [u8; 32] directly
416 #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
417 pub struct InterceptId(pub [u8; 32]);
418
419 impl Writeable for InterceptId {
420         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
421                 self.0.write(w)
422         }
423 }
424
425 impl Readable for InterceptId {
426         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
427                 let buf: [u8; 32] = Readable::read(r)?;
428                 Ok(InterceptId(buf))
429         }
430 }
431
432 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
433 /// Uniquely describes an HTLC by its source. Just the guaranteed-unique subset of [`HTLCSource`].
434 pub(crate) enum SentHTLCId {
435         PreviousHopData { short_channel_id: u64, htlc_id: u64 },
436         OutboundRoute { session_priv: [u8; SECRET_KEY_SIZE] },
437 }
438 impl SentHTLCId {
439         pub(crate) fn from_source(source: &HTLCSource) -> Self {
440                 match source {
441                         HTLCSource::PreviousHopData(hop_data) => Self::PreviousHopData {
442                                 short_channel_id: hop_data.short_channel_id,
443                                 htlc_id: hop_data.htlc_id,
444                         },
445                         HTLCSource::OutboundRoute { session_priv, .. } =>
446                                 Self::OutboundRoute { session_priv: session_priv.secret_bytes() },
447                 }
448         }
449 }
450 impl_writeable_tlv_based_enum!(SentHTLCId,
451         (0, PreviousHopData) => {
452                 (0, short_channel_id, required),
453                 (2, htlc_id, required),
454         },
455         (2, OutboundRoute) => {
456                 (0, session_priv, required),
457         };
458 );
459
460
461 /// Tracks the inbound corresponding to an outbound HTLC
462 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
463 #[derive(Clone, Debug, PartialEq, Eq)]
464 pub(crate) enum HTLCSource {
465         PreviousHopData(HTLCPreviousHopData),
466         OutboundRoute {
467                 path: Path,
468                 session_priv: SecretKey,
469                 /// Technically we can recalculate this from the route, but we cache it here to avoid
470                 /// doing a double-pass on route when we get a failure back
471                 first_hop_htlc_msat: u64,
472                 payment_id: PaymentId,
473         },
474 }
475 #[allow(clippy::derive_hash_xor_eq)] // Our Hash is faithful to the data, we just don't have SecretKey::hash
476 impl core::hash::Hash for HTLCSource {
477         fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
478                 match self {
479                         HTLCSource::PreviousHopData(prev_hop_data) => {
480                                 0u8.hash(hasher);
481                                 prev_hop_data.hash(hasher);
482                         },
483                         HTLCSource::OutboundRoute { path, session_priv, payment_id, first_hop_htlc_msat } => {
484                                 1u8.hash(hasher);
485                                 path.hash(hasher);
486                                 session_priv[..].hash(hasher);
487                                 payment_id.hash(hasher);
488                                 first_hop_htlc_msat.hash(hasher);
489                         },
490                 }
491         }
492 }
493 impl HTLCSource {
494         #[cfg(all(feature = "_test_vectors", not(feature = "grind_signatures")))]
495         #[cfg(test)]
496         pub fn dummy() -> Self {
497                 HTLCSource::OutboundRoute {
498                         path: Path { hops: Vec::new(), blinded_tail: None },
499                         session_priv: SecretKey::from_slice(&[1; 32]).unwrap(),
500                         first_hop_htlc_msat: 0,
501                         payment_id: PaymentId([2; 32]),
502                 }
503         }
504
505         #[cfg(debug_assertions)]
506         /// Checks whether this HTLCSource could possibly match the given HTLC output in a commitment
507         /// transaction. Useful to ensure different datastructures match up.
508         pub(crate) fn possibly_matches_output(&self, htlc: &super::chan_utils::HTLCOutputInCommitment) -> bool {
509                 if let HTLCSource::OutboundRoute { first_hop_htlc_msat, .. } = self {
510                         *first_hop_htlc_msat == htlc.amount_msat
511                 } else {
512                         // There's nothing we can check for forwarded HTLCs
513                         true
514                 }
515         }
516 }
517
518 /// This enum is used to specify which error data to send to peers when failing back an HTLC
519 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
520 ///
521 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
522 #[derive(Clone, Copy)]
523 pub enum FailureCode {
524         /// We had a temporary error processing the payment. Useful if no other error codes fit
525         /// and you want to indicate that the payer may want to retry.
526         TemporaryNodeFailure,
527         /// We have a required feature which was not in this onion. For example, you may require
528         /// some additional metadata that was not provided with this payment.
529         RequiredNodeFeatureMissing,
530         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
531         /// the HTLC is too close to the current block height for safe handling.
532         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
533         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
534         IncorrectOrUnknownPaymentDetails,
535         /// We failed to process the payload after the onion was decrypted. You may wish to
536         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
537         ///
538         /// If available, the tuple data may include the type number and byte offset in the
539         /// decrypted byte stream where the failure occurred.
540         InvalidOnionPayload(Option<(u64, u16)>),
541 }
542
543 impl Into<u16> for FailureCode {
544     fn into(self) -> u16 {
545                 match self {
546                         FailureCode::TemporaryNodeFailure => 0x2000 | 2,
547                         FailureCode::RequiredNodeFeatureMissing => 0x4000 | 0x2000 | 3,
548                         FailureCode::IncorrectOrUnknownPaymentDetails => 0x4000 | 15,
549                         FailureCode::InvalidOnionPayload(_) => 0x4000 | 22,
550                 }
551         }
552 }
553
554 /// Error type returned across the peer_state mutex boundary. When an Err is generated for a
555 /// Channel, we generally end up with a ChannelError::Close for which we have to close the channel
556 /// immediately (ie with no further calls on it made). Thus, this step happens inside a
557 /// peer_state lock. We then return the set of things that need to be done outside the lock in
558 /// this struct and call handle_error!() on it.
559
560 struct MsgHandleErrInternal {
561         err: msgs::LightningError,
562         closes_channel: bool,
563         shutdown_finish: Option<(ShutdownResult, Option<msgs::ChannelUpdate>)>,
564 }
565 impl MsgHandleErrInternal {
566         #[inline]
567         fn send_err_msg_no_close(err: String, channel_id: ChannelId) -> Self {
568                 Self {
569                         err: LightningError {
570                                 err: err.clone(),
571                                 action: msgs::ErrorAction::SendErrorMessage {
572                                         msg: msgs::ErrorMessage {
573                                                 channel_id,
574                                                 data: err
575                                         },
576                                 },
577                         },
578                         closes_channel: false,
579                         shutdown_finish: None,
580                 }
581         }
582         #[inline]
583         fn from_no_close(err: msgs::LightningError) -> Self {
584                 Self { err, closes_channel: false, shutdown_finish: None }
585         }
586         #[inline]
587         fn from_finish_shutdown(err: String, channel_id: ChannelId, shutdown_res: ShutdownResult, channel_update: Option<msgs::ChannelUpdate>) -> Self {
588                 let err_msg = msgs::ErrorMessage { channel_id, data: err.clone() };
589                 let action = if shutdown_res.monitor_update.is_some() {
590                         // We have a closing `ChannelMonitorUpdate`, which means the channel was funded and we
591                         // should disconnect our peer such that we force them to broadcast their latest
592                         // commitment upon reconnecting.
593                         msgs::ErrorAction::DisconnectPeer { msg: Some(err_msg) }
594                 } else {
595                         msgs::ErrorAction::SendErrorMessage { msg: err_msg }
596                 };
597                 Self {
598                         err: LightningError { err, action },
599                         closes_channel: true,
600                         shutdown_finish: Some((shutdown_res, channel_update)),
601                 }
602         }
603         #[inline]
604         fn from_chan_no_close(err: ChannelError, channel_id: ChannelId) -> Self {
605                 Self {
606                         err: match err {
607                                 ChannelError::Warn(msg) =>  LightningError {
608                                         err: msg.clone(),
609                                         action: msgs::ErrorAction::SendWarningMessage {
610                                                 msg: msgs::WarningMessage {
611                                                         channel_id,
612                                                         data: msg
613                                                 },
614                                                 log_level: Level::Warn,
615                                         },
616                                 },
617                                 ChannelError::Ignore(msg) => LightningError {
618                                         err: msg,
619                                         action: msgs::ErrorAction::IgnoreError,
620                                 },
621                                 ChannelError::Close(msg) => LightningError {
622                                         err: msg.clone(),
623                                         action: msgs::ErrorAction::SendErrorMessage {
624                                                 msg: msgs::ErrorMessage {
625                                                         channel_id,
626                                                         data: msg
627                                                 },
628                                         },
629                                 },
630                         },
631                         closes_channel: false,
632                         shutdown_finish: None,
633                 }
634         }
635
636         fn closes_channel(&self) -> bool {
637                 self.closes_channel
638         }
639 }
640
641 /// We hold back HTLCs we intend to relay for a random interval greater than this (see
642 /// Event::PendingHTLCsForwardable for the API guidelines indicating how long should be waited).
643 /// This provides some limited amount of privacy. Ideally this would range from somewhere like one
644 /// second to 30 seconds, but people expect lightning to be, you know, kinda fast, sadly.
645 pub(super) const MIN_HTLC_RELAY_HOLDING_CELL_MILLIS: u64 = 100;
646
647 /// For events which result in both a RevokeAndACK and a CommitmentUpdate, by default they should
648 /// be sent in the order they appear in the return value, however sometimes the order needs to be
649 /// variable at runtime (eg Channel::channel_reestablish needs to re-send messages in the order
650 /// they were originally sent). In those cases, this enum is also returned.
651 #[derive(Clone, PartialEq)]
652 pub(super) enum RAACommitmentOrder {
653         /// Send the CommitmentUpdate messages first
654         CommitmentFirst,
655         /// Send the RevokeAndACK message first
656         RevokeAndACKFirst,
657 }
658
659 /// Information about a payment which is currently being claimed.
660 struct ClaimingPayment {
661         amount_msat: u64,
662         payment_purpose: events::PaymentPurpose,
663         receiver_node_id: PublicKey,
664         htlcs: Vec<events::ClaimedHTLC>,
665         sender_intended_value: Option<u64>,
666 }
667 impl_writeable_tlv_based!(ClaimingPayment, {
668         (0, amount_msat, required),
669         (2, payment_purpose, required),
670         (4, receiver_node_id, required),
671         (5, htlcs, optional_vec),
672         (7, sender_intended_value, option),
673 });
674
675 struct ClaimablePayment {
676         purpose: events::PaymentPurpose,
677         onion_fields: Option<RecipientOnionFields>,
678         htlcs: Vec<ClaimableHTLC>,
679 }
680
681 /// Information about claimable or being-claimed payments
682 struct ClaimablePayments {
683         /// Map from payment hash to the payment data and any HTLCs which are to us and can be
684         /// failed/claimed by the user.
685         ///
686         /// Note that, no consistency guarantees are made about the channels given here actually
687         /// existing anymore by the time you go to read them!
688         ///
689         /// When adding to the map, [`Self::pending_claiming_payments`] must also be checked to ensure
690         /// we don't get a duplicate payment.
691         claimable_payments: HashMap<PaymentHash, ClaimablePayment>,
692
693         /// Map from payment hash to the payment data for HTLCs which we have begun claiming, but which
694         /// are waiting on a [`ChannelMonitorUpdate`] to complete in order to be surfaced to the user
695         /// as an [`events::Event::PaymentClaimed`].
696         pending_claiming_payments: HashMap<PaymentHash, ClaimingPayment>,
697 }
698
699 /// Events which we process internally but cannot be processed immediately at the generation site
700 /// usually because we're running pre-full-init. They are handled immediately once we detect we are
701 /// running normally, and specifically must be processed before any other non-background
702 /// [`ChannelMonitorUpdate`]s are applied.
703 #[derive(Debug)]
704 enum BackgroundEvent {
705         /// Handle a ChannelMonitorUpdate which closes the channel or for an already-closed channel.
706         /// This is only separated from [`Self::MonitorUpdateRegeneratedOnStartup`] as the
707         /// maybe-non-closing variant needs a public key to handle channel resumption, whereas if the
708         /// channel has been force-closed we do not need the counterparty node_id.
709         ///
710         /// Note that any such events are lost on shutdown, so in general they must be updates which
711         /// are regenerated on startup.
712         ClosedMonitorUpdateRegeneratedOnStartup((OutPoint, ChannelId, ChannelMonitorUpdate)),
713         /// Handle a ChannelMonitorUpdate which may or may not close the channel and may unblock the
714         /// channel to continue normal operation.
715         ///
716         /// In general this should be used rather than
717         /// [`Self::ClosedMonitorUpdateRegeneratedOnStartup`], however in cases where the
718         /// `counterparty_node_id` is not available as the channel has closed from a [`ChannelMonitor`]
719         /// error the other variant is acceptable.
720         ///
721         /// Note that any such events are lost on shutdown, so in general they must be updates which
722         /// are regenerated on startup.
723         MonitorUpdateRegeneratedOnStartup {
724                 counterparty_node_id: PublicKey,
725                 funding_txo: OutPoint,
726                 channel_id: ChannelId,
727                 update: ChannelMonitorUpdate
728         },
729         /// Some [`ChannelMonitorUpdate`] (s) completed before we were serialized but we still have
730         /// them marked pending, thus we need to run any [`MonitorUpdateCompletionAction`] (s) pending
731         /// on a channel.
732         MonitorUpdatesComplete {
733                 counterparty_node_id: PublicKey,
734                 channel_id: ChannelId,
735         },
736 }
737
738 #[derive(Debug)]
739 pub(crate) enum MonitorUpdateCompletionAction {
740         /// Indicates that a payment ultimately destined for us was claimed and we should emit an
741         /// [`events::Event::PaymentClaimed`] to the user if we haven't yet generated such an event for
742         /// this payment. Note that this is only best-effort. On restart it's possible such a duplicate
743         /// event can be generated.
744         PaymentClaimed { payment_hash: PaymentHash },
745         /// Indicates an [`events::Event`] should be surfaced to the user and possibly resume the
746         /// operation of another channel.
747         ///
748         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
749         /// from completing a monitor update which removes the payment preimage until the inbound edge
750         /// completes a monitor update containing the payment preimage. In that case, after the inbound
751         /// edge completes, we will surface an [`Event::PaymentForwarded`] as well as unblock the
752         /// outbound edge.
753         EmitEventAndFreeOtherChannel {
754                 event: events::Event,
755                 downstream_counterparty_and_funding_outpoint: Option<(PublicKey, OutPoint, ChannelId, RAAMonitorUpdateBlockingAction)>,
756         },
757         /// Indicates we should immediately resume the operation of another channel, unless there is
758         /// some other reason why the channel is blocked. In practice this simply means immediately
759         /// removing the [`RAAMonitorUpdateBlockingAction`] provided from the blocking set.
760         ///
761         /// This is usually generated when we've forwarded an HTLC and want to block the outbound edge
762         /// from completing a monitor update which removes the payment preimage until the inbound edge
763         /// completes a monitor update containing the payment preimage. However, we use this variant
764         /// instead of [`Self::EmitEventAndFreeOtherChannel`] when we discover that the claim was in
765         /// fact duplicative and we simply want to resume the outbound edge channel immediately.
766         ///
767         /// This variant should thus never be written to disk, as it is processed inline rather than
768         /// stored for later processing.
769         FreeOtherChannelImmediately {
770                 downstream_counterparty_node_id: PublicKey,
771                 downstream_funding_outpoint: OutPoint,
772                 blocking_action: RAAMonitorUpdateBlockingAction,
773                 downstream_channel_id: ChannelId,
774         },
775 }
776
777 impl_writeable_tlv_based_enum_upgradable!(MonitorUpdateCompletionAction,
778         (0, PaymentClaimed) => { (0, payment_hash, required) },
779         // Note that FreeOtherChannelImmediately should never be written - we were supposed to free
780         // *immediately*. However, for simplicity we implement read/write here.
781         (1, FreeOtherChannelImmediately) => {
782                 (0, downstream_counterparty_node_id, required),
783                 (2, downstream_funding_outpoint, required),
784                 (4, blocking_action, required),
785                 // Note that by the time we get past the required read above, downstream_funding_outpoint will be
786                 // filled in, so we can safely unwrap it here.
787                 (5, downstream_channel_id, (default_value, ChannelId::v1_from_funding_outpoint(downstream_funding_outpoint.0.unwrap()))),
788         },
789         (2, EmitEventAndFreeOtherChannel) => {
790                 (0, event, upgradable_required),
791                 // LDK prior to 0.0.116 did not have this field as the monitor update application order was
792                 // required by clients. If we downgrade to something prior to 0.0.116 this may result in
793                 // monitor updates which aren't properly blocked or resumed, however that's fine - we don't
794                 // support async monitor updates even in LDK 0.0.116 and once we do we'll require no
795                 // downgrades to prior versions.
796                 (1, downstream_counterparty_and_funding_outpoint, option),
797         },
798 );
799
800 #[derive(Clone, Debug, PartialEq, Eq)]
801 pub(crate) enum EventCompletionAction {
802         ReleaseRAAChannelMonitorUpdate {
803                 counterparty_node_id: PublicKey,
804                 channel_funding_outpoint: OutPoint,
805                 channel_id: ChannelId,
806         },
807 }
808 impl_writeable_tlv_based_enum!(EventCompletionAction,
809         (0, ReleaseRAAChannelMonitorUpdate) => {
810                 (0, channel_funding_outpoint, required),
811                 (2, counterparty_node_id, required),
812                 // Note that by the time we get past the required read above, channel_funding_outpoint will be
813                 // filled in, so we can safely unwrap it here.
814                 (3, channel_id, (default_value, ChannelId::v1_from_funding_outpoint(channel_funding_outpoint.0.unwrap()))),
815         };
816 );
817
818 #[derive(Clone, PartialEq, Eq, Debug)]
819 /// If something is blocked on the completion of an RAA-generated [`ChannelMonitorUpdate`] we track
820 /// the blocked action here. See enum variants for more info.
821 pub(crate) enum RAAMonitorUpdateBlockingAction {
822         /// A forwarded payment was claimed. We block the downstream channel completing its monitor
823         /// update which removes the HTLC preimage until the upstream channel has gotten the preimage
824         /// durably to disk.
825         ForwardedPaymentInboundClaim {
826                 /// The upstream channel ID (i.e. the inbound edge).
827                 channel_id: ChannelId,
828                 /// The HTLC ID on the inbound edge.
829                 htlc_id: u64,
830         },
831 }
832
833 impl RAAMonitorUpdateBlockingAction {
834         fn from_prev_hop_data(prev_hop: &HTLCPreviousHopData) -> Self {
835                 Self::ForwardedPaymentInboundClaim {
836                         channel_id: prev_hop.channel_id,
837                         htlc_id: prev_hop.htlc_id,
838                 }
839         }
840 }
841
842 impl_writeable_tlv_based_enum!(RAAMonitorUpdateBlockingAction,
843         (0, ForwardedPaymentInboundClaim) => { (0, channel_id, required), (2, htlc_id, required) }
844 ;);
845
846
847 /// State we hold per-peer.
848 pub(super) struct PeerState<SP: Deref> where SP::Target: SignerProvider {
849         /// `channel_id` -> `ChannelPhase`
850         ///
851         /// Holds all channels within corresponding `ChannelPhase`s where the peer is the counterparty.
852         pub(super) channel_by_id: HashMap<ChannelId, ChannelPhase<SP>>,
853         /// `temporary_channel_id` -> `InboundChannelRequest`.
854         ///
855         /// When manual channel acceptance is enabled, this holds all unaccepted inbound channels where
856         /// the peer is the counterparty. If the channel is accepted, then the entry in this table is
857         /// removed, and an InboundV1Channel is created and placed in the `inbound_v1_channel_by_id` table. If
858         /// the channel is rejected, then the entry is simply removed.
859         pub(super) inbound_channel_request_by_id: HashMap<ChannelId, InboundChannelRequest>,
860         /// The latest `InitFeatures` we heard from the peer.
861         latest_features: InitFeatures,
862         /// Messages to send to the peer - pushed to in the same lock that they are generated in (except
863         /// for broadcast messages, where ordering isn't as strict).
864         pub(super) pending_msg_events: Vec<MessageSendEvent>,
865         /// Map from Channel IDs to pending [`ChannelMonitorUpdate`]s which have been passed to the
866         /// user but which have not yet completed.
867         ///
868         /// Note that the channel may no longer exist. For example if the channel was closed but we
869         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
870         /// for a missing channel.
871         in_flight_monitor_updates: BTreeMap<OutPoint, Vec<ChannelMonitorUpdate>>,
872         /// Map from a specific channel to some action(s) that should be taken when all pending
873         /// [`ChannelMonitorUpdate`]s for the channel complete updating.
874         ///
875         /// Note that because we generally only have one entry here a HashMap is pretty overkill. A
876         /// BTreeMap currently stores more than ten elements per leaf node, so even up to a few
877         /// channels with a peer this will just be one allocation and will amount to a linear list of
878         /// channels to walk, avoiding the whole hashing rigmarole.
879         ///
880         /// Note that the channel may no longer exist. For example, if a channel was closed but we
881         /// later needed to claim an HTLC which is pending on-chain, we may generate a monitor update
882         /// for a missing channel. While a malicious peer could construct a second channel with the
883         /// same `temporary_channel_id` (or final `channel_id` in the case of 0conf channels or prior
884         /// to funding appearing on-chain), the downstream `ChannelMonitor` set is required to ensure
885         /// duplicates do not occur, so such channels should fail without a monitor update completing.
886         monitor_update_blocked_actions: BTreeMap<ChannelId, Vec<MonitorUpdateCompletionAction>>,
887         /// If another channel's [`ChannelMonitorUpdate`] needs to complete before a channel we have
888         /// with this peer can complete an RAA [`ChannelMonitorUpdate`] (e.g. because the RAA update
889         /// will remove a preimage that needs to be durably in an upstream channel first), we put an
890         /// entry here to note that the channel with the key's ID is blocked on a set of actions.
891         actions_blocking_raa_monitor_updates: BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
892         /// The peer is currently connected (i.e. we've seen a
893         /// [`ChannelMessageHandler::peer_connected`] and no corresponding
894         /// [`ChannelMessageHandler::peer_disconnected`].
895         pub is_connected: bool,
896 }
897
898 impl <SP: Deref> PeerState<SP> where SP::Target: SignerProvider {
899         /// Indicates that a peer meets the criteria where we're ok to remove it from our storage.
900         /// If true is passed for `require_disconnected`, the function will return false if we haven't
901         /// disconnected from the node already, ie. `PeerState::is_connected` is set to `true`.
902         fn ok_to_remove(&self, require_disconnected: bool) -> bool {
903                 if require_disconnected && self.is_connected {
904                         return false
905                 }
906                 self.channel_by_id.iter().filter(|(_, phase)| matches!(phase, ChannelPhase::Funded(_))).count() == 0
907                         && self.monitor_update_blocked_actions.is_empty()
908                         && self.in_flight_monitor_updates.is_empty()
909         }
910
911         // Returns a count of all channels we have with this peer, including unfunded channels.
912         fn total_channel_count(&self) -> usize {
913                 self.channel_by_id.len() + self.inbound_channel_request_by_id.len()
914         }
915
916         // Returns a bool indicating if the given `channel_id` matches a channel we have with this peer.
917         fn has_channel(&self, channel_id: &ChannelId) -> bool {
918                 self.channel_by_id.contains_key(channel_id) ||
919                         self.inbound_channel_request_by_id.contains_key(channel_id)
920         }
921 }
922
923 /// A not-yet-accepted inbound (from counterparty) channel. Once
924 /// accepted, the parameters will be used to construct a channel.
925 pub(super) struct InboundChannelRequest {
926         /// The original OpenChannel message.
927         pub open_channel_msg: msgs::OpenChannel,
928         /// The number of ticks remaining before the request expires.
929         pub ticks_remaining: i32,
930 }
931
932 /// The number of ticks that may elapse while we're waiting for an unaccepted inbound channel to be
933 /// accepted. An unaccepted channel that exceeds this limit will be abandoned.
934 const UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS: i32 = 2;
935
936 /// Stores a PaymentSecret and any other data we may need to validate an inbound payment is
937 /// actually ours and not some duplicate HTLC sent to us by a node along the route.
938 ///
939 /// For users who don't want to bother doing their own payment preimage storage, we also store that
940 /// here.
941 ///
942 /// Note that this struct will be removed entirely soon, in favor of storing no inbound payment data
943 /// and instead encoding it in the payment secret.
944 struct PendingInboundPayment {
945         /// The payment secret that the sender must use for us to accept this payment
946         payment_secret: PaymentSecret,
947         /// Time at which this HTLC expires - blocks with a header time above this value will result in
948         /// this payment being removed.
949         expiry_time: u64,
950         /// Arbitrary identifier the user specifies (or not)
951         user_payment_id: u64,
952         // Other required attributes of the payment, optionally enforced:
953         payment_preimage: Option<PaymentPreimage>,
954         min_value_msat: Option<u64>,
955 }
956
957 /// [`SimpleArcChannelManager`] is useful when you need a [`ChannelManager`] with a static lifetime, e.g.
958 /// when you're using `lightning-net-tokio` (since `tokio::spawn` requires parameters with static
959 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
960 /// [`SimpleRefChannelManager`] is the more appropriate type. Defining these type aliases prevents
961 /// issues such as overly long function definitions. Note that the `ChannelManager` can take any type
962 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
963 /// or, respectively, [`Router`] for its router, but this type alias chooses the concrete types
964 /// of [`KeysManager`] and [`DefaultRouter`].
965 ///
966 /// This is not exported to bindings users as type aliases aren't supported in most languages.
967 #[cfg(not(c_bindings))]
968 pub type SimpleArcChannelManager<M, T, F, L> = ChannelManager<
969         Arc<M>,
970         Arc<T>,
971         Arc<KeysManager>,
972         Arc<KeysManager>,
973         Arc<KeysManager>,
974         Arc<F>,
975         Arc<DefaultRouter<
976                 Arc<NetworkGraph<Arc<L>>>,
977                 Arc<L>,
978                 Arc<RwLock<ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>>>,
979                 ProbabilisticScoringFeeParameters,
980                 ProbabilisticScorer<Arc<NetworkGraph<Arc<L>>>, Arc<L>>,
981         >>,
982         Arc<L>
983 >;
984
985 /// [`SimpleRefChannelManager`] is a type alias for a ChannelManager reference, and is the reference
986 /// counterpart to the [`SimpleArcChannelManager`] type alias. Use this type by default when you don't
987 /// need a ChannelManager with a static lifetime. You'll need a static lifetime in cases such as
988 /// usage of lightning-net-tokio (since `tokio::spawn` requires parameters with static lifetimes).
989 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
990 /// issues such as overly long function definitions. Note that the ChannelManager can take any type
991 /// that implements [`NodeSigner`], [`EntropySource`], and [`SignerProvider`] for its keys manager,
992 /// or, respectively, [`Router`]  for its router, but this type alias chooses the concrete types
993 /// of [`KeysManager`] and [`DefaultRouter`].
994 ///
995 /// This is not exported to bindings users as type aliases aren't supported in most languages.
996 #[cfg(not(c_bindings))]
997 pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
998         ChannelManager<
999                 &'a M,
1000                 &'b T,
1001                 &'c KeysManager,
1002                 &'c KeysManager,
1003                 &'c KeysManager,
1004                 &'d F,
1005                 &'e DefaultRouter<
1006                         &'f NetworkGraph<&'g L>,
1007                         &'g L,
1008                         &'h RwLock<ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>>,
1009                         ProbabilisticScoringFeeParameters,
1010                         ProbabilisticScorer<&'f NetworkGraph<&'g L>, &'g L>
1011                 >,
1012                 &'g L
1013         >;
1014
1015 /// A trivial trait which describes any [`ChannelManager`].
1016 ///
1017 /// This is not exported to bindings users as general cover traits aren't useful in other
1018 /// languages.
1019 pub trait AChannelManager {
1020         /// A type implementing [`chain::Watch`].
1021         type Watch: chain::Watch<Self::Signer> + ?Sized;
1022         /// A type that may be dereferenced to [`Self::Watch`].
1023         type M: Deref<Target = Self::Watch>;
1024         /// A type implementing [`BroadcasterInterface`].
1025         type Broadcaster: BroadcasterInterface + ?Sized;
1026         /// A type that may be dereferenced to [`Self::Broadcaster`].
1027         type T: Deref<Target = Self::Broadcaster>;
1028         /// A type implementing [`EntropySource`].
1029         type EntropySource: EntropySource + ?Sized;
1030         /// A type that may be dereferenced to [`Self::EntropySource`].
1031         type ES: Deref<Target = Self::EntropySource>;
1032         /// A type implementing [`NodeSigner`].
1033         type NodeSigner: NodeSigner + ?Sized;
1034         /// A type that may be dereferenced to [`Self::NodeSigner`].
1035         type NS: Deref<Target = Self::NodeSigner>;
1036         /// A type implementing [`WriteableEcdsaChannelSigner`].
1037         type Signer: WriteableEcdsaChannelSigner + Sized;
1038         /// A type implementing [`SignerProvider`] for [`Self::Signer`].
1039         type SignerProvider: SignerProvider<EcdsaSigner= Self::Signer> + ?Sized;
1040         /// A type that may be dereferenced to [`Self::SignerProvider`].
1041         type SP: Deref<Target = Self::SignerProvider>;
1042         /// A type implementing [`FeeEstimator`].
1043         type FeeEstimator: FeeEstimator + ?Sized;
1044         /// A type that may be dereferenced to [`Self::FeeEstimator`].
1045         type F: Deref<Target = Self::FeeEstimator>;
1046         /// A type implementing [`Router`].
1047         type Router: Router + ?Sized;
1048         /// A type that may be dereferenced to [`Self::Router`].
1049         type R: Deref<Target = Self::Router>;
1050         /// A type implementing [`Logger`].
1051         type Logger: Logger + ?Sized;
1052         /// A type that may be dereferenced to [`Self::Logger`].
1053         type L: Deref<Target = Self::Logger>;
1054         /// Returns a reference to the actual [`ChannelManager`] object.
1055         fn get_cm(&self) -> &ChannelManager<Self::M, Self::T, Self::ES, Self::NS, Self::SP, Self::F, Self::R, Self::L>;
1056 }
1057
1058 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> AChannelManager
1059 for ChannelManager<M, T, ES, NS, SP, F, R, L>
1060 where
1061         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1062         T::Target: BroadcasterInterface,
1063         ES::Target: EntropySource,
1064         NS::Target: NodeSigner,
1065         SP::Target: SignerProvider,
1066         F::Target: FeeEstimator,
1067         R::Target: Router,
1068         L::Target: Logger,
1069 {
1070         type Watch = M::Target;
1071         type M = M;
1072         type Broadcaster = T::Target;
1073         type T = T;
1074         type EntropySource = ES::Target;
1075         type ES = ES;
1076         type NodeSigner = NS::Target;
1077         type NS = NS;
1078         type Signer = <SP::Target as SignerProvider>::EcdsaSigner;
1079         type SignerProvider = SP::Target;
1080         type SP = SP;
1081         type FeeEstimator = F::Target;
1082         type F = F;
1083         type Router = R::Target;
1084         type R = R;
1085         type Logger = L::Target;
1086         type L = L;
1087         fn get_cm(&self) -> &ChannelManager<M, T, ES, NS, SP, F, R, L> { self }
1088 }
1089
1090 /// Manager which keeps track of a number of channels and sends messages to the appropriate
1091 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
1092 ///
1093 /// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through
1094 /// to individual Channels.
1095 ///
1096 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
1097 /// all peers during write/read (though does not modify this instance, only the instance being
1098 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
1099 /// called [`funding_transaction_generated`] for outbound channels) being closed.
1100 ///
1101 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
1102 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
1103 /// [`ChannelMonitorUpdate`] before returning from
1104 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
1105 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
1106 /// `ChannelManager` operations from occurring during the serialization process). If the
1107 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
1108 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
1109 /// will be lost (modulo on-chain transaction fees).
1110 ///
1111 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
1112 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
1113 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
1114 ///
1115 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1116 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1117 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1118 /// offline for a full minute. In order to track this, you must call
1119 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1120 ///
1121 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1122 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1123 /// not have a channel with being unable to connect to us or open new channels with us if we have
1124 /// many peers with unfunded channels.
1125 ///
1126 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1127 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1128 /// never limited. Please ensure you limit the count of such channels yourself.
1129 ///
1130 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1131 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1132 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1133 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1134 /// you're using lightning-net-tokio.
1135 ///
1136 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1137 /// [`funding_created`]: msgs::FundingCreated
1138 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1139 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1140 /// [`update_channel`]: chain::Watch::update_channel
1141 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1142 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1143 /// [`read`]: ReadableArgs::read
1144 //
1145 // Lock order:
1146 // The tree structure below illustrates the lock order requirements for the different locks of the
1147 // `ChannelManager`. Locks can be held at the same time if they are on the same branch in the tree,
1148 // and should then be taken in the order of the lowest to the highest level in the tree.
1149 // Note that locks on different branches shall not be taken at the same time, as doing so will
1150 // create a new lock order for those specific locks in the order they were taken.
1151 //
1152 // Lock order tree:
1153 //
1154 // `pending_offers_messages`
1155 //
1156 // `total_consistency_lock`
1157 //  |
1158 //  |__`forward_htlcs`
1159 //  |   |
1160 //  |   |__`pending_intercepted_htlcs`
1161 //  |
1162 //  |__`per_peer_state`
1163 //      |
1164 //      |__`pending_inbound_payments`
1165 //          |
1166 //          |__`claimable_payments`
1167 //          |
1168 //          |__`pending_outbound_payments` // This field's struct contains a map of pending outbounds
1169 //              |
1170 //              |__`peer_state`
1171 //                  |
1172 //                  |__`outpoint_to_peer`
1173 //                  |
1174 //                  |__`short_to_chan_info`
1175 //                  |
1176 //                  |__`outbound_scid_aliases`
1177 //                  |
1178 //                  |__`best_block`
1179 //                  |
1180 //                  |__`pending_events`
1181 //                      |
1182 //                      |__`pending_background_events`
1183 //
1184 pub struct ChannelManager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
1185 where
1186         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
1187         T::Target: BroadcasterInterface,
1188         ES::Target: EntropySource,
1189         NS::Target: NodeSigner,
1190         SP::Target: SignerProvider,
1191         F::Target: FeeEstimator,
1192         R::Target: Router,
1193         L::Target: Logger,
1194 {
1195         default_configuration: UserConfig,
1196         chain_hash: ChainHash,
1197         fee_estimator: LowerBoundedFeeEstimator<F>,
1198         chain_monitor: M,
1199         tx_broadcaster: T,
1200         #[allow(unused)]
1201         router: R,
1202
1203         /// See `ChannelManager` struct-level documentation for lock order requirements.
1204         #[cfg(test)]
1205         pub(super) best_block: RwLock<BestBlock>,
1206         #[cfg(not(test))]
1207         best_block: RwLock<BestBlock>,
1208         secp_ctx: Secp256k1<secp256k1::All>,
1209
1210         /// Storage for PaymentSecrets and any requirements on future inbound payments before we will
1211         /// expose them to users via a PaymentClaimable event. HTLCs which do not meet the requirements
1212         /// here are failed when we process them as pending-forwardable-HTLCs, and entries are removed
1213         /// after we generate a PaymentClaimable upon receipt of all MPP parts or when they time out.
1214         ///
1215         /// See `ChannelManager` struct-level documentation for lock order requirements.
1216         pending_inbound_payments: Mutex<HashMap<PaymentHash, PendingInboundPayment>>,
1217
1218         /// The session_priv bytes and retry metadata of outbound payments which are pending resolution.
1219         /// The authoritative state of these HTLCs resides either within Channels or ChannelMonitors
1220         /// (if the channel has been force-closed), however we track them here to prevent duplicative
1221         /// PaymentSent/PaymentPathFailed events. Specifically, in the case of a duplicative
1222         /// update_fulfill_htlc message after a reconnect, we may "claim" a payment twice.
1223         /// Additionally, because ChannelMonitors are often not re-serialized after connecting block(s)
1224         /// which may generate a claim event, we may receive similar duplicate claim/fail MonitorEvents
1225         /// after reloading from disk while replaying blocks against ChannelMonitors.
1226         ///
1227         /// See `PendingOutboundPayment` documentation for more info.
1228         ///
1229         /// See `ChannelManager` struct-level documentation for lock order requirements.
1230         pending_outbound_payments: OutboundPayments,
1231
1232         /// SCID/SCID Alias -> forward infos. Key of 0 means payments received.
1233         ///
1234         /// Note that because we may have an SCID Alias as the key we can have two entries per channel,
1235         /// though in practice we probably won't be receiving HTLCs for a channel both via the alias
1236         /// and via the classic SCID.
1237         ///
1238         /// Note that no consistency guarantees are made about the existence of a channel with the
1239         /// `short_channel_id` here, nor the `short_channel_id` in the `PendingHTLCInfo`!
1240         ///
1241         /// See `ChannelManager` struct-level documentation for lock order requirements.
1242         #[cfg(test)]
1243         pub(super) forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1244         #[cfg(not(test))]
1245         forward_htlcs: Mutex<HashMap<u64, Vec<HTLCForwardInfo>>>,
1246         /// Storage for HTLCs that have been intercepted and bubbled up to the user. We hold them here
1247         /// until the user tells us what we should do with them.
1248         ///
1249         /// See `ChannelManager` struct-level documentation for lock order requirements.
1250         pending_intercepted_htlcs: Mutex<HashMap<InterceptId, PendingAddHTLCInfo>>,
1251
1252         /// The sets of payments which are claimable or currently being claimed. See
1253         /// [`ClaimablePayments`]' individual field docs for more info.
1254         ///
1255         /// See `ChannelManager` struct-level documentation for lock order requirements.
1256         claimable_payments: Mutex<ClaimablePayments>,
1257
1258         /// The set of outbound SCID aliases across all our channels, including unconfirmed channels
1259         /// and some closed channels which reached a usable state prior to being closed. This is used
1260         /// only to avoid duplicates, and is not persisted explicitly to disk, but rebuilt from the
1261         /// active channel list on load.
1262         ///
1263         /// See `ChannelManager` struct-level documentation for lock order requirements.
1264         outbound_scid_aliases: Mutex<HashSet<u64>>,
1265
1266         /// Channel funding outpoint -> `counterparty_node_id`.
1267         ///
1268         /// Note that this map should only be used for `MonitorEvent` handling, to be able to access
1269         /// the corresponding channel for the event, as we only have access to the `channel_id` during
1270         /// the handling of the events.
1271         ///
1272         /// Note that no consistency guarantees are made about the existence of a peer with the
1273         /// `counterparty_node_id` in our other maps.
1274         ///
1275         /// TODO:
1276         /// The `counterparty_node_id` isn't passed with `MonitorEvent`s currently. To pass it, we need
1277         /// to make `counterparty_node_id`'s a required field in `ChannelMonitor`s, which unfortunately
1278         /// would break backwards compatability.
1279         /// We should add `counterparty_node_id`s to `MonitorEvent`s, and eventually rely on it in the
1280         /// future. That would make this map redundant, as only the `ChannelManager::per_peer_state` is
1281         /// required to access the channel with the `counterparty_node_id`.
1282         ///
1283         /// See `ChannelManager` struct-level documentation for lock order requirements.
1284         #[cfg(not(test))]
1285         outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1286         #[cfg(test)]
1287         pub(crate) outpoint_to_peer: Mutex<HashMap<OutPoint, PublicKey>>,
1288
1289         /// SCIDs (and outbound SCID aliases) -> `counterparty_node_id`s and `channel_id`s.
1290         ///
1291         /// Outbound SCID aliases are added here once the channel is available for normal use, with
1292         /// SCIDs being added once the funding transaction is confirmed at the channel's required
1293         /// confirmation depth.
1294         ///
1295         /// Note that while this holds `counterparty_node_id`s and `channel_id`s, no consistency
1296         /// guarantees are made about the existence of a peer with the `counterparty_node_id` nor a
1297         /// channel with the `channel_id` in our other maps.
1298         ///
1299         /// See `ChannelManager` struct-level documentation for lock order requirements.
1300         #[cfg(test)]
1301         pub(super) short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1302         #[cfg(not(test))]
1303         short_to_chan_info: FairRwLock<HashMap<u64, (PublicKey, ChannelId)>>,
1304
1305         our_network_pubkey: PublicKey,
1306
1307         inbound_payment_key: inbound_payment::ExpandedKey,
1308
1309         /// LDK puts the [fake scids] that it generates into namespaces, to identify the type of an
1310         /// incoming payment. To make it harder for a third-party to identify the type of a payment,
1311         /// we encrypt the namespace identifier using these bytes.
1312         ///
1313         /// [fake scids]: crate::util::scid_utils::fake_scid
1314         fake_scid_rand_bytes: [u8; 32],
1315
1316         /// When we send payment probes, we generate the [`PaymentHash`] based on this cookie secret
1317         /// and a random [`PaymentId`]. This allows us to discern probes from real payments, without
1318         /// keeping additional state.
1319         probing_cookie_secret: [u8; 32],
1320
1321         /// The highest block timestamp we've seen, which is usually a good guess at the current time.
1322         /// Assuming most miners are generating blocks with reasonable timestamps, this shouldn't be
1323         /// very far in the past, and can only ever be up to two hours in the future.
1324         highest_seen_timestamp: AtomicUsize,
1325
1326         /// The bulk of our storage. Currently the `per_peer_state` stores our channels on a per-peer
1327         /// basis, as well as the peer's latest features.
1328         ///
1329         /// If we are connected to a peer we always at least have an entry here, even if no channels
1330         /// are currently open with that peer.
1331         ///
1332         /// Because adding or removing an entry is rare, we usually take an outer read lock and then
1333         /// operate on the inner value freely. This opens up for parallel per-peer operation for
1334         /// channels.
1335         ///
1336         /// Note that the same thread must never acquire two inner `PeerState` locks at the same time.
1337         ///
1338         /// See `ChannelManager` struct-level documentation for lock order requirements.
1339         #[cfg(not(any(test, feature = "_test_utils")))]
1340         per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1341         #[cfg(any(test, feature = "_test_utils"))]
1342         pub(super) per_peer_state: FairRwLock<HashMap<PublicKey, Mutex<PeerState<SP>>>>,
1343
1344         /// The set of events which we need to give to the user to handle. In some cases an event may
1345         /// require some further action after the user handles it (currently only blocking a monitor
1346         /// update from being handed to the user to ensure the included changes to the channel state
1347         /// are handled by the user before they're persisted durably to disk). In that case, the second
1348         /// element in the tuple is set to `Some` with further details of the action.
1349         ///
1350         /// Note that events MUST NOT be removed from pending_events after deserialization, as they
1351         /// could be in the middle of being processed without the direct mutex held.
1352         ///
1353         /// See `ChannelManager` struct-level documentation for lock order requirements.
1354         #[cfg(not(any(test, feature = "_test_utils")))]
1355         pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1356         #[cfg(any(test, feature = "_test_utils"))]
1357         pub(crate) pending_events: Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1358
1359         /// A simple atomic flag to ensure only one task at a time can be processing events asynchronously.
1360         pending_events_processor: AtomicBool,
1361
1362         /// If we are running during init (either directly during the deserialization method or in
1363         /// block connection methods which run after deserialization but before normal operation) we
1364         /// cannot provide the user with [`ChannelMonitorUpdate`]s through the normal update flow -
1365         /// prior to normal operation the user may not have loaded the [`ChannelMonitor`]s into their
1366         /// [`ChainMonitor`] and thus attempting to update it will fail or panic.
1367         ///
1368         /// Thus, we place them here to be handled as soon as possible once we are running normally.
1369         ///
1370         /// See `ChannelManager` struct-level documentation for lock order requirements.
1371         ///
1372         /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1373         pending_background_events: Mutex<Vec<BackgroundEvent>>,
1374         /// Used when we have to take a BIG lock to make sure everything is self-consistent.
1375         /// Essentially just when we're serializing ourselves out.
1376         /// Taken first everywhere where we are making changes before any other locks.
1377         /// When acquiring this lock in read mode, rather than acquiring it directly, call
1378         /// `PersistenceNotifierGuard::notify_on_drop(..)` and pass the lock to it, to ensure the
1379         /// Notifier the lock contains sends out a notification when the lock is released.
1380         total_consistency_lock: RwLock<()>,
1381         /// Tracks the progress of channels going through batch funding by whether funding_signed was
1382         /// received and the monitor has been persisted.
1383         ///
1384         /// This information does not need to be persisted as funding nodes can forget
1385         /// unfunded channels upon disconnection.
1386         funding_batch_states: Mutex<BTreeMap<Txid, Vec<(ChannelId, PublicKey, bool)>>>,
1387
1388         background_events_processed_since_startup: AtomicBool,
1389
1390         event_persist_notifier: Notifier,
1391         needs_persist_flag: AtomicBool,
1392
1393         pending_offers_messages: Mutex<Vec<PendingOnionMessage<OffersMessage>>>,
1394
1395         /// Tracks the message events that are to be broadcasted when we are connected to some peer.
1396         pending_broadcast_messages: Mutex<Vec<MessageSendEvent>>,
1397
1398         entropy_source: ES,
1399         node_signer: NS,
1400         signer_provider: SP,
1401
1402         logger: L,
1403 }
1404
1405 /// Chain-related parameters used to construct a new `ChannelManager`.
1406 ///
1407 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1408 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1409 /// are not needed when deserializing a previously constructed `ChannelManager`.
1410 #[derive(Clone, Copy, PartialEq)]
1411 pub struct ChainParameters {
1412         /// The network for determining the `chain_hash` in Lightning messages.
1413         pub network: Network,
1414
1415         /// The hash and height of the latest block successfully connected.
1416         ///
1417         /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1418         pub best_block: BestBlock,
1419 }
1420
1421 #[derive(Copy, Clone, PartialEq)]
1422 #[must_use]
1423 enum NotifyOption {
1424         DoPersist,
1425         SkipPersistHandleEvents,
1426         SkipPersistNoEvents,
1427 }
1428
1429 /// Whenever we release the `ChannelManager`'s `total_consistency_lock`, from read mode, it is
1430 /// desirable to notify any listeners on `await_persistable_update_timeout`/
1431 /// `await_persistable_update` when new updates are available for persistence. Therefore, this
1432 /// struct is responsible for locking the total consistency lock and, upon going out of scope,
1433 /// sending the aforementioned notification (since the lock being released indicates that the
1434 /// updates are ready for persistence).
1435 ///
1436 /// We allow callers to either always notify by constructing with `notify_on_drop` or choose to
1437 /// notify or not based on whether relevant changes have been made, providing a closure to
1438 /// `optionally_notify` which returns a `NotifyOption`.
1439 struct PersistenceNotifierGuard<'a, F: FnMut() -> NotifyOption> {
1440         event_persist_notifier: &'a Notifier,
1441         needs_persist_flag: &'a AtomicBool,
1442         should_persist: F,
1443         // We hold onto this result so the lock doesn't get released immediately.
1444         _read_guard: RwLockReadGuard<'a, ()>,
1445 }
1446
1447 impl<'a> PersistenceNotifierGuard<'a, fn() -> NotifyOption> { // We don't care what the concrete F is here, it's unused
1448         /// Notifies any waiters and indicates that we need to persist, in addition to possibly having
1449         /// events to handle.
1450         ///
1451         /// This must always be called if the changes included a `ChannelMonitorUpdate`, as well as in
1452         /// other cases where losing the changes on restart may result in a force-close or otherwise
1453         /// isn't ideal.
1454         fn notify_on_drop<C: AChannelManager>(cm: &'a C) -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1455                 Self::optionally_notify(cm, || -> NotifyOption { NotifyOption::DoPersist })
1456         }
1457
1458         fn optionally_notify<F: FnMut() -> NotifyOption, C: AChannelManager>(cm: &'a C, mut persist_check: F)
1459         -> PersistenceNotifierGuard<'a, impl FnMut() -> NotifyOption> {
1460                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1461                 let force_notify = cm.get_cm().process_background_events();
1462
1463                 PersistenceNotifierGuard {
1464                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1465                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1466                         should_persist: move || {
1467                                 // Pick the "most" action between `persist_check` and the background events
1468                                 // processing and return that.
1469                                 let notify = persist_check();
1470                                 match (notify, force_notify) {
1471                                         (NotifyOption::DoPersist, _) => NotifyOption::DoPersist,
1472                                         (_, NotifyOption::DoPersist) => NotifyOption::DoPersist,
1473                                         (NotifyOption::SkipPersistHandleEvents, _) => NotifyOption::SkipPersistHandleEvents,
1474                                         (_, NotifyOption::SkipPersistHandleEvents) => NotifyOption::SkipPersistHandleEvents,
1475                                         _ => NotifyOption::SkipPersistNoEvents,
1476                                 }
1477                         },
1478                         _read_guard: read_guard,
1479                 }
1480         }
1481
1482         /// Note that if any [`ChannelMonitorUpdate`]s are possibly generated,
1483         /// [`ChannelManager::process_background_events`] MUST be called first (or
1484         /// [`Self::optionally_notify`] used).
1485         fn optionally_notify_skipping_background_events<F: Fn() -> NotifyOption, C: AChannelManager>
1486         (cm: &'a C, persist_check: F) -> PersistenceNotifierGuard<'a, F> {
1487                 let read_guard = cm.get_cm().total_consistency_lock.read().unwrap();
1488
1489                 PersistenceNotifierGuard {
1490                         event_persist_notifier: &cm.get_cm().event_persist_notifier,
1491                         needs_persist_flag: &cm.get_cm().needs_persist_flag,
1492                         should_persist: persist_check,
1493                         _read_guard: read_guard,
1494                 }
1495         }
1496 }
1497
1498 impl<'a, F: FnMut() -> NotifyOption> Drop for PersistenceNotifierGuard<'a, F> {
1499         fn drop(&mut self) {
1500                 match (self.should_persist)() {
1501                         NotifyOption::DoPersist => {
1502                                 self.needs_persist_flag.store(true, Ordering::Release);
1503                                 self.event_persist_notifier.notify()
1504                         },
1505                         NotifyOption::SkipPersistHandleEvents =>
1506                                 self.event_persist_notifier.notify(),
1507                         NotifyOption::SkipPersistNoEvents => {},
1508                 }
1509         }
1510 }
1511
1512 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1513 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1514 ///
1515 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1516 ///
1517 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1518 pub const BREAKDOWN_TIMEOUT: u16 = 6 * 24;
1519 /// The amount of time in blocks we're willing to wait to claim money back to us. This matches
1520 /// the maximum required amount in lnd as of March 2021.
1521 pub(crate) const MAX_LOCAL_BREAKDOWN_TIMEOUT: u16 = 2 * 6 * 24 * 7;
1522
1523 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1524 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1525 ///
1526 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1527 ///
1528 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1529 // This should always be a few blocks greater than channelmonitor::CLTV_CLAIM_BUFFER,
1530 // i.e. the node we forwarded the payment on to should always have enough room to reliably time out
1531 // the HTLC via a full update_fail_htlc/commitment_signed dance before we hit the
1532 // CLTV_CLAIM_BUFFER point (we static assert that it's at least 3 blocks more).
1533 pub const MIN_CLTV_EXPIRY_DELTA: u16 = 6*7;
1534 // This should be long enough to allow a payment path drawn across multiple routing hops with substantial
1535 // `cltv_expiry_delta`. Indeed, the length of those values is the reaction delay offered to a routing node
1536 // in case of HTLC on-chain settlement. While appearing less competitive, a node operator could decide to
1537 // scale them up to suit its security policy. At the network-level, we shouldn't constrain them too much,
1538 // while avoiding to introduce a DoS vector. Further, a low CTLV_FAR_FAR_AWAY could be a source of
1539 // routing failure for any HTLC sender picking up an LDK node among the first hops.
1540 pub(super) const CLTV_FAR_FAR_AWAY: u32 = 14 * 24 * 6;
1541
1542 /// Minimum CLTV difference between the current block height and received inbound payments.
1543 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1544 /// this value.
1545 // Note that we fail if exactly HTLC_FAIL_BACK_BUFFER + 1 was used, so we need to add one for
1546 // any payments to succeed. Further, we don't want payments to fail if a block was found while
1547 // a payment was being routed, so we add an extra block to be safe.
1548 pub const MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = HTLC_FAIL_BACK_BUFFER as u16 + 3;
1549
1550 // Check that our CLTV_EXPIRY is at least CLTV_CLAIM_BUFFER + ANTI_REORG_DELAY + LATENCY_GRACE_PERIOD_BLOCKS,
1551 // ie that if the next-hop peer fails the HTLC within
1552 // LATENCY_GRACE_PERIOD_BLOCKS then we'll still have CLTV_CLAIM_BUFFER left to timeout it onchain,
1553 // then waiting ANTI_REORG_DELAY to be reorg-safe on the outbound HLTC and
1554 // failing the corresponding htlc backward, and us now seeing the last block of ANTI_REORG_DELAY before
1555 // LATENCY_GRACE_PERIOD_BLOCKS.
1556 #[allow(dead_code)]
1557 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;
1558
1559 // Check for ability of an attacker to make us fail on-chain by delaying an HTLC claim. See
1560 // ChannelMonitor::should_broadcast_holder_commitment_txn for a description of why this is needed.
1561 #[allow(dead_code)]
1562 const CHECK_CLTV_EXPIRY_SANITY_2: u32 = MIN_CLTV_EXPIRY_DELTA as u32 - LATENCY_GRACE_PERIOD_BLOCKS - 2*CLTV_CLAIM_BUFFER;
1563
1564 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until expiry of incomplete MPPs
1565 pub(crate) const MPP_TIMEOUT_TICKS: u8 = 3;
1566
1567 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is disconnected
1568 /// until we mark the channel disabled and gossip the update.
1569 pub(crate) const DISABLE_GOSSIP_TICKS: u8 = 10;
1570
1571 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] where a peer is connected until
1572 /// we mark the channel enabled and gossip the update.
1573 pub(crate) const ENABLE_GOSSIP_TICKS: u8 = 5;
1574
1575 /// The maximum number of unfunded channels we can have per-peer before we start rejecting new
1576 /// (inbound) ones. The number of peers with unfunded channels is limited separately in
1577 /// [`MAX_UNFUNDED_CHANNEL_PEERS`].
1578 const MAX_UNFUNDED_CHANS_PER_PEER: usize = 4;
1579
1580 /// The maximum number of peers from which we will allow pending unfunded channels. Once we reach
1581 /// this many peers we reject new (inbound) channels from peers with which we don't have a channel.
1582 const MAX_UNFUNDED_CHANNEL_PEERS: usize = 50;
1583
1584 /// The maximum number of peers which we do not have a (funded) channel with. Once we reach this
1585 /// many peers we reject new (inbound) connections.
1586 const MAX_NO_CHANNEL_PEERS: usize = 250;
1587
1588 /// Information needed for constructing an invoice route hint for this channel.
1589 #[derive(Clone, Debug, PartialEq)]
1590 pub struct CounterpartyForwardingInfo {
1591         /// Base routing fee in millisatoshis.
1592         pub fee_base_msat: u32,
1593         /// Amount in millionths of a satoshi the channel will charge per transferred satoshi.
1594         pub fee_proportional_millionths: u32,
1595         /// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart,
1596         /// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s
1597         /// `cltv_expiry_delta` for more details.
1598         pub cltv_expiry_delta: u16,
1599 }
1600
1601 /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`]
1602 /// to better separate parameters.
1603 #[derive(Clone, Debug, PartialEq)]
1604 pub struct ChannelCounterparty {
1605         /// The node_id of our counterparty
1606         pub node_id: PublicKey,
1607         /// The Features the channel counterparty provided upon last connection.
1608         /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
1609         /// many routing-relevant features are present in the init context.
1610         pub features: InitFeatures,
1611         /// The value, in satoshis, that must always be held in the channel for our counterparty. This
1612         /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
1613         /// claiming at least this value on chain.
1614         ///
1615         /// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
1616         ///
1617         /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
1618         pub unspendable_punishment_reserve: u64,
1619         /// Information on the fees and requirements that the counterparty requires when forwarding
1620         /// payments to us through this channel.
1621         pub forwarding_info: Option<CounterpartyForwardingInfo>,
1622         /// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field
1623         /// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message
1624         /// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107.
1625         pub outbound_htlc_minimum_msat: Option<u64>,
1626         /// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
1627         pub outbound_htlc_maximum_msat: Option<u64>,
1628 }
1629
1630 /// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`]
1631 #[derive(Clone, Debug, PartialEq)]
1632 pub struct ChannelDetails {
1633         /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
1634         /// thereafter this is the txid of the funding transaction xor the funding transaction output).
1635         /// Note that this means this value is *not* persistent - it can change once during the
1636         /// lifetime of the channel.
1637         pub channel_id: ChannelId,
1638         /// Parameters which apply to our counterparty. See individual fields for more information.
1639         pub counterparty: ChannelCounterparty,
1640         /// The Channel's funding transaction output, if we've negotiated the funding transaction with
1641         /// our counterparty already.
1642         ///
1643         /// Note that, if this has been set, `channel_id` for V1-established channels will be equivalent to
1644         /// `ChannelId::v1_from_funding_outpoint(funding_txo.unwrap())`.
1645         pub funding_txo: Option<OutPoint>,
1646         /// The features which this channel operates with. See individual features for more info.
1647         ///
1648         /// `None` until negotiation completes and the channel type is finalized.
1649         pub channel_type: Option<ChannelTypeFeatures>,
1650         /// The position of the funding transaction in the chain. None if the funding transaction has
1651         /// not yet been confirmed and the channel fully opened.
1652         ///
1653         /// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound
1654         /// payments instead of this. See [`get_inbound_payment_scid`].
1655         ///
1656         /// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
1657         /// be used in place of this in outbound routes. See [`get_outbound_payment_scid`].
1658         ///
1659         /// [`inbound_scid_alias`]: Self::inbound_scid_alias
1660         /// [`outbound_scid_alias`]: Self::outbound_scid_alias
1661         /// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid
1662         /// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid
1663         /// [`confirmations_required`]: Self::confirmations_required
1664         pub short_channel_id: Option<u64>,
1665         /// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
1666         /// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
1667         /// the channel has not yet been confirmed (as long as [`confirmations_required`] is
1668         /// `Some(0)`).
1669         ///
1670         /// This will be `None` as long as the channel is not available for routing outbound payments.
1671         ///
1672         /// [`short_channel_id`]: Self::short_channel_id
1673         /// [`confirmations_required`]: Self::confirmations_required
1674         pub outbound_scid_alias: Option<u64>,
1675         /// An optional [`short_channel_id`] alias for this channel, randomly generated by our
1676         /// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
1677         /// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
1678         /// when they see a payment to be routed to us.
1679         ///
1680         /// Our counterparty may choose to rotate this value at any time, though will always recognize
1681         /// previous values for inbound payment forwarding.
1682         ///
1683         /// [`short_channel_id`]: Self::short_channel_id
1684         pub inbound_scid_alias: Option<u64>,
1685         /// The value, in satoshis, of this channel as appears in the funding output
1686         pub channel_value_satoshis: u64,
1687         /// The value, in satoshis, that must always be held in the channel for us. This value ensures
1688         /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least
1689         /// this value on chain.
1690         ///
1691         /// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
1692         ///
1693         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1694         ///
1695         /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat
1696         pub unspendable_punishment_reserve: Option<u64>,
1697         /// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound
1698         /// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if
1699         /// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise
1700         /// `user_channel_id` will be randomized for an inbound channel.  This may be zero for objects
1701         /// serialized with LDK versions prior to 0.0.113.
1702         ///
1703         /// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel
1704         /// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel
1705         /// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels
1706         pub user_channel_id: u128,
1707         /// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
1708         /// which is applied to commitment and HTLC transactions.
1709         ///
1710         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.115.
1711         pub feerate_sat_per_1000_weight: Option<u32>,
1712         /// Our total balance.  This is the amount we would get if we close the channel.
1713         /// This value is not exact. Due to various in-flight changes and feerate changes, exactly this
1714         /// amount is not likely to be recoverable on close.
1715         ///
1716         /// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose
1717         /// balance is not available for inclusion in new outbound HTLCs). This further does not include
1718         /// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
1719         /// This does not consider any on-chain fees.
1720         ///
1721         /// See also [`ChannelDetails::outbound_capacity_msat`]
1722         pub balance_msat: u64,
1723         /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
1724         /// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1725         /// available for inclusion in new outbound HTLCs). This further does not include any pending
1726         /// outgoing HTLCs which are awaiting some other resolution to be sent.
1727         ///
1728         /// See also [`ChannelDetails::balance_msat`]
1729         ///
1730         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1731         /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we
1732         /// should be able to spend nearly this amount.
1733         pub outbound_capacity_msat: u64,
1734         /// The available outbound capacity for sending a single HTLC to the remote peer. This is
1735         /// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
1736         /// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
1737         /// to use a limit as close as possible to the HTLC limit we can currently send.
1738         ///
1739         /// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`],
1740         /// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`].
1741         pub next_outbound_htlc_limit_msat: u64,
1742         /// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
1743         /// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
1744         /// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
1745         /// route which is valid.
1746         pub next_outbound_htlc_minimum_msat: u64,
1747         /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
1748         /// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not
1749         /// available for inclusion in new inbound HTLCs).
1750         /// Note that there are some corner cases not fully handled here, so the actual available
1751         /// inbound capacity may be slightly higher than this.
1752         ///
1753         /// This value is not exact. Due to various in-flight changes, feerate changes, and our
1754         /// counterparty's conflict-avoidance policy, exactly this amount is not likely to be spendable.
1755         /// However, our counterparty should be able to spend nearly this amount.
1756         pub inbound_capacity_msat: u64,
1757         /// The number of required confirmations on the funding transaction before the funding will be
1758         /// considered "locked". This number is selected by the channel fundee (i.e. us if
1759         /// [`is_outbound`] is *not* set), and can be selected for inbound channels with
1760         /// [`ChannelHandshakeConfig::minimum_depth`] or limited for outbound channels with
1761         /// [`ChannelHandshakeLimits::max_minimum_depth`].
1762         ///
1763         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1764         ///
1765         /// [`is_outbound`]: ChannelDetails::is_outbound
1766         /// [`ChannelHandshakeConfig::minimum_depth`]: crate::util::config::ChannelHandshakeConfig::minimum_depth
1767         /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth
1768         pub confirmations_required: Option<u32>,
1769         /// The current number of confirmations on the funding transaction.
1770         ///
1771         /// This value will be `None` for objects serialized with LDK versions prior to 0.0.113.
1772         pub confirmations: Option<u32>,
1773         /// The number of blocks (after our commitment transaction confirms) that we will need to wait
1774         /// until we can claim our funds after we force-close the channel. During this time our
1775         /// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
1776         /// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
1777         /// time to claim our non-HTLC-encumbered funds.
1778         ///
1779         /// This value will be `None` for outbound channels until the counterparty accepts the channel.
1780         pub force_close_spend_delay: Option<u16>,
1781         /// True if the channel was initiated (and thus funded) by us.
1782         pub is_outbound: bool,
1783         /// True if the channel is confirmed, channel_ready messages have been exchanged, and the
1784         /// channel is not currently being shut down. `channel_ready` message exchange implies the
1785         /// required confirmation count has been reached (and we were connected to the peer at some
1786         /// point after the funding transaction received enough confirmations). The required
1787         /// confirmation count is provided in [`confirmations_required`].
1788         ///
1789         /// [`confirmations_required`]: ChannelDetails::confirmations_required
1790         pub is_channel_ready: bool,
1791         /// The stage of the channel's shutdown.
1792         /// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116.
1793         pub channel_shutdown_state: Option<ChannelShutdownState>,
1794         /// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b)
1795         /// the peer is connected, and (c) the channel is not currently negotiating a shutdown.
1796         ///
1797         /// This is a strict superset of `is_channel_ready`.
1798         pub is_usable: bool,
1799         /// True if this channel is (or will be) publicly-announced.
1800         pub is_public: bool,
1801         /// The smallest value HTLC (in msat) we will accept, for this channel. This field
1802         /// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107
1803         pub inbound_htlc_minimum_msat: Option<u64>,
1804         /// The largest value HTLC (in msat) we currently will accept, for this channel.
1805         pub inbound_htlc_maximum_msat: Option<u64>,
1806         /// Set of configurable parameters that affect channel operation.
1807         ///
1808         /// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109.
1809         pub config: Option<ChannelConfig>,
1810 }
1811
1812 impl ChannelDetails {
1813         /// Gets the current SCID which should be used to identify this channel for inbound payments.
1814         /// This should be used for providing invoice hints or in any other context where our
1815         /// counterparty will forward a payment to us.
1816         ///
1817         /// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the
1818         /// [`ChannelDetails::short_channel_id`]. See those for more information.
1819         pub fn get_inbound_payment_scid(&self) -> Option<u64> {
1820                 self.inbound_scid_alias.or(self.short_channel_id)
1821         }
1822
1823         /// Gets the current SCID which should be used to identify this channel for outbound payments.
1824         /// This should be used in [`Route`]s to describe the first hop or in other contexts where
1825         /// we're sending or forwarding a payment outbound over this channel.
1826         ///
1827         /// This is either the [`ChannelDetails::short_channel_id`], if set, or the
1828         /// [`ChannelDetails::outbound_scid_alias`]. See those for more information.
1829         pub fn get_outbound_payment_scid(&self) -> Option<u64> {
1830                 self.short_channel_id.or(self.outbound_scid_alias)
1831         }
1832
1833         fn from_channel_context<SP: Deref, F: Deref>(
1834                 context: &ChannelContext<SP>, best_block_height: u32, latest_features: InitFeatures,
1835                 fee_estimator: &LowerBoundedFeeEstimator<F>
1836         ) -> Self
1837         where
1838                 SP::Target: SignerProvider,
1839                 F::Target: FeeEstimator
1840         {
1841                 let balance = context.get_available_balances(fee_estimator);
1842                 let (to_remote_reserve_satoshis, to_self_reserve_satoshis) =
1843                         context.get_holder_counterparty_selected_channel_reserve_satoshis();
1844                 ChannelDetails {
1845                         channel_id: context.channel_id(),
1846                         counterparty: ChannelCounterparty {
1847                                 node_id: context.get_counterparty_node_id(),
1848                                 features: latest_features,
1849                                 unspendable_punishment_reserve: to_remote_reserve_satoshis,
1850                                 forwarding_info: context.counterparty_forwarding_info(),
1851                                 // Ensures that we have actually received the `htlc_minimum_msat` value
1852                                 // from the counterparty through the `OpenChannel` or `AcceptChannel`
1853                                 // message (as they are always the first message from the counterparty).
1854                                 // Else `Channel::get_counterparty_htlc_minimum_msat` could return the
1855                                 // default `0` value set by `Channel::new_outbound`.
1856                                 outbound_htlc_minimum_msat: if context.have_received_message() {
1857                                         Some(context.get_counterparty_htlc_minimum_msat()) } else { None },
1858                                 outbound_htlc_maximum_msat: context.get_counterparty_htlc_maximum_msat(),
1859                         },
1860                         funding_txo: context.get_funding_txo(),
1861                         // Note that accept_channel (or open_channel) is always the first message, so
1862                         // `have_received_message` indicates that type negotiation has completed.
1863                         channel_type: if context.have_received_message() { Some(context.get_channel_type().clone()) } else { None },
1864                         short_channel_id: context.get_short_channel_id(),
1865                         outbound_scid_alias: if context.is_usable() { Some(context.outbound_scid_alias()) } else { None },
1866                         inbound_scid_alias: context.latest_inbound_scid_alias(),
1867                         channel_value_satoshis: context.get_value_satoshis(),
1868                         feerate_sat_per_1000_weight: Some(context.get_feerate_sat_per_1000_weight()),
1869                         unspendable_punishment_reserve: to_self_reserve_satoshis,
1870                         balance_msat: balance.balance_msat,
1871                         inbound_capacity_msat: balance.inbound_capacity_msat,
1872                         outbound_capacity_msat: balance.outbound_capacity_msat,
1873                         next_outbound_htlc_limit_msat: balance.next_outbound_htlc_limit_msat,
1874                         next_outbound_htlc_minimum_msat: balance.next_outbound_htlc_minimum_msat,
1875                         user_channel_id: context.get_user_id(),
1876                         confirmations_required: context.minimum_depth(),
1877                         confirmations: Some(context.get_funding_tx_confirmations(best_block_height)),
1878                         force_close_spend_delay: context.get_counterparty_selected_contest_delay(),
1879                         is_outbound: context.is_outbound(),
1880                         is_channel_ready: context.is_usable(),
1881                         is_usable: context.is_live(),
1882                         is_public: context.should_announce(),
1883                         inbound_htlc_minimum_msat: Some(context.get_holder_htlc_minimum_msat()),
1884                         inbound_htlc_maximum_msat: context.get_holder_htlc_maximum_msat(),
1885                         config: Some(context.config()),
1886                         channel_shutdown_state: Some(context.shutdown_state()),
1887                 }
1888         }
1889 }
1890
1891 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1892 /// Further information on the details of the channel shutdown.
1893 /// Upon channels being forced closed (i.e. commitment transaction confirmation detected
1894 /// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or
1895 /// the channel will be removed shortly.
1896 /// Also note, that in normal operation, peers could disconnect at any of these states
1897 /// and require peer re-connection before making progress onto other states
1898 pub enum ChannelShutdownState {
1899         /// Channel has not sent or received a shutdown message.
1900         NotShuttingDown,
1901         /// Local node has sent a shutdown message for this channel.
1902         ShutdownInitiated,
1903         /// Shutdown message exchanges have concluded and the channels are in the midst of
1904         /// resolving all existing open HTLCs before closing can continue.
1905         ResolvingHTLCs,
1906         /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates.
1907         NegotiatingClosingFee,
1908         /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about
1909         /// to drop the channel.
1910         ShutdownComplete,
1911 }
1912
1913 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1914 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1915 #[derive(Debug, PartialEq)]
1916 pub enum RecentPaymentDetails {
1917         /// When an invoice was requested and thus a payment has not yet been sent.
1918         AwaitingInvoice {
1919                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1920                 /// a payment and ensure idempotency in LDK.
1921                 payment_id: PaymentId,
1922         },
1923         /// When a payment is still being sent and awaiting successful delivery.
1924         Pending {
1925                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1926                 /// a payment and ensure idempotency in LDK.
1927                 payment_id: PaymentId,
1928                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1929                 /// abandoned.
1930                 payment_hash: PaymentHash,
1931                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1932                 /// not just the amount currently inflight.
1933                 total_msat: u64,
1934         },
1935         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1936         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1937         /// payment is removed from tracking.
1938         Fulfilled {
1939                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1940                 /// a payment and ensure idempotency in LDK.
1941                 payment_id: PaymentId,
1942                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1943                 /// made before LDK version 0.0.104.
1944                 payment_hash: Option<PaymentHash>,
1945         },
1946         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1947         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1948         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1949         Abandoned {
1950                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1951                 /// a payment and ensure idempotency in LDK.
1952                 payment_id: PaymentId,
1953                 /// Hash of the payment that we have given up trying to send.
1954                 payment_hash: PaymentHash,
1955         },
1956 }
1957
1958 /// Route hints used in constructing invoices for [phantom node payents].
1959 ///
1960 /// [phantom node payments]: crate::sign::PhantomKeysManager
1961 #[derive(Clone)]
1962 pub struct PhantomRouteHints {
1963         /// The list of channels to be included in the invoice route hints.
1964         pub channels: Vec<ChannelDetails>,
1965         /// A fake scid used for representing the phantom node's fake channel in generating the invoice
1966         /// route hints.
1967         pub phantom_scid: u64,
1968         /// The pubkey of the real backing node that would ultimately receive the payment.
1969         pub real_node_pubkey: PublicKey,
1970 }
1971
1972 macro_rules! handle_error {
1973         ($self: ident, $internal: expr, $counterparty_node_id: expr) => { {
1974                 // In testing, ensure there are no deadlocks where the lock is already held upon
1975                 // entering the macro.
1976                 debug_assert_ne!($self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
1977                 debug_assert_ne!($self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
1978
1979                 match $internal {
1980                         Ok(msg) => Ok(msg),
1981                         Err(MsgHandleErrInternal { err, shutdown_finish, .. }) => {
1982                                 let mut msg_event = None;
1983
1984                                 if let Some((shutdown_res, update_option)) = shutdown_finish {
1985                                         let counterparty_node_id = shutdown_res.counterparty_node_id;
1986                                         let channel_id = shutdown_res.channel_id;
1987                                         let logger = WithContext::from(
1988                                                 &$self.logger, Some(counterparty_node_id), Some(channel_id),
1989                                         );
1990                                         log_error!(logger, "Force-closing channel: {}", err.err);
1991
1992                                         $self.finish_close_channel(shutdown_res);
1993                                         if let Some(update) = update_option {
1994                                                 let mut pending_broadcast_messages = $self.pending_broadcast_messages.lock().unwrap();
1995                                                 pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
1996                                                         msg: update
1997                                                 });
1998                                         }
1999                                 } else {
2000                                         log_error!($self.logger, "Got non-closing error: {}", err.err);
2001                                 }
2002
2003                                 if let msgs::ErrorAction::IgnoreError = err.action {
2004                                 } else {
2005                                         msg_event = Some(events::MessageSendEvent::HandleError {
2006                                                 node_id: $counterparty_node_id,
2007                                                 action: err.action.clone()
2008                                         });
2009                                 }
2010
2011                                 if let Some(msg_event) = msg_event {
2012                                         let per_peer_state = $self.per_peer_state.read().unwrap();
2013                                         if let Some(peer_state_mutex) = per_peer_state.get(&$counterparty_node_id) {
2014                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2015                                                 peer_state.pending_msg_events.push(msg_event);
2016                                         }
2017                                 }
2018
2019                                 // Return error in case higher-API need one
2020                                 Err(err)
2021                         },
2022                 }
2023         } };
2024 }
2025
2026 macro_rules! update_maps_on_chan_removal {
2027         ($self: expr, $channel_context: expr) => {{
2028                 if let Some(outpoint) = $channel_context.get_funding_txo() {
2029                         $self.outpoint_to_peer.lock().unwrap().remove(&outpoint);
2030                 }
2031                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2032                 if let Some(short_id) = $channel_context.get_short_channel_id() {
2033                         short_to_chan_info.remove(&short_id);
2034                 } else {
2035                         // If the channel was never confirmed on-chain prior to its closure, remove the
2036                         // outbound SCID alias we used for it from the collision-prevention set. While we
2037                         // generally want to avoid ever re-using an outbound SCID alias across all channels, we
2038                         // also don't want a counterparty to be able to trivially cause a memory leak by simply
2039                         // opening a million channels with us which are closed before we ever reach the funding
2040                         // stage.
2041                         let alias_removed = $self.outbound_scid_aliases.lock().unwrap().remove(&$channel_context.outbound_scid_alias());
2042                         debug_assert!(alias_removed);
2043                 }
2044                 short_to_chan_info.remove(&$channel_context.outbound_scid_alias());
2045         }}
2046 }
2047
2048 /// Returns (boolean indicating if we should remove the Channel object from memory, a mapped error)
2049 macro_rules! convert_chan_phase_err {
2050         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, MANUAL_CHANNEL_UPDATE, $channel_update: expr) => {
2051                 match $err {
2052                         ChannelError::Warn(msg) => {
2053                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(msg), *$channel_id))
2054                         },
2055                         ChannelError::Ignore(msg) => {
2056                                 (false, MsgHandleErrInternal::from_chan_no_close(ChannelError::Ignore(msg), *$channel_id))
2057                         },
2058                         ChannelError::Close(msg) => {
2059                                 let logger = WithChannelContext::from(&$self.logger, &$channel.context);
2060                                 log_error!(logger, "Closing channel {} due to close-required error: {}", $channel_id, msg);
2061                                 update_maps_on_chan_removal!($self, $channel.context);
2062                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
2063                                 let shutdown_res = $channel.context.force_shutdown(true, reason);
2064                                 let err =
2065                                         MsgHandleErrInternal::from_finish_shutdown(msg, *$channel_id, shutdown_res, $channel_update);
2066                                 (true, err)
2067                         },
2068                 }
2069         };
2070         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, FUNDED_CHANNEL) => {
2071                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, { $self.get_channel_update_for_broadcast($channel).ok() })
2072         };
2073         ($self: ident, $err: expr, $channel: expr, $channel_id: expr, UNFUNDED_CHANNEL) => {
2074                 convert_chan_phase_err!($self, $err, $channel, $channel_id, MANUAL_CHANNEL_UPDATE, None)
2075         };
2076         ($self: ident, $err: expr, $channel_phase: expr, $channel_id: expr) => {
2077                 match $channel_phase {
2078                         ChannelPhase::Funded(channel) => {
2079                                 convert_chan_phase_err!($self, $err, channel, $channel_id, FUNDED_CHANNEL)
2080                         },
2081                         ChannelPhase::UnfundedOutboundV1(channel) => {
2082                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2083                         },
2084                         ChannelPhase::UnfundedInboundV1(channel) => {
2085                                 convert_chan_phase_err!($self, $err, channel, $channel_id, UNFUNDED_CHANNEL)
2086                         },
2087                 }
2088         };
2089 }
2090
2091 macro_rules! break_chan_phase_entry {
2092         ($self: ident, $res: expr, $entry: expr) => {
2093                 match $res {
2094                         Ok(res) => res,
2095                         Err(e) => {
2096                                 let key = *$entry.key();
2097                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2098                                 if drop {
2099                                         $entry.remove_entry();
2100                                 }
2101                                 break Err(res);
2102                         }
2103                 }
2104         }
2105 }
2106
2107 macro_rules! try_chan_phase_entry {
2108         ($self: ident, $res: expr, $entry: expr) => {
2109                 match $res {
2110                         Ok(res) => res,
2111                         Err(e) => {
2112                                 let key = *$entry.key();
2113                                 let (drop, res) = convert_chan_phase_err!($self, e, $entry.get_mut(), &key);
2114                                 if drop {
2115                                         $entry.remove_entry();
2116                                 }
2117                                 return Err(res);
2118                         }
2119                 }
2120         }
2121 }
2122
2123 macro_rules! remove_channel_phase {
2124         ($self: expr, $entry: expr) => {
2125                 {
2126                         let channel = $entry.remove_entry().1;
2127                         update_maps_on_chan_removal!($self, &channel.context());
2128                         channel
2129                 }
2130         }
2131 }
2132
2133 macro_rules! send_channel_ready {
2134         ($self: ident, $pending_msg_events: expr, $channel: expr, $channel_ready_msg: expr) => {{
2135                 $pending_msg_events.push(events::MessageSendEvent::SendChannelReady {
2136                         node_id: $channel.context.get_counterparty_node_id(),
2137                         msg: $channel_ready_msg,
2138                 });
2139                 // Note that we may send a `channel_ready` multiple times for a channel if we reconnect, so
2140                 // we allow collisions, but we shouldn't ever be updating the channel ID pointed to.
2141                 let mut short_to_chan_info = $self.short_to_chan_info.write().unwrap();
2142                 let outbound_alias_insert = short_to_chan_info.insert($channel.context.outbound_scid_alias(), ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2143                 assert!(outbound_alias_insert.is_none() || outbound_alias_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2144                         "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2145                 if let Some(real_scid) = $channel.context.get_short_channel_id() {
2146                         let scid_insert = short_to_chan_info.insert(real_scid, ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()));
2147                         assert!(scid_insert.is_none() || scid_insert.unwrap() == ($channel.context.get_counterparty_node_id(), $channel.context.channel_id()),
2148                                 "SCIDs should never collide - ensure you weren't behind the chain tip by a full month when creating channels");
2149                 }
2150         }}
2151 }
2152
2153 macro_rules! emit_channel_pending_event {
2154         ($locked_events: expr, $channel: expr) => {
2155                 if $channel.context.should_emit_channel_pending_event() {
2156                         $locked_events.push_back((events::Event::ChannelPending {
2157                                 channel_id: $channel.context.channel_id(),
2158                                 former_temporary_channel_id: $channel.context.temporary_channel_id(),
2159                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2160                                 user_channel_id: $channel.context.get_user_id(),
2161                                 funding_txo: $channel.context.get_funding_txo().unwrap().into_bitcoin_outpoint(),
2162                         }, None));
2163                         $channel.context.set_channel_pending_event_emitted();
2164                 }
2165         }
2166 }
2167
2168 macro_rules! emit_channel_ready_event {
2169         ($locked_events: expr, $channel: expr) => {
2170                 if $channel.context.should_emit_channel_ready_event() {
2171                         debug_assert!($channel.context.channel_pending_event_emitted());
2172                         $locked_events.push_back((events::Event::ChannelReady {
2173                                 channel_id: $channel.context.channel_id(),
2174                                 user_channel_id: $channel.context.get_user_id(),
2175                                 counterparty_node_id: $channel.context.get_counterparty_node_id(),
2176                                 channel_type: $channel.context.get_channel_type().clone(),
2177                         }, None));
2178                         $channel.context.set_channel_ready_event_emitted();
2179                 }
2180         }
2181 }
2182
2183 macro_rules! handle_monitor_update_completion {
2184         ($self: ident, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2185                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2186                 let mut updates = $chan.monitor_updating_restored(&&logger,
2187                         &$self.node_signer, $self.chain_hash, &$self.default_configuration,
2188                         $self.best_block.read().unwrap().height());
2189                 let counterparty_node_id = $chan.context.get_counterparty_node_id();
2190                 let channel_update = if updates.channel_ready.is_some() && $chan.context.is_usable() {
2191                         // We only send a channel_update in the case where we are just now sending a
2192                         // channel_ready and the channel is in a usable state. We may re-send a
2193                         // channel_update later through the announcement_signatures process for public
2194                         // channels, but there's no reason not to just inform our counterparty of our fees
2195                         // now.
2196                         if let Ok(msg) = $self.get_channel_update_for_unicast($chan) {
2197                                 Some(events::MessageSendEvent::SendChannelUpdate {
2198                                         node_id: counterparty_node_id,
2199                                         msg,
2200                                 })
2201                         } else { None }
2202                 } else { None };
2203
2204                 let update_actions = $peer_state.monitor_update_blocked_actions
2205                         .remove(&$chan.context.channel_id()).unwrap_or(Vec::new());
2206
2207                 let htlc_forwards = $self.handle_channel_resumption(
2208                         &mut $peer_state.pending_msg_events, $chan, updates.raa,
2209                         updates.commitment_update, updates.order, updates.accepted_htlcs,
2210                         updates.funding_broadcastable, updates.channel_ready,
2211                         updates.announcement_sigs);
2212                 if let Some(upd) = channel_update {
2213                         $peer_state.pending_msg_events.push(upd);
2214                 }
2215
2216                 let channel_id = $chan.context.channel_id();
2217                 let unbroadcasted_batch_funding_txid = $chan.context.unbroadcasted_batch_funding_txid();
2218                 core::mem::drop($peer_state_lock);
2219                 core::mem::drop($per_peer_state_lock);
2220
2221                 // If the channel belongs to a batch funding transaction, the progress of the batch
2222                 // should be updated as we have received funding_signed and persisted the monitor.
2223                 if let Some(txid) = unbroadcasted_batch_funding_txid {
2224                         let mut funding_batch_states = $self.funding_batch_states.lock().unwrap();
2225                         let mut batch_completed = false;
2226                         if let Some(batch_state) = funding_batch_states.get_mut(&txid) {
2227                                 let channel_state = batch_state.iter_mut().find(|(chan_id, pubkey, _)| (
2228                                         *chan_id == channel_id &&
2229                                         *pubkey == counterparty_node_id
2230                                 ));
2231                                 if let Some(channel_state) = channel_state {
2232                                         channel_state.2 = true;
2233                                 } else {
2234                                         debug_assert!(false, "Missing channel batch state for channel which completed initial monitor update");
2235                                 }
2236                                 batch_completed = batch_state.iter().all(|(_, _, completed)| *completed);
2237                         } else {
2238                                 debug_assert!(false, "Missing batch state for channel which completed initial monitor update");
2239                         }
2240
2241                         // When all channels in a batched funding transaction have become ready, it is not necessary
2242                         // to track the progress of the batch anymore and the state of the channels can be updated.
2243                         if batch_completed {
2244                                 let removed_batch_state = funding_batch_states.remove(&txid).into_iter().flatten();
2245                                 let per_peer_state = $self.per_peer_state.read().unwrap();
2246                                 let mut batch_funding_tx = None;
2247                                 for (channel_id, counterparty_node_id, _) in removed_batch_state {
2248                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2249                                                 let mut peer_state = peer_state_mutex.lock().unwrap();
2250                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
2251                                                         batch_funding_tx = batch_funding_tx.or_else(|| chan.context.unbroadcasted_funding());
2252                                                         chan.set_batch_ready();
2253                                                         let mut pending_events = $self.pending_events.lock().unwrap();
2254                                                         emit_channel_pending_event!(pending_events, chan);
2255                                                 }
2256                                         }
2257                                 }
2258                                 if let Some(tx) = batch_funding_tx {
2259                                         log_info!($self.logger, "Broadcasting batch funding transaction with txid {}", tx.txid());
2260                                         $self.tx_broadcaster.broadcast_transactions(&[&tx]);
2261                                 }
2262                         }
2263                 }
2264
2265                 $self.handle_monitor_update_completion_actions(update_actions);
2266
2267                 if let Some(forwards) = htlc_forwards {
2268                         $self.forward_htlcs(&mut [forwards][..]);
2269                 }
2270                 $self.finalize_claims(updates.finalized_claimed_htlcs);
2271                 for failure in updates.failed_htlcs.drain(..) {
2272                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2273                         $self.fail_htlc_backwards_internal(&failure.0, &failure.1, &failure.2, receiver);
2274                 }
2275         } }
2276 }
2277
2278 macro_rules! handle_new_monitor_update {
2279         ($self: ident, $update_res: expr, $chan: expr, _internal, $completed: expr) => { {
2280                 debug_assert!($self.background_events_processed_since_startup.load(Ordering::Acquire));
2281                 let logger = WithChannelContext::from(&$self.logger, &$chan.context);
2282                 match $update_res {
2283                         ChannelMonitorUpdateStatus::UnrecoverableError => {
2284                                 let err_str = "ChannelMonitor[Update] persistence failed unrecoverably. This indicates we cannot continue normal operation and must shut down.";
2285                                 log_error!(logger, "{}", err_str);
2286                                 panic!("{}", err_str);
2287                         },
2288                         ChannelMonitorUpdateStatus::InProgress => {
2289                                 log_debug!(logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
2290                                         &$chan.context.channel_id());
2291                                 false
2292                         },
2293                         ChannelMonitorUpdateStatus::Completed => {
2294                                 $completed;
2295                                 true
2296                         },
2297                 }
2298         } };
2299         ($self: ident, $update_res: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, INITIAL_MONITOR) => {
2300                 handle_new_monitor_update!($self, $update_res, $chan, _internal,
2301                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan))
2302         };
2303         ($self: ident, $funding_txo: expr, $channel_id: expr, $update: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr) => { {
2304                 let in_flight_updates = $peer_state.in_flight_monitor_updates.entry($funding_txo)
2305                         .or_insert_with(Vec::new);
2306                 // During startup, we push monitor updates as background events through to here in
2307                 // order to replay updates that were in-flight when we shut down. Thus, we have to
2308                 // filter for uniqueness here.
2309                 let idx = in_flight_updates.iter().position(|upd| upd == &$update)
2310                         .unwrap_or_else(|| {
2311                                 in_flight_updates.push($update);
2312                                 in_flight_updates.len() - 1
2313                         });
2314                 let update_res = $self.chain_monitor.update_channel($funding_txo, &in_flight_updates[idx]);
2315                 handle_new_monitor_update!($self, update_res, $chan, _internal,
2316                         {
2317                                 let _ = in_flight_updates.remove(idx);
2318                                 if in_flight_updates.is_empty() && $chan.blocked_monitor_updates_pending() == 0 {
2319                                         handle_monitor_update_completion!($self, $peer_state_lock, $peer_state, $per_peer_state_lock, $chan);
2320                                 }
2321                         })
2322         } };
2323 }
2324
2325 macro_rules! process_events_body {
2326         ($self: expr, $event_to_handle: expr, $handle_event: expr) => {
2327                 let mut processed_all_events = false;
2328                 while !processed_all_events {
2329                         if $self.pending_events_processor.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
2330                                 return;
2331                         }
2332
2333                         let mut result;
2334
2335                         {
2336                                 // We'll acquire our total consistency lock so that we can be sure no other
2337                                 // persists happen while processing monitor events.
2338                                 let _read_guard = $self.total_consistency_lock.read().unwrap();
2339
2340                                 // Because `handle_post_event_actions` may send `ChannelMonitorUpdate`s to the user we must
2341                                 // ensure any startup-generated background events are handled first.
2342                                 result = $self.process_background_events();
2343
2344                                 // TODO: This behavior should be documented. It's unintuitive that we query
2345                                 // ChannelMonitors when clearing other events.
2346                                 if $self.process_pending_monitor_events() {
2347                                         result = NotifyOption::DoPersist;
2348                                 }
2349                         }
2350
2351                         let pending_events = $self.pending_events.lock().unwrap().clone();
2352                         let num_events = pending_events.len();
2353                         if !pending_events.is_empty() {
2354                                 result = NotifyOption::DoPersist;
2355                         }
2356
2357                         let mut post_event_actions = Vec::new();
2358
2359                         for (event, action_opt) in pending_events {
2360                                 $event_to_handle = event;
2361                                 $handle_event;
2362                                 if let Some(action) = action_opt {
2363                                         post_event_actions.push(action);
2364                                 }
2365                         }
2366
2367                         {
2368                                 let mut pending_events = $self.pending_events.lock().unwrap();
2369                                 pending_events.drain(..num_events);
2370                                 processed_all_events = pending_events.is_empty();
2371                                 // Note that `push_pending_forwards_ev` relies on `pending_events_processor` being
2372                                 // updated here with the `pending_events` lock acquired.
2373                                 $self.pending_events_processor.store(false, Ordering::Release);
2374                         }
2375
2376                         if !post_event_actions.is_empty() {
2377                                 $self.handle_post_event_actions(post_event_actions);
2378                                 // If we had some actions, go around again as we may have more events now
2379                                 processed_all_events = false;
2380                         }
2381
2382                         match result {
2383                                 NotifyOption::DoPersist => {
2384                                         $self.needs_persist_flag.store(true, Ordering::Release);
2385                                         $self.event_persist_notifier.notify();
2386                                 },
2387                                 NotifyOption::SkipPersistHandleEvents =>
2388                                         $self.event_persist_notifier.notify(),
2389                                 NotifyOption::SkipPersistNoEvents => {},
2390                         }
2391                 }
2392         }
2393 }
2394
2395 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>
2396 where
2397         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
2398         T::Target: BroadcasterInterface,
2399         ES::Target: EntropySource,
2400         NS::Target: NodeSigner,
2401         SP::Target: SignerProvider,
2402         F::Target: FeeEstimator,
2403         R::Target: Router,
2404         L::Target: Logger,
2405 {
2406         /// Constructs a new `ChannelManager` to hold several channels and route between them.
2407         ///
2408         /// The current time or latest block header time can be provided as the `current_timestamp`.
2409         ///
2410         /// This is the main "logic hub" for all channel-related actions, and implements
2411         /// [`ChannelMessageHandler`].
2412         ///
2413         /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2414         ///
2415         /// Users need to notify the new `ChannelManager` when a new block is connected or
2416         /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2417         /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2418         /// more details.
2419         ///
2420         /// [`block_connected`]: chain::Listen::block_connected
2421         /// [`block_disconnected`]: chain::Listen::block_disconnected
2422         /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2423         pub fn new(
2424                 fee_est: F, chain_monitor: M, tx_broadcaster: T, router: R, logger: L, entropy_source: ES,
2425                 node_signer: NS, signer_provider: SP, config: UserConfig, params: ChainParameters,
2426                 current_timestamp: u32,
2427         ) -> Self {
2428                 let mut secp_ctx = Secp256k1::new();
2429                 secp_ctx.seeded_randomize(&entropy_source.get_secure_random_bytes());
2430                 let inbound_pmt_key_material = node_signer.get_inbound_payment_key_material();
2431                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
2432                 ChannelManager {
2433                         default_configuration: config.clone(),
2434                         chain_hash: ChainHash::using_genesis_block(params.network),
2435                         fee_estimator: LowerBoundedFeeEstimator::new(fee_est),
2436                         chain_monitor,
2437                         tx_broadcaster,
2438                         router,
2439
2440                         best_block: RwLock::new(params.best_block),
2441
2442                         outbound_scid_aliases: Mutex::new(HashSet::new()),
2443                         pending_inbound_payments: Mutex::new(HashMap::new()),
2444                         pending_outbound_payments: OutboundPayments::new(),
2445                         forward_htlcs: Mutex::new(HashMap::new()),
2446                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments: HashMap::new(), pending_claiming_payments: HashMap::new() }),
2447                         pending_intercepted_htlcs: Mutex::new(HashMap::new()),
2448                         outpoint_to_peer: Mutex::new(HashMap::new()),
2449                         short_to_chan_info: FairRwLock::new(HashMap::new()),
2450
2451                         our_network_pubkey: node_signer.get_node_id(Recipient::Node).unwrap(),
2452                         secp_ctx,
2453
2454                         inbound_payment_key: expanded_inbound_key,
2455                         fake_scid_rand_bytes: entropy_source.get_secure_random_bytes(),
2456
2457                         probing_cookie_secret: entropy_source.get_secure_random_bytes(),
2458
2459                         highest_seen_timestamp: AtomicUsize::new(current_timestamp as usize),
2460
2461                         per_peer_state: FairRwLock::new(HashMap::new()),
2462
2463                         pending_events: Mutex::new(VecDeque::new()),
2464                         pending_events_processor: AtomicBool::new(false),
2465                         pending_background_events: Mutex::new(Vec::new()),
2466                         total_consistency_lock: RwLock::new(()),
2467                         background_events_processed_since_startup: AtomicBool::new(false),
2468                         event_persist_notifier: Notifier::new(),
2469                         needs_persist_flag: AtomicBool::new(false),
2470                         funding_batch_states: Mutex::new(BTreeMap::new()),
2471
2472                         pending_offers_messages: Mutex::new(Vec::new()),
2473                         pending_broadcast_messages: Mutex::new(Vec::new()),
2474
2475                         entropy_source,
2476                         node_signer,
2477                         signer_provider,
2478
2479                         logger,
2480                 }
2481         }
2482
2483         /// Gets the current configuration applied to all new channels.
2484         pub fn get_current_default_configuration(&self) -> &UserConfig {
2485                 &self.default_configuration
2486         }
2487
2488         fn create_and_insert_outbound_scid_alias(&self) -> u64 {
2489                 let height = self.best_block.read().unwrap().height();
2490                 let mut outbound_scid_alias = 0;
2491                 let mut i = 0;
2492                 loop {
2493                         if cfg!(fuzzing) { // fuzzing chacha20 doesn't use the key at all so we always get the same alias
2494                                 outbound_scid_alias += 1;
2495                         } else {
2496                                 outbound_scid_alias = fake_scid::Namespace::OutboundAlias.get_fake_scid(height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
2497                         }
2498                         if outbound_scid_alias != 0 && self.outbound_scid_aliases.lock().unwrap().insert(outbound_scid_alias) {
2499                                 break;
2500                         }
2501                         i += 1;
2502                         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"); }
2503                 }
2504                 outbound_scid_alias
2505         }
2506
2507         /// Creates a new outbound channel to the given remote node and with the given value.
2508         ///
2509         /// `user_channel_id` will be provided back as in
2510         /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2511         /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2512         /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2513         /// is simply copied to events and otherwise ignored.
2514         ///
2515         /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2516         /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2517         ///
2518         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2519         /// generate a shutdown scriptpubkey or destination script set by
2520         /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2521         ///
2522         /// Note that we do not check if you are currently connected to the given peer. If no
2523         /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2524         /// the channel eventually being silently forgotten (dropped on reload).
2525         ///
2526         /// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the
2527         /// channel. Otherwise, a random one will be generated for you.
2528         ///
2529         /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2530         /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2531         /// [`ChannelDetails::channel_id`] until after
2532         /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2533         /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2534         /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2535         ///
2536         /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2537         /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2538         /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2539         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> {
2540                 if channel_value_satoshis < 1000 {
2541                         return Err(APIError::APIMisuseError { err: format!("Channel value must be at least 1000 satoshis. It was {}", channel_value_satoshis) });
2542                 }
2543
2544                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2545                 // We want to make sure the lock is actually acquired by PersistenceNotifierGuard.
2546                 debug_assert!(&self.total_consistency_lock.try_write().is_err());
2547
2548                 let per_peer_state = self.per_peer_state.read().unwrap();
2549
2550                 let peer_state_mutex = per_peer_state.get(&their_network_key)
2551                         .ok_or_else(|| APIError::APIMisuseError{ err: format!("Not connected to node: {}", their_network_key) })?;
2552
2553                 let mut peer_state = peer_state_mutex.lock().unwrap();
2554
2555                 if let Some(temporary_channel_id) = temporary_channel_id {
2556                         if peer_state.channel_by_id.contains_key(&temporary_channel_id) {
2557                                 return Err(APIError::APIMisuseError{ err: format!("Channel with temporary channel ID {} already exists!", temporary_channel_id)});
2558                         }
2559                 }
2560
2561                 let channel = {
2562                         let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
2563                         let their_features = &peer_state.latest_features;
2564                         let config = if override_config.is_some() { override_config.as_ref().unwrap() } else { &self.default_configuration };
2565                         match OutboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider, their_network_key,
2566                                 their_features, channel_value_satoshis, push_msat, user_channel_id, config,
2567                                 self.best_block.read().unwrap().height(), outbound_scid_alias, temporary_channel_id)
2568                         {
2569                                 Ok(res) => res,
2570                                 Err(e) => {
2571                                         self.outbound_scid_aliases.lock().unwrap().remove(&outbound_scid_alias);
2572                                         return Err(e);
2573                                 },
2574                         }
2575                 };
2576                 let res = channel.get_open_channel(self.chain_hash);
2577
2578                 let temporary_channel_id = channel.context.channel_id();
2579                 match peer_state.channel_by_id.entry(temporary_channel_id) {
2580                         hash_map::Entry::Occupied(_) => {
2581                                 if cfg!(fuzzing) {
2582                                         return Err(APIError::APIMisuseError { err: "Fuzzy bad RNG".to_owned() });
2583                                 } else {
2584                                         panic!("RNG is bad???");
2585                                 }
2586                         },
2587                         hash_map::Entry::Vacant(entry) => { entry.insert(ChannelPhase::UnfundedOutboundV1(channel)); }
2588                 }
2589
2590                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
2591                         node_id: their_network_key,
2592                         msg: res,
2593                 });
2594                 Ok(temporary_channel_id)
2595         }
2596
2597         fn list_funded_channels_with_filter<Fn: FnMut(&(&ChannelId, &Channel<SP>)) -> bool + Copy>(&self, f: Fn) -> Vec<ChannelDetails> {
2598                 // Allocate our best estimate of the number of channels we have in the `res`
2599                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2600                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2601                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2602                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2603                 // the same channel.
2604                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2605                 {
2606                         let best_block_height = self.best_block.read().unwrap().height();
2607                         let per_peer_state = self.per_peer_state.read().unwrap();
2608                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2609                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2610                                 let peer_state = &mut *peer_state_lock;
2611                                 res.extend(peer_state.channel_by_id.iter()
2612                                         .filter_map(|(chan_id, phase)| match phase {
2613                                                 // Only `Channels` in the `ChannelPhase::Funded` phase can be considered funded.
2614                                                 ChannelPhase::Funded(chan) => Some((chan_id, chan)),
2615                                                 _ => None,
2616                                         })
2617                                         .filter(f)
2618                                         .map(|(_channel_id, channel)| {
2619                                                 ChannelDetails::from_channel_context(&channel.context, best_block_height,
2620                                                         peer_state.latest_features.clone(), &self.fee_estimator)
2621                                         })
2622                                 );
2623                         }
2624                 }
2625                 res
2626         }
2627
2628         /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2629         /// more information.
2630         pub fn list_channels(&self) -> Vec<ChannelDetails> {
2631                 // Allocate our best estimate of the number of channels we have in the `res`
2632                 // Vec. Sadly the `short_to_chan_info` map doesn't cover channels without
2633                 // a scid or a scid alias, and the `outpoint_to_peer` shouldn't be used outside
2634                 // of the ChannelMonitor handling. Therefore reallocations may still occur, but is
2635                 // unlikely as the `short_to_chan_info` map often contains 2 entries for
2636                 // the same channel.
2637                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
2638                 {
2639                         let best_block_height = self.best_block.read().unwrap().height();
2640                         let per_peer_state = self.per_peer_state.read().unwrap();
2641                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
2642                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2643                                 let peer_state = &mut *peer_state_lock;
2644                                 for context in peer_state.channel_by_id.iter().map(|(_, phase)| phase.context()) {
2645                                         let details = ChannelDetails::from_channel_context(context, best_block_height,
2646                                                 peer_state.latest_features.clone(), &self.fee_estimator);
2647                                         res.push(details);
2648                                 }
2649                         }
2650                 }
2651                 res
2652         }
2653
2654         /// Gets the list of usable channels, in random order. Useful as an argument to
2655         /// [`Router::find_route`] to ensure non-announced channels are used.
2656         ///
2657         /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2658         /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2659         /// are.
2660         pub fn list_usable_channels(&self) -> Vec<ChannelDetails> {
2661                 // Note we use is_live here instead of usable which leads to somewhat confused
2662                 // internal/external nomenclature, but that's ok cause that's probably what the user
2663                 // really wanted anyway.
2664                 self.list_funded_channels_with_filter(|&(_, ref channel)| channel.context.is_live())
2665         }
2666
2667         /// Gets the list of channels we have with a given counterparty, in random order.
2668         pub fn list_channels_with_counterparty(&self, counterparty_node_id: &PublicKey) -> Vec<ChannelDetails> {
2669                 let best_block_height = self.best_block.read().unwrap().height();
2670                 let per_peer_state = self.per_peer_state.read().unwrap();
2671
2672                 if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
2673                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2674                         let peer_state = &mut *peer_state_lock;
2675                         let features = &peer_state.latest_features;
2676                         let context_to_details = |context| {
2677                                 ChannelDetails::from_channel_context(context, best_block_height, features.clone(), &self.fee_estimator)
2678                         };
2679                         return peer_state.channel_by_id
2680                                 .iter()
2681                                 .map(|(_, phase)| phase.context())
2682                                 .map(context_to_details)
2683                                 .collect();
2684                 }
2685                 vec![]
2686         }
2687
2688         /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2689         /// successful path, or have unresolved HTLCs.
2690         ///
2691         /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2692         /// result of a crash. If such a payment exists, is not listed here, and an
2693         /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2694         ///
2695         /// [`Event::PaymentSent`]: events::Event::PaymentSent
2696         pub fn list_recent_payments(&self) -> Vec<RecentPaymentDetails> {
2697                 self.pending_outbound_payments.pending_outbound_payments.lock().unwrap().iter()
2698                         .filter_map(|(payment_id, pending_outbound_payment)| match pending_outbound_payment {
2699                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
2700                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2701                                 },
2702                                 // InvoiceReceived is an intermediate state and doesn't need to be exposed
2703                                 PendingOutboundPayment::InvoiceReceived { .. } => {
2704                                         Some(RecentPaymentDetails::AwaitingInvoice { payment_id: *payment_id })
2705                                 },
2706                                 PendingOutboundPayment::Retryable { payment_hash, total_msat, .. } => {
2707                                         Some(RecentPaymentDetails::Pending {
2708                                                 payment_id: *payment_id,
2709                                                 payment_hash: *payment_hash,
2710                                                 total_msat: *total_msat,
2711                                         })
2712                                 },
2713                                 PendingOutboundPayment::Abandoned { payment_hash, .. } => {
2714                                         Some(RecentPaymentDetails::Abandoned { payment_id: *payment_id, payment_hash: *payment_hash })
2715                                 },
2716                                 PendingOutboundPayment::Fulfilled { payment_hash, .. } => {
2717                                         Some(RecentPaymentDetails::Fulfilled { payment_id: *payment_id, payment_hash: *payment_hash })
2718                                 },
2719                                 PendingOutboundPayment::Legacy { .. } => None
2720                         })
2721                         .collect()
2722         }
2723
2724         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> {
2725                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2726
2727                 let mut failed_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
2728                 let mut shutdown_result = None;
2729
2730                 {
2731                         let per_peer_state = self.per_peer_state.read().unwrap();
2732
2733                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
2734                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
2735
2736                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
2737                         let peer_state = &mut *peer_state_lock;
2738
2739                         match peer_state.channel_by_id.entry(channel_id.clone()) {
2740                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
2741                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
2742                                                 let funding_txo_opt = chan.context.get_funding_txo();
2743                                                 let their_features = &peer_state.latest_features;
2744                                                 let (shutdown_msg, mut monitor_update_opt, htlcs) =
2745                                                         chan.get_shutdown(&self.signer_provider, their_features, target_feerate_sats_per_1000_weight, override_shutdown_script)?;
2746                                                 failed_htlcs = htlcs;
2747
2748                                                 // We can send the `shutdown` message before updating the `ChannelMonitor`
2749                                                 // here as we don't need the monitor update to complete until we send a
2750                                                 // `shutdown_signed`, which we'll delay if we're pending a monitor update.
2751                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
2752                                                         node_id: *counterparty_node_id,
2753                                                         msg: shutdown_msg,
2754                                                 });
2755
2756                                                 debug_assert!(monitor_update_opt.is_none() || !chan.is_shutdown(),
2757                                                         "We can't both complete shutdown and generate a monitor update");
2758
2759                                                 // Update the monitor with the shutdown script if necessary.
2760                                                 if let Some(monitor_update) = monitor_update_opt.take() {
2761                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), *channel_id, monitor_update,
2762                                                                 peer_state_lock, peer_state, per_peer_state, chan);
2763                                                 }
2764                                         } else {
2765                                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2766                                                 shutdown_result = Some(chan_phase.context_mut().force_shutdown(false, ClosureReason::HolderForceClosed));
2767                                         }
2768                                 },
2769                                 hash_map::Entry::Vacant(_) => {
2770                                         return Err(APIError::ChannelUnavailable {
2771                                                 err: format!(
2772                                                         "Channel with id {} not found for the passed counterparty node_id {}",
2773                                                         channel_id, counterparty_node_id,
2774                                                 )
2775                                         });
2776                                 },
2777                         }
2778                 }
2779
2780                 for htlc_source in failed_htlcs.drain(..) {
2781                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2782                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(*counterparty_node_id), channel_id: *channel_id };
2783                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
2784                 }
2785
2786                 if let Some(shutdown_result) = shutdown_result {
2787                         self.finish_close_channel(shutdown_result);
2788                 }
2789
2790                 Ok(())
2791         }
2792
2793         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2794         /// will be accepted on the given channel, and after additional timeout/the closing of all
2795         /// pending HTLCs, the channel will be closed on chain.
2796         ///
2797         ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2798         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2799         ///    fee estimate.
2800         ///  * If our counterparty is the channel initiator, we will require a channel closing
2801         ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2802         ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2803         ///    counterparty to pay as much fee as they'd like, however.
2804         ///
2805         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2806         ///
2807         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2808         /// generate a shutdown scriptpubkey or destination script set by
2809         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2810         /// channel.
2811         ///
2812         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2813         /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2814         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2815         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2816         pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
2817                 self.close_channel_internal(channel_id, counterparty_node_id, None, None)
2818         }
2819
2820         /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2821         /// will be accepted on the given channel, and after additional timeout/the closing of all
2822         /// pending HTLCs, the channel will be closed on chain.
2823         ///
2824         /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2825         /// the channel being closed or not:
2826         ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2827         ///    transaction. The upper-bound is set by
2828         ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2829         ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2830         ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2831         ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2832         ///    will appear on a force-closure transaction, whichever is lower).
2833         ///
2834         /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2835         /// Will fail if a shutdown script has already been set for this channel by
2836         /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2837         /// also be compatible with our and the counterparty's features.
2838         ///
2839         /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2840         ///
2841         /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2842         /// generate a shutdown scriptpubkey or destination script set by
2843         /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2844         /// channel.
2845         ///
2846         /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2847         /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2848         /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2849         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> {
2850                 self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
2851         }
2852
2853         fn finish_close_channel(&self, mut shutdown_res: ShutdownResult) {
2854                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
2855                 #[cfg(debug_assertions)]
2856                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
2857                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
2858                 }
2859
2860                 let logger = WithContext::from(
2861                         &self.logger, Some(shutdown_res.counterparty_node_id), Some(shutdown_res.channel_id),
2862                 );
2863
2864                 log_debug!(logger, "Finishing closure of channel due to {} with {} HTLCs to fail",
2865                         shutdown_res.closure_reason, shutdown_res.dropped_outbound_htlcs.len());
2866                 for htlc_source in shutdown_res.dropped_outbound_htlcs.drain(..) {
2867                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
2868                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
2869                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
2870                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
2871                 }
2872                 if let Some((_, funding_txo, _channel_id, monitor_update)) = shutdown_res.monitor_update {
2873                         // There isn't anything we can do if we get an update failure - we're already
2874                         // force-closing. The monitor update on the required in-memory copy should broadcast
2875                         // the latest local state, which is the best we can do anyway. Thus, it is safe to
2876                         // ignore the result here.
2877                         let _ = self.chain_monitor.update_channel(funding_txo, &monitor_update);
2878                 }
2879                 let mut shutdown_results = Vec::new();
2880                 if let Some(txid) = shutdown_res.unbroadcasted_batch_funding_txid {
2881                         let mut funding_batch_states = self.funding_batch_states.lock().unwrap();
2882                         let affected_channels = funding_batch_states.remove(&txid).into_iter().flatten();
2883                         let per_peer_state = self.per_peer_state.read().unwrap();
2884                         let mut has_uncompleted_channel = None;
2885                         for (channel_id, counterparty_node_id, state) in affected_channels {
2886                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2887                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2888                                         if let Some(mut chan) = peer_state.channel_by_id.remove(&channel_id) {
2889                                                 update_maps_on_chan_removal!(self, &chan.context());
2890                                                 shutdown_results.push(chan.context_mut().force_shutdown(false, ClosureReason::FundingBatchClosure));
2891                                         }
2892                                 }
2893                                 has_uncompleted_channel = Some(has_uncompleted_channel.map_or(!state, |v| v || !state));
2894                         }
2895                         debug_assert!(
2896                                 has_uncompleted_channel.unwrap_or(true),
2897                                 "Closing a batch where all channels have completed initial monitor update",
2898                         );
2899                 }
2900
2901                 {
2902                         let mut pending_events = self.pending_events.lock().unwrap();
2903                         pending_events.push_back((events::Event::ChannelClosed {
2904                                 channel_id: shutdown_res.channel_id,
2905                                 user_channel_id: shutdown_res.user_channel_id,
2906                                 reason: shutdown_res.closure_reason,
2907                                 counterparty_node_id: Some(shutdown_res.counterparty_node_id),
2908                                 channel_capacity_sats: Some(shutdown_res.channel_capacity_satoshis),
2909                                 channel_funding_txo: shutdown_res.channel_funding_txo,
2910                         }, None));
2911
2912                         if let Some(transaction) = shutdown_res.unbroadcasted_funding_tx {
2913                                 pending_events.push_back((events::Event::DiscardFunding {
2914                                         channel_id: shutdown_res.channel_id, transaction
2915                                 }, None));
2916                         }
2917                 }
2918                 for shutdown_result in shutdown_results.drain(..) {
2919                         self.finish_close_channel(shutdown_result);
2920                 }
2921         }
2922
2923         /// `peer_msg` should be set when we receive a message from a peer, but not set when the
2924         /// user closes, which will be re-exposed as the `ChannelClosed` reason.
2925         fn force_close_channel_with_peer(&self, channel_id: &ChannelId, peer_node_id: &PublicKey, peer_msg: Option<&String>, broadcast: bool)
2926         -> Result<PublicKey, APIError> {
2927                 let per_peer_state = self.per_peer_state.read().unwrap();
2928                 let peer_state_mutex = per_peer_state.get(peer_node_id)
2929                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", peer_node_id) })?;
2930                 let (update_opt, counterparty_node_id) = {
2931                         let mut peer_state = peer_state_mutex.lock().unwrap();
2932                         let closure_reason = if let Some(peer_msg) = peer_msg {
2933                                 ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(peer_msg.to_string()) }
2934                         } else {
2935                                 ClosureReason::HolderForceClosed
2936                         };
2937                         let logger = WithContext::from(&self.logger, Some(*peer_node_id), Some(*channel_id));
2938                         if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id.clone()) {
2939                                 log_error!(logger, "Force-closing channel {}", channel_id);
2940                                 let mut chan_phase = remove_channel_phase!(self, chan_phase_entry);
2941                                 mem::drop(peer_state);
2942                                 mem::drop(per_peer_state);
2943                                 match chan_phase {
2944                                         ChannelPhase::Funded(mut chan) => {
2945                                                 self.finish_close_channel(chan.context.force_shutdown(broadcast, closure_reason));
2946                                                 (self.get_channel_update_for_broadcast(&chan).ok(), chan.context.get_counterparty_node_id())
2947                                         },
2948                                         ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => {
2949                                                 self.finish_close_channel(chan_phase.context_mut().force_shutdown(false, closure_reason));
2950                                                 // Unfunded channel has no update
2951                                                 (None, chan_phase.context().get_counterparty_node_id())
2952                                         },
2953                                 }
2954                         } else if peer_state.inbound_channel_request_by_id.remove(channel_id).is_some() {
2955                                 log_error!(logger, "Force-closing channel {}", &channel_id);
2956                                 // N.B. that we don't send any channel close event here: we
2957                                 // don't have a user_channel_id, and we never sent any opening
2958                                 // events anyway.
2959                                 (None, *peer_node_id)
2960                         } else {
2961                                 return Err(APIError::ChannelUnavailable{ err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, peer_node_id) });
2962                         }
2963                 };
2964                 if let Some(update) = update_opt {
2965                         // If we have some Channel Update to broadcast, we cache it and broadcast it later.
2966                         let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
2967                         pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
2968                                 msg: update
2969                         });
2970                 }
2971
2972                 Ok(counterparty_node_id)
2973         }
2974
2975         fn force_close_sending_error(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, broadcast: bool) -> Result<(), APIError> {
2976                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
2977                 match self.force_close_channel_with_peer(channel_id, counterparty_node_id, None, broadcast) {
2978                         Ok(counterparty_node_id) => {
2979                                 let per_peer_state = self.per_peer_state.read().unwrap();
2980                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
2981                                         let mut peer_state = peer_state_mutex.lock().unwrap();
2982                                         peer_state.pending_msg_events.push(
2983                                                 events::MessageSendEvent::HandleError {
2984                                                         node_id: counterparty_node_id,
2985                                                         action: msgs::ErrorAction::DisconnectPeer {
2986                                                                 msg: Some(msgs::ErrorMessage { channel_id: *channel_id, data: "Channel force-closed".to_owned() })
2987                                                         },
2988                                                 }
2989                                         );
2990                                 }
2991                                 Ok(())
2992                         },
2993                         Err(e) => Err(e)
2994                 }
2995         }
2996
2997         /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2998         /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2999         /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
3000         /// channel.
3001         pub fn force_close_broadcasting_latest_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
3002         -> Result<(), APIError> {
3003                 self.force_close_sending_error(channel_id, counterparty_node_id, true)
3004         }
3005
3006         /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
3007         /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
3008         /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
3009         ///
3010         /// You can always get the latest local transaction(s) to broadcast from
3011         /// [`ChannelMonitor::get_latest_holder_commitment_txn`].
3012         pub fn force_close_without_broadcasting_txn(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey)
3013         -> Result<(), APIError> {
3014                 self.force_close_sending_error(channel_id, counterparty_node_id, false)
3015         }
3016
3017         /// Force close all channels, immediately broadcasting the latest local commitment transaction
3018         /// for each to the chain and rejecting new HTLCs on each.
3019         pub fn force_close_all_channels_broadcasting_latest_txn(&self) {
3020                 for chan in self.list_channels() {
3021                         let _ = self.force_close_broadcasting_latest_txn(&chan.channel_id, &chan.counterparty.node_id);
3022                 }
3023         }
3024
3025         /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
3026         /// local transaction(s).
3027         pub fn force_close_all_channels_without_broadcasting_txn(&self) {
3028                 for chan in self.list_channels() {
3029                         let _ = self.force_close_without_broadcasting_txn(&chan.channel_id, &chan.counterparty.node_id);
3030                 }
3031         }
3032
3033         fn decode_update_add_htlc_onion(
3034                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey,
3035         ) -> Result<
3036                 (onion_utils::Hop, [u8; 32], Option<Result<PublicKey, secp256k1::Error>>), HTLCFailureMsg
3037         > {
3038                 let (next_hop, shared_secret, next_packet_details_opt) = decode_incoming_update_add_htlc_onion(
3039                         msg, &self.node_signer, &self.logger, &self.secp_ctx
3040                 )?;
3041
3042                 let is_intro_node_forward = match next_hop {
3043                         onion_utils::Hop::Forward {
3044                                 next_hop_data: msgs::InboundOnionPayload::BlindedForward {
3045                                         intro_node_blinding_point: Some(_), ..
3046                                 }, ..
3047                         } => true,
3048                         _ => false,
3049                 };
3050
3051                 macro_rules! return_err {
3052                         ($msg: expr, $err_code: expr, $data: expr) => {
3053                                 {
3054                                         log_info!(
3055                                                 WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id)),
3056                                                 "Failed to accept/forward incoming HTLC: {}", $msg
3057                                         );
3058                                         // If `msg.blinding_point` is set, we must always fail with malformed.
3059                                         if msg.blinding_point.is_some() {
3060                                                 return Err(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
3061                                                         channel_id: msg.channel_id,
3062                                                         htlc_id: msg.htlc_id,
3063                                                         sha256_of_onion: [0; 32],
3064                                                         failure_code: INVALID_ONION_BLINDING,
3065                                                 }));
3066                                         }
3067
3068                                         let (err_code, err_data) = if is_intro_node_forward {
3069                                                 (INVALID_ONION_BLINDING, &[0; 32][..])
3070                                         } else { ($err_code, $data) };
3071                                         return Err(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3072                                                 channel_id: msg.channel_id,
3073                                                 htlc_id: msg.htlc_id,
3074                                                 reason: HTLCFailReason::reason(err_code, err_data.to_vec())
3075                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3076                                         }));
3077                                 }
3078                         }
3079                 }
3080
3081                 let NextPacketDetails {
3082                         next_packet_pubkey, outgoing_amt_msat, outgoing_scid, outgoing_cltv_value
3083                 } = match next_packet_details_opt {
3084                         Some(next_packet_details) => next_packet_details,
3085                         // it is a receive, so no need for outbound checks
3086                         None => return Ok((next_hop, shared_secret, None)),
3087                 };
3088
3089                 // Perform outbound checks here instead of in [`Self::construct_pending_htlc_info`] because we
3090                 // can't hold the outbound peer state lock at the same time as the inbound peer state lock.
3091                 if let Some((err, mut code, chan_update)) = loop {
3092                         let id_option = self.short_to_chan_info.read().unwrap().get(&outgoing_scid).cloned();
3093                         let forwarding_chan_info_opt = match id_option {
3094                                 None => { // unknown_next_peer
3095                                         // Note that this is likely a timing oracle for detecting whether an scid is a
3096                                         // phantom or an intercept.
3097                                         if (self.default_configuration.accept_intercept_htlcs &&
3098                                                 fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)) ||
3099                                                 fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, outgoing_scid, &self.chain_hash)
3100                                         {
3101                                                 None
3102                                         } else {
3103                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3104                                         }
3105                                 },
3106                                 Some((cp_id, id)) => Some((cp_id.clone(), id.clone())),
3107                         };
3108                         let chan_update_opt = if let Some((counterparty_node_id, forwarding_id)) = forwarding_chan_info_opt {
3109                                 let per_peer_state = self.per_peer_state.read().unwrap();
3110                                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
3111                                 if peer_state_mutex_opt.is_none() {
3112                                         break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3113                                 }
3114                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
3115                                 let peer_state = &mut *peer_state_lock;
3116                                 let chan = match peer_state.channel_by_id.get_mut(&forwarding_id).map(
3117                                         |chan_phase| if let ChannelPhase::Funded(chan) = chan_phase { Some(chan) } else { None }
3118                                 ).flatten() {
3119                                         None => {
3120                                                 // Channel was removed. The short_to_chan_info and channel_by_id maps
3121                                                 // have no consistency guarantees.
3122                                                 break Some(("Don't have available channel for forwarding as requested.", 0x4000 | 10, None));
3123                                         },
3124                                         Some(chan) => chan
3125                                 };
3126                                 if !chan.context.should_announce() && !self.default_configuration.accept_forwards_to_priv_channels {
3127                                         // Note that the behavior here should be identical to the above block - we
3128                                         // should NOT reveal the existence or non-existence of a private channel if
3129                                         // we don't allow forwards outbound over them.
3130                                         break Some(("Refusing to forward to a private channel based on our config.", 0x4000 | 10, None));
3131                                 }
3132                                 if chan.context.get_channel_type().supports_scid_privacy() && outgoing_scid != chan.context.outbound_scid_alias() {
3133                                         // `option_scid_alias` (referred to in LDK as `scid_privacy`) means
3134                                         // "refuse to forward unless the SCID alias was used", so we pretend
3135                                         // we don't have the channel here.
3136                                         break Some(("Refusing to forward over real channel SCID as our counterparty requested.", 0x4000 | 10, None));
3137                                 }
3138                                 let chan_update_opt = self.get_channel_update_for_onion(outgoing_scid, chan).ok();
3139
3140                                 // Note that we could technically not return an error yet here and just hope
3141                                 // that the connection is reestablished or monitor updated by the time we get
3142                                 // around to doing the actual forward, but better to fail early if we can and
3143                                 // hopefully an attacker trying to path-trace payments cannot make this occur
3144                                 // on a small/per-node/per-channel scale.
3145                                 if !chan.context.is_live() { // channel_disabled
3146                                         // If the channel_update we're going to return is disabled (i.e. the
3147                                         // peer has been disabled for some time), return `channel_disabled`,
3148                                         // otherwise return `temporary_channel_failure`.
3149                                         if chan_update_opt.as_ref().map(|u| u.contents.flags & 2 == 2).unwrap_or(false) {
3150                                                 break Some(("Forwarding channel has been disconnected for some time.", 0x1000 | 20, chan_update_opt));
3151                                         } else {
3152                                                 break Some(("Forwarding channel is not in a ready state.", 0x1000 | 7, chan_update_opt));
3153                                         }
3154                                 }
3155                                 if outgoing_amt_msat < chan.context.get_counterparty_htlc_minimum_msat() { // amount_below_minimum
3156                                         break Some(("HTLC amount was below the htlc_minimum_msat", 0x1000 | 11, chan_update_opt));
3157                                 }
3158                                 if let Err((err, code)) = chan.htlc_satisfies_config(&msg, outgoing_amt_msat, outgoing_cltv_value) {
3159                                         break Some((err, code, chan_update_opt));
3160                                 }
3161                                 chan_update_opt
3162                         } else {
3163                                 None
3164                         };
3165
3166                         let cur_height = self.best_block.read().unwrap().height() + 1;
3167
3168                         if let Err((err_msg, code)) = check_incoming_htlc_cltv(
3169                                 cur_height, outgoing_cltv_value, msg.cltv_expiry
3170                         ) {
3171                                 if code & 0x1000 != 0 && chan_update_opt.is_none() {
3172                                         // We really should set `incorrect_cltv_expiry` here but as we're not
3173                                         // forwarding over a real channel we can't generate a channel_update
3174                                         // for it. Instead we just return a generic temporary_node_failure.
3175                                         break Some((err_msg, 0x2000 | 2, None))
3176                                 }
3177                                 let chan_update_opt = if code & 0x1000 != 0 { chan_update_opt } else { None };
3178                                 break Some((err_msg, code, chan_update_opt));
3179                         }
3180
3181                         break None;
3182                 }
3183                 {
3184                         let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
3185                         if let Some(chan_update) = chan_update {
3186                                 if code == 0x1000 | 11 || code == 0x1000 | 12 {
3187                                         msg.amount_msat.write(&mut res).expect("Writes cannot fail");
3188                                 }
3189                                 else if code == 0x1000 | 13 {
3190                                         msg.cltv_expiry.write(&mut res).expect("Writes cannot fail");
3191                                 }
3192                                 else if code == 0x1000 | 20 {
3193                                         // TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
3194                                         0u16.write(&mut res).expect("Writes cannot fail");
3195                                 }
3196                                 (chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
3197                                 msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
3198                                 chan_update.write(&mut res).expect("Writes cannot fail");
3199                         } else if code & 0x1000 == 0x1000 {
3200                                 // If we're trying to return an error that requires a `channel_update` but
3201                                 // we're forwarding to a phantom or intercept "channel" (i.e. cannot
3202                                 // generate an update), just use the generic "temporary_node_failure"
3203                                 // instead.
3204                                 code = 0x2000 | 2;
3205                         }
3206                         return_err!(err, code, &res.0[..]);
3207                 }
3208                 Ok((next_hop, shared_secret, Some(next_packet_pubkey)))
3209         }
3210
3211         fn construct_pending_htlc_status<'a>(
3212                 &self, msg: &msgs::UpdateAddHTLC, counterparty_node_id: &PublicKey, shared_secret: [u8; 32],
3213                 decoded_hop: onion_utils::Hop, allow_underpay: bool,
3214                 next_packet_pubkey_opt: Option<Result<PublicKey, secp256k1::Error>>,
3215         ) -> PendingHTLCStatus {
3216                 macro_rules! return_err {
3217                         ($msg: expr, $err_code: expr, $data: expr) => {
3218                                 {
3219                                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
3220                                         log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
3221                                         if msg.blinding_point.is_some() {
3222                                                 return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
3223                                                         msgs::UpdateFailMalformedHTLC {
3224                                                                 channel_id: msg.channel_id,
3225                                                                 htlc_id: msg.htlc_id,
3226                                                                 sha256_of_onion: [0; 32],
3227                                                                 failure_code: INVALID_ONION_BLINDING,
3228                                                         }
3229                                                 ))
3230                                         }
3231                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
3232                                                 channel_id: msg.channel_id,
3233                                                 htlc_id: msg.htlc_id,
3234                                                 reason: HTLCFailReason::reason($err_code, $data.to_vec())
3235                                                         .get_encrypted_failure_packet(&shared_secret, &None),
3236                                         }));
3237                                 }
3238                         }
3239                 }
3240                 match decoded_hop {
3241                         onion_utils::Hop::Receive(next_hop_data) => {
3242                                 // OUR PAYMENT!
3243                                 let current_height: u32 = self.best_block.read().unwrap().height();
3244                                 match create_recv_pending_htlc_info(next_hop_data, shared_secret, msg.payment_hash,
3245                                         msg.amount_msat, msg.cltv_expiry, None, allow_underpay, msg.skimmed_fee_msat,
3246                                         current_height, self.default_configuration.accept_mpp_keysend)
3247                                 {
3248                                         Ok(info) => {
3249                                                 // Note that we could obviously respond immediately with an update_fulfill_htlc
3250                                                 // message, however that would leak that we are the recipient of this payment, so
3251                                                 // instead we stay symmetric with the forwarding case, only responding (after a
3252                                                 // delay) once they've send us a commitment_signed!
3253                                                 PendingHTLCStatus::Forward(info)
3254                                         },
3255                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3256                                 }
3257                         },
3258                         onion_utils::Hop::Forward { next_hop_data, next_hop_hmac, new_packet_bytes } => {
3259                                 match create_fwd_pending_htlc_info(msg, next_hop_data, next_hop_hmac,
3260                                         new_packet_bytes, shared_secret, next_packet_pubkey_opt) {
3261                                         Ok(info) => PendingHTLCStatus::Forward(info),
3262                                         Err(InboundHTLCErr { err_code, err_data, msg }) => return_err!(msg, err_code, &err_data)
3263                                 }
3264                         }
3265                 }
3266         }
3267
3268         /// Gets the current [`channel_update`] for the given channel. This first checks if the channel is
3269         /// public, and thus should be called whenever the result is going to be passed out in a
3270         /// [`MessageSendEvent::BroadcastChannelUpdate`] event.
3271         ///
3272         /// Note that in [`internal_closing_signed`], this function is called without the `peer_state`
3273         /// corresponding to the channel's counterparty locked, as the channel been removed from the
3274         /// storage and the `peer_state` lock has been dropped.
3275         ///
3276         /// [`channel_update`]: msgs::ChannelUpdate
3277         /// [`internal_closing_signed`]: Self::internal_closing_signed
3278         fn get_channel_update_for_broadcast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3279                 if !chan.context.should_announce() {
3280                         return Err(LightningError {
3281                                 err: "Cannot broadcast a channel_update for a private channel".to_owned(),
3282                                 action: msgs::ErrorAction::IgnoreError
3283                         });
3284                 }
3285                 if chan.context.get_short_channel_id().is_none() {
3286                         return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError});
3287                 }
3288                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3289                 log_trace!(logger, "Attempting to generate broadcast channel update for channel {}", &chan.context.channel_id());
3290                 self.get_channel_update_for_unicast(chan)
3291         }
3292
3293         /// Gets the current [`channel_update`] for the given channel. This does not check if the channel
3294         /// is public (only returning an `Err` if the channel does not yet have an assigned SCID),
3295         /// and thus MUST NOT be called unless the recipient of the resulting message has already
3296         /// provided evidence that they know about the existence of the channel.
3297         ///
3298         /// Note that through [`internal_closing_signed`], this function is called without the
3299         /// `peer_state`  corresponding to the channel's counterparty locked, as the channel been
3300         /// removed from the storage and the `peer_state` lock has been dropped.
3301         ///
3302         /// [`channel_update`]: msgs::ChannelUpdate
3303         /// [`internal_closing_signed`]: Self::internal_closing_signed
3304         fn get_channel_update_for_unicast(&self, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3305                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3306                 log_trace!(logger, "Attempting to generate channel update for channel {}", chan.context.channel_id());
3307                 let short_channel_id = match chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias()) {
3308                         None => return Err(LightningError{err: "Channel not yet established".to_owned(), action: msgs::ErrorAction::IgnoreError}),
3309                         Some(id) => id,
3310                 };
3311
3312                 self.get_channel_update_for_onion(short_channel_id, chan)
3313         }
3314
3315         fn get_channel_update_for_onion(&self, short_channel_id: u64, chan: &Channel<SP>) -> Result<msgs::ChannelUpdate, LightningError> {
3316                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3317                 log_trace!(logger, "Generating channel update for channel {}", chan.context.channel_id());
3318                 let were_node_one = self.our_network_pubkey.serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
3319
3320                 let enabled = chan.context.is_usable() && match chan.channel_update_status() {
3321                         ChannelUpdateStatus::Enabled => true,
3322                         ChannelUpdateStatus::DisabledStaged(_) => true,
3323                         ChannelUpdateStatus::Disabled => false,
3324                         ChannelUpdateStatus::EnabledStaged(_) => false,
3325                 };
3326
3327                 let unsigned = msgs::UnsignedChannelUpdate {
3328                         chain_hash: self.chain_hash,
3329                         short_channel_id,
3330                         timestamp: chan.context.get_update_time_counter(),
3331                         flags: (!were_node_one) as u8 | ((!enabled as u8) << 1),
3332                         cltv_expiry_delta: chan.context.get_cltv_expiry_delta(),
3333                         htlc_minimum_msat: chan.context.get_counterparty_htlc_minimum_msat(),
3334                         htlc_maximum_msat: chan.context.get_announced_htlc_max_msat(),
3335                         fee_base_msat: chan.context.get_outbound_forwarding_fee_base_msat(),
3336                         fee_proportional_millionths: chan.context.get_fee_proportional_millionths(),
3337                         excess_data: Vec::new(),
3338                 };
3339                 // Panic on failure to signal LDK should be restarted to retry signing the `ChannelUpdate`.
3340                 // If we returned an error and the `node_signer` cannot provide a signature for whatever
3341                 // reason`, we wouldn't be able to receive inbound payments through the corresponding
3342                 // channel.
3343                 let sig = self.node_signer.sign_gossip_message(msgs::UnsignedGossipMessage::ChannelUpdate(&unsigned)).unwrap();
3344
3345                 Ok(msgs::ChannelUpdate {
3346                         signature: sig,
3347                         contents: unsigned
3348                 })
3349         }
3350
3351         #[cfg(test)]
3352         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> {
3353                 let _lck = self.total_consistency_lock.read().unwrap();
3354                 self.send_payment_along_path(SendAlongPathArgs {
3355                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3356                         session_priv_bytes
3357                 })
3358         }
3359
3360         fn send_payment_along_path(&self, args: SendAlongPathArgs) -> Result<(), APIError> {
3361                 let SendAlongPathArgs {
3362                         path, payment_hash, recipient_onion, total_value, cur_height, payment_id, keysend_preimage,
3363                         session_priv_bytes
3364                 } = args;
3365                 // The top-level caller should hold the total_consistency_lock read lock.
3366                 debug_assert!(self.total_consistency_lock.try_write().is_err());
3367                 let prng_seed = self.entropy_source.get_secure_random_bytes();
3368                 let session_priv = SecretKey::from_slice(&session_priv_bytes[..]).expect("RNG is busted");
3369
3370                 let (onion_packet, htlc_msat, htlc_cltv) = onion_utils::create_payment_onion(
3371                         &self.secp_ctx, &path, &session_priv, total_value, recipient_onion, cur_height,
3372                         payment_hash, keysend_preimage, prng_seed
3373                 ).map_err(|e| {
3374                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3375                         log_error!(logger, "Failed to build an onion for path for payment hash {}", payment_hash);
3376                         e
3377                 })?;
3378
3379                 let err: Result<(), _> = loop {
3380                         let (counterparty_node_id, id) = match self.short_to_chan_info.read().unwrap().get(&path.hops.first().unwrap().short_channel_id) {
3381                                 None => {
3382                                         let logger = WithContext::from(&self.logger, Some(path.hops.first().unwrap().pubkey), None);
3383                                         log_error!(logger, "Failed to find first-hop for payment hash {}", payment_hash);
3384                                         return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()})
3385                                 },
3386                                 Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
3387                         };
3388
3389                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(id));
3390                         log_trace!(logger,
3391                                 "Attempting to send payment with payment hash {} along path with next hop {}",
3392                                 payment_hash, path.hops.first().unwrap().short_channel_id);
3393
3394                         let per_peer_state = self.per_peer_state.read().unwrap();
3395                         let peer_state_mutex = per_peer_state.get(&counterparty_node_id)
3396                                 .ok_or_else(|| APIError::ChannelUnavailable{err: "No peer matching the path's first hop found!".to_owned() })?;
3397                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3398                         let peer_state = &mut *peer_state_lock;
3399                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(id) {
3400                                 match chan_phase_entry.get_mut() {
3401                                         ChannelPhase::Funded(chan) => {
3402                                                 if !chan.context.is_live() {
3403                                                         return Err(APIError::ChannelUnavailable{err: "Peer for first hop currently disconnected".to_owned()});
3404                                                 }
3405                                                 let funding_txo = chan.context.get_funding_txo().unwrap();
3406                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3407                                                 let send_res = chan.send_htlc_and_commit(htlc_msat, payment_hash.clone(),
3408                                                         htlc_cltv, HTLCSource::OutboundRoute {
3409                                                                 path: path.clone(),
3410                                                                 session_priv: session_priv.clone(),
3411                                                                 first_hop_htlc_msat: htlc_msat,
3412                                                                 payment_id,
3413                                                         }, onion_packet, None, &self.fee_estimator, &&logger);
3414                                                 match break_chan_phase_entry!(self, send_res, chan_phase_entry) {
3415                                                         Some(monitor_update) => {
3416                                                                 match handle_new_monitor_update!(self, funding_txo, channel_id, monitor_update, peer_state_lock, peer_state, per_peer_state, chan) {
3417                                                                         false => {
3418                                                                                 // Note that MonitorUpdateInProgress here indicates (per function
3419                                                                                 // docs) that we will resend the commitment update once monitor
3420                                                                                 // updating completes. Therefore, we must return an error
3421                                                                                 // indicating that it is unsafe to retry the payment wholesale,
3422                                                                                 // which we do in the send_payment check for
3423                                                                                 // MonitorUpdateInProgress, below.
3424                                                                                 return Err(APIError::MonitorUpdateInProgress);
3425                                                                         },
3426                                                                         true => {},
3427                                                                 }
3428                                                         },
3429                                                         None => {},
3430                                                 }
3431                                         },
3432                                         _ => return Err(APIError::ChannelUnavailable{err: "Channel to first hop is unfunded".to_owned()}),
3433                                 };
3434                         } else {
3435                                 // The channel was likely removed after we fetched the id from the
3436                                 // `short_to_chan_info` map, but before we successfully locked the
3437                                 // `channel_by_id` map.
3438                                 // This can occur as no consistency guarantees exists between the two maps.
3439                                 return Err(APIError::ChannelUnavailable{err: "No channel available with first hop!".to_owned()});
3440                         }
3441                         return Ok(());
3442                 };
3443                 match handle_error!(self, err, path.hops.first().unwrap().pubkey) {
3444                         Ok(_) => unreachable!(),
3445                         Err(e) => {
3446                                 Err(APIError::ChannelUnavailable { err: e.err })
3447                         },
3448                 }
3449         }
3450
3451         /// Sends a payment along a given route.
3452         ///
3453         /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
3454         /// fields for more info.
3455         ///
3456         /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
3457         /// [`PeerManager::process_events`]).
3458         ///
3459         /// # Avoiding Duplicate Payments
3460         ///
3461         /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
3462         /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
3463         /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
3464         /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
3465         /// second payment with the same [`PaymentId`].
3466         ///
3467         /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
3468         /// tracking of payments, including state to indicate once a payment has completed. Because you
3469         /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
3470         /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
3471         /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
3472         ///
3473         /// Additionally, in the scenario where we begin the process of sending a payment, but crash
3474         /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
3475         /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
3476         /// [`ChannelManager::list_recent_payments`] for more information.
3477         ///
3478         /// # Possible Error States on [`PaymentSendFailure`]
3479         ///
3480         /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
3481         /// each entry matching the corresponding-index entry in the route paths, see
3482         /// [`PaymentSendFailure`] for more info.
3483         ///
3484         /// In general, a path may raise:
3485         ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
3486         ///    node public key) is specified.
3487         ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
3488         ///    closed, doesn't exist, or the peer is currently disconnected.
3489         ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
3490         ///    relevant updates.
3491         ///
3492         /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
3493         /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
3494         /// different route unless you intend to pay twice!
3495         ///
3496         /// [`RouteHop`]: crate::routing::router::RouteHop
3497         /// [`Event::PaymentSent`]: events::Event::PaymentSent
3498         /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
3499         /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
3500         /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
3501         /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
3502         pub fn send_payment_with_route(&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<(), PaymentSendFailure> {
3503                 let best_block_height = self.best_block.read().unwrap().height();
3504                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3505                 self.pending_outbound_payments
3506                         .send_payment_with_route(route, payment_hash, recipient_onion, payment_id,
3507                                 &self.entropy_source, &self.node_signer, best_block_height,
3508                                 |args| self.send_payment_along_path(args))
3509         }
3510
3511         /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
3512         /// `route_params` and retry failed payment paths based on `retry_strategy`.
3513         pub fn send_payment(&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId, route_params: RouteParameters, retry_strategy: Retry) -> Result<(), RetryableSendFailure> {
3514                 let best_block_height = self.best_block.read().unwrap().height();
3515                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3516                 self.pending_outbound_payments
3517                         .send_payment(payment_hash, recipient_onion, payment_id, retry_strategy, route_params,
3518                                 &self.router, self.list_usable_channels(), || self.compute_inflight_htlcs(),
3519                                 &self.entropy_source, &self.node_signer, best_block_height, &self.logger,
3520                                 &self.pending_events, |args| self.send_payment_along_path(args))
3521         }
3522
3523         #[cfg(test)]
3524         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> {
3525                 let best_block_height = self.best_block.read().unwrap().height();
3526                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3527                 self.pending_outbound_payments.test_send_payment_internal(route, payment_hash, recipient_onion,
3528                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs, &self.node_signer,
3529                         best_block_height, |args| self.send_payment_along_path(args))
3530         }
3531
3532         #[cfg(test)]
3533         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> {
3534                 let best_block_height = self.best_block.read().unwrap().height();
3535                 self.pending_outbound_payments.test_add_new_pending_payment(payment_hash, recipient_onion, payment_id, route, None, &self.entropy_source, best_block_height)
3536         }
3537
3538         #[cfg(test)]
3539         pub(crate) fn test_set_payment_metadata(&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>) {
3540                 self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
3541         }
3542
3543         pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3544                 let best_block_height = self.best_block.read().unwrap().height();
3545                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3546                 self.pending_outbound_payments
3547                         .send_payment_for_bolt12_invoice(
3548                                 invoice, payment_id, &self.router, self.list_usable_channels(),
3549                                 || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3550                                 best_block_height, &self.logger, &self.pending_events,
3551                                 |args| self.send_payment_along_path(args)
3552                         )
3553         }
3554
3555         /// Signals that no further attempts for the given payment should occur. Useful if you have a
3556         /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
3557         /// retries are exhausted.
3558         ///
3559         /// # Event Generation
3560         ///
3561         /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
3562         /// as there are no remaining pending HTLCs for this payment.
3563         ///
3564         /// Note that calling this method does *not* prevent a payment from succeeding. You must still
3565         /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
3566         /// determine the ultimate status of a payment.
3567         ///
3568         /// # Requested Invoices
3569         ///
3570         /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
3571         /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
3572         /// and prevent any attempts at paying it once received. The other events may only be generated
3573         /// once the invoice has been received.
3574         ///
3575         /// # Restart Behavior
3576         ///
3577         /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
3578         /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
3579         /// [`Event::InvoiceRequestFailed`].
3580         ///
3581         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3582         pub fn abandon_payment(&self, payment_id: PaymentId) {
3583                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3584                 self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
3585         }
3586
3587         /// Send a spontaneous payment, which is a payment that does not require the recipient to have
3588         /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
3589         /// the preimage, it must be a cryptographically secure random value that no intermediate node
3590         /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
3591         /// never reach the recipient.
3592         ///
3593         /// See [`send_payment`] documentation for more details on the return value of this function
3594         /// and idempotency guarantees provided by the [`PaymentId`] key.
3595         ///
3596         /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
3597         /// [`send_payment`] for more information about the risks of duplicate preimage usage.
3598         ///
3599         /// [`send_payment`]: Self::send_payment
3600         pub fn send_spontaneous_payment(&self, route: &Route, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields, payment_id: PaymentId) -> Result<PaymentHash, PaymentSendFailure> {
3601                 let best_block_height = self.best_block.read().unwrap().height();
3602                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3603                 self.pending_outbound_payments.send_spontaneous_payment_with_route(
3604                         route, payment_preimage, recipient_onion, payment_id, &self.entropy_source,
3605                         &self.node_signer, best_block_height, |args| self.send_payment_along_path(args))
3606         }
3607
3608         /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
3609         /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
3610         ///
3611         /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
3612         /// payments.
3613         ///
3614         /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
3615         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> {
3616                 let best_block_height = self.best_block.read().unwrap().height();
3617                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3618                 self.pending_outbound_payments.send_spontaneous_payment(payment_preimage, recipient_onion,
3619                         payment_id, retry_strategy, route_params, &self.router, self.list_usable_channels(),
3620                         || self.compute_inflight_htlcs(),  &self.entropy_source, &self.node_signer, best_block_height,
3621                         &self.logger, &self.pending_events, |args| self.send_payment_along_path(args))
3622         }
3623
3624         /// Send a payment that is probing the given route for liquidity. We calculate the
3625         /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
3626         /// us to easily discern them from real payments.
3627         pub fn send_probe(&self, path: Path) -> Result<(PaymentHash, PaymentId), PaymentSendFailure> {
3628                 let best_block_height = self.best_block.read().unwrap().height();
3629                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3630                 self.pending_outbound_payments.send_probe(path, self.probing_cookie_secret,
3631                         &self.entropy_source, &self.node_signer, best_block_height,
3632                         |args| self.send_payment_along_path(args))
3633         }
3634
3635         /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
3636         /// payment probe.
3637         #[cfg(test)]
3638         pub(crate) fn payment_is_probe(&self, payment_hash: &PaymentHash, payment_id: &PaymentId) -> bool {
3639                 outbound_payment::payment_is_probe(payment_hash, payment_id, self.probing_cookie_secret)
3640         }
3641
3642         /// Sends payment probes over all paths of a route that would be used to pay the given
3643         /// amount to the given `node_id`.
3644         ///
3645         /// See [`ChannelManager::send_preflight_probes`] for more information.
3646         pub fn send_spontaneous_preflight_probes(
3647                 &self, node_id: PublicKey, amount_msat: u64, final_cltv_expiry_delta: u32,
3648                 liquidity_limit_multiplier: Option<u64>,
3649         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3650                 let payment_params =
3651                         PaymentParameters::from_node_id(node_id, final_cltv_expiry_delta);
3652
3653                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, amount_msat);
3654
3655                 self.send_preflight_probes(route_params, liquidity_limit_multiplier)
3656         }
3657
3658         /// Sends payment probes over all paths of a route that would be used to pay a route found
3659         /// according to the given [`RouteParameters`].
3660         ///
3661         /// This may be used to send "pre-flight" probes, i.e., to train our scorer before conducting
3662         /// the actual payment. Note this is only useful if there likely is sufficient time for the
3663         /// probe to settle before sending out the actual payment, e.g., when waiting for user
3664         /// confirmation in a wallet UI.
3665         ///
3666         /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
3667         /// actual payment. Users should therefore be cautious and might avoid sending probes if
3668         /// liquidity is scarce and/or they don't expect the probe to return before they send the
3669         /// payment. To mitigate this issue, channels with available liquidity less than the required
3670         /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
3671         /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
3672         pub fn send_preflight_probes(
3673                 &self, route_params: RouteParameters, liquidity_limit_multiplier: Option<u64>,
3674         ) -> Result<Vec<(PaymentHash, PaymentId)>, ProbeSendFailure> {
3675                 let liquidity_limit_multiplier = liquidity_limit_multiplier.unwrap_or(3);
3676
3677                 let payer = self.get_our_node_id();
3678                 let usable_channels = self.list_usable_channels();
3679                 let first_hops = usable_channels.iter().collect::<Vec<_>>();
3680                 let inflight_htlcs = self.compute_inflight_htlcs();
3681
3682                 let route = self
3683                         .router
3684                         .find_route(&payer, &route_params, Some(&first_hops), inflight_htlcs)
3685                         .map_err(|e| {
3686                                 log_error!(self.logger, "Failed to find path for payment probe: {:?}", e);
3687                                 ProbeSendFailure::RouteNotFound
3688                         })?;
3689
3690                 let mut used_liquidity_map = HashMap::with_capacity(first_hops.len());
3691
3692                 let mut res = Vec::new();
3693
3694                 for mut path in route.paths {
3695                         // If the last hop is probably an unannounced channel we refrain from probing all the
3696                         // way through to the end and instead probe up to the second-to-last channel.
3697                         while let Some(last_path_hop) = path.hops.last() {
3698                                 if last_path_hop.maybe_announced_channel {
3699                                         // We found a potentially announced last hop.
3700                                         break;
3701                                 } else {
3702                                         // Drop the last hop, as it's likely unannounced.
3703                                         log_debug!(
3704                                                 self.logger,
3705                                                 "Avoided sending payment probe all the way to last hop {} as it is likely unannounced.",
3706                                                 last_path_hop.short_channel_id
3707                                         );
3708                                         let final_value_msat = path.final_value_msat();
3709                                         path.hops.pop();
3710                                         if let Some(new_last) = path.hops.last_mut() {
3711                                                 new_last.fee_msat += final_value_msat;
3712                                         }
3713                                 }
3714                         }
3715
3716                         if path.hops.len() < 2 {
3717                                 log_debug!(
3718                                         self.logger,
3719                                         "Skipped sending payment probe over path with less than two hops."
3720                                 );
3721                                 continue;
3722                         }
3723
3724                         if let Some(first_path_hop) = path.hops.first() {
3725                                 if let Some(first_hop) = first_hops.iter().find(|h| {
3726                                         h.get_outbound_payment_scid() == Some(first_path_hop.short_channel_id)
3727                                 }) {
3728                                         let path_value = path.final_value_msat() + path.fee_msat();
3729                                         let used_liquidity =
3730                                                 used_liquidity_map.entry(first_path_hop.short_channel_id).or_insert(0);
3731
3732                                         if first_hop.next_outbound_htlc_limit_msat
3733                                                 < (*used_liquidity + path_value) * liquidity_limit_multiplier
3734                                         {
3735                                                 log_debug!(self.logger, "Skipped sending payment probe to avoid putting channel {} under the liquidity limit.", first_path_hop.short_channel_id);
3736                                                 continue;
3737                                         } else {
3738                                                 *used_liquidity += path_value;
3739                                         }
3740                                 }
3741                         }
3742
3743                         res.push(self.send_probe(path).map_err(|e| {
3744                                 log_error!(self.logger, "Failed to send pre-flight probe: {:?}", e);
3745                                 ProbeSendFailure::SendingFailed(e)
3746                         })?);
3747                 }
3748
3749                 Ok(res)
3750         }
3751
3752         /// Handles the generation of a funding transaction, optionally (for tests) with a function
3753         /// which checks the correctness of the funding transaction given the associated channel.
3754         fn funding_transaction_generated_intern<FundingOutput: FnMut(&OutboundV1Channel<SP>, &Transaction) -> Result<OutPoint, APIError>>(
3755                 &self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, is_batch_funding: bool,
3756                 mut find_funding_output: FundingOutput,
3757         ) -> Result<(), APIError> {
3758                 let per_peer_state = self.per_peer_state.read().unwrap();
3759                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
3760                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
3761
3762                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
3763                 let peer_state = &mut *peer_state_lock;
3764                 let funding_txo;
3765                 let (mut chan, msg_opt) = match peer_state.channel_by_id.remove(temporary_channel_id) {
3766                         Some(ChannelPhase::UnfundedOutboundV1(mut chan)) => {
3767                                 funding_txo = find_funding_output(&chan, &funding_transaction)?;
3768
3769                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
3770                                 let funding_res = chan.get_funding_created(funding_transaction, funding_txo, is_batch_funding, &&logger)
3771                                         .map_err(|(mut chan, e)| if let ChannelError::Close(msg) = e {
3772                                                 let channel_id = chan.context.channel_id();
3773                                                 let reason = ClosureReason::ProcessingError { err: msg.clone() };
3774                                                 let shutdown_res = chan.context.force_shutdown(false, reason);
3775                                                 (chan, MsgHandleErrInternal::from_finish_shutdown(msg, channel_id, shutdown_res, None))
3776                                         } else { unreachable!(); });
3777                                 match funding_res {
3778                                         Ok(funding_msg) => (chan, funding_msg),
3779                                         Err((chan, err)) => {
3780                                                 mem::drop(peer_state_lock);
3781                                                 mem::drop(per_peer_state);
3782                                                 let _: Result<(), _> = handle_error!(self, Err(err), chan.context.get_counterparty_node_id());
3783                                                 return Err(APIError::ChannelUnavailable {
3784                                                         err: "Signer refused to sign the initial commitment transaction".to_owned()
3785                                                 });
3786                                         },
3787                                 }
3788                         },
3789                         Some(phase) => {
3790                                 peer_state.channel_by_id.insert(*temporary_channel_id, phase);
3791                                 return Err(APIError::APIMisuseError {
3792                                         err: format!(
3793                                                 "Channel with id {} for the passed counterparty node_id {} is not an unfunded, outbound V1 channel",
3794                                                 temporary_channel_id, counterparty_node_id),
3795                                 })
3796                         },
3797                         None => return Err(APIError::ChannelUnavailable {err: format!(
3798                                 "Channel with id {} not found for the passed counterparty node_id {}",
3799                                 temporary_channel_id, counterparty_node_id),
3800                                 }),
3801                 };
3802
3803                 if let Some(msg) = msg_opt {
3804                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
3805                                 node_id: chan.context.get_counterparty_node_id(),
3806                                 msg,
3807                         });
3808                 }
3809                 match peer_state.channel_by_id.entry(chan.context.channel_id()) {
3810                         hash_map::Entry::Occupied(_) => {
3811                                 panic!("Generated duplicate funding txid?");
3812                         },
3813                         hash_map::Entry::Vacant(e) => {
3814                                 let mut outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
3815                                 match outpoint_to_peer.entry(funding_txo) {
3816                                         hash_map::Entry::Vacant(e) => { e.insert(chan.context.get_counterparty_node_id()); },
3817                                         hash_map::Entry::Occupied(o) => {
3818                                                 let err = format!(
3819                                                         "An existing channel using outpoint {} is open with peer {}",
3820                                                         funding_txo, o.get()
3821                                                 );
3822                                                 mem::drop(outpoint_to_peer);
3823                                                 mem::drop(peer_state_lock);
3824                                                 mem::drop(per_peer_state);
3825                                                 let reason = ClosureReason::ProcessingError { err: err.clone() };
3826                                                 self.finish_close_channel(chan.context.force_shutdown(true, reason));
3827                                                 return Err(APIError::ChannelUnavailable { err });
3828                                         }
3829                                 }
3830                                 e.insert(ChannelPhase::UnfundedOutboundV1(chan));
3831                         }
3832                 }
3833                 Ok(())
3834         }
3835
3836         #[cfg(test)]
3837         pub(crate) fn funding_transaction_generated_unchecked(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction, output_index: u16) -> Result<(), APIError> {
3838                 self.funding_transaction_generated_intern(temporary_channel_id, counterparty_node_id, funding_transaction, false, |_, tx| {
3839                         Ok(OutPoint { txid: tx.txid(), index: output_index })
3840                 })
3841         }
3842
3843         /// Call this upon creation of a funding transaction for the given channel.
3844         ///
3845         /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
3846         /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
3847         ///
3848         /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
3849         /// across the p2p network.
3850         ///
3851         /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
3852         /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
3853         ///
3854         /// May panic if the output found in the funding transaction is duplicative with some other
3855         /// channel (note that this should be trivially prevented by using unique funding transaction
3856         /// keys per-channel).
3857         ///
3858         /// Do NOT broadcast the funding transaction yourself. When we have safely received our
3859         /// counterparty's signature the funding transaction will automatically be broadcast via the
3860         /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
3861         ///
3862         /// Note that this includes RBF or similar transaction replacement strategies - lightning does
3863         /// not currently support replacing a funding transaction on an existing channel. Instead,
3864         /// create a new channel with a conflicting funding transaction.
3865         ///
3866         /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
3867         /// the wallet software generating the funding transaction to apply anti-fee sniping as
3868         /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
3869         /// for more details.
3870         ///
3871         /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
3872         /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
3873         pub fn funding_transaction_generated(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, funding_transaction: Transaction) -> Result<(), APIError> {
3874                 self.batch_funding_transaction_generated(&[(temporary_channel_id, counterparty_node_id)], funding_transaction)
3875         }
3876
3877         /// Call this upon creation of a batch funding transaction for the given channels.
3878         ///
3879         /// Return values are identical to [`Self::funding_transaction_generated`], respective to
3880         /// each individual channel and transaction output.
3881         ///
3882         /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
3883         /// will only be broadcast when we have safely received and persisted the counterparty's
3884         /// signature for each channel.
3885         ///
3886         /// If there is an error, all channels in the batch are to be considered closed.
3887         pub fn batch_funding_transaction_generated(&self, temporary_channels: &[(&ChannelId, &PublicKey)], funding_transaction: Transaction) -> Result<(), APIError> {
3888                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3889                 let mut result = Ok(());
3890
3891                 if !funding_transaction.is_coin_base() {
3892                         for inp in funding_transaction.input.iter() {
3893                                 if inp.witness.is_empty() {
3894                                         result = result.and(Err(APIError::APIMisuseError {
3895                                                 err: "Funding transaction must be fully signed and spend Segwit outputs".to_owned()
3896                                         }));
3897                                 }
3898                         }
3899                 }
3900                 if funding_transaction.output.len() > u16::max_value() as usize {
3901                         result = result.and(Err(APIError::APIMisuseError {
3902                                 err: "Transaction had more than 2^16 outputs, which is not supported".to_owned()
3903                         }));
3904                 }
3905                 {
3906                         let height = self.best_block.read().unwrap().height();
3907                         // Transactions are evaluated as final by network mempools if their locktime is strictly
3908                         // lower than the next block height. However, the modules constituting our Lightning
3909                         // node might not have perfect sync about their blockchain views. Thus, if the wallet
3910                         // module is ahead of LDK, only allow one more block of headroom.
3911                         if !funding_transaction.input.iter().all(|input| input.sequence == Sequence::MAX) &&
3912                                 funding_transaction.lock_time.is_block_height() &&
3913                                 funding_transaction.lock_time.to_consensus_u32() > height + 1
3914                         {
3915                                 result = result.and(Err(APIError::APIMisuseError {
3916                                         err: "Funding transaction absolute timelock is non-final".to_owned()
3917                                 }));
3918                         }
3919                 }
3920
3921                 let txid = funding_transaction.txid();
3922                 let is_batch_funding = temporary_channels.len() > 1;
3923                 let mut funding_batch_states = if is_batch_funding {
3924                         Some(self.funding_batch_states.lock().unwrap())
3925                 } else {
3926                         None
3927                 };
3928                 let mut funding_batch_state = funding_batch_states.as_mut().and_then(|states| {
3929                         match states.entry(txid) {
3930                                 btree_map::Entry::Occupied(_) => {
3931                                         result = result.clone().and(Err(APIError::APIMisuseError {
3932                                                 err: "Batch funding transaction with the same txid already exists".to_owned()
3933                                         }));
3934                                         None
3935                                 },
3936                                 btree_map::Entry::Vacant(vacant) => Some(vacant.insert(Vec::new())),
3937                         }
3938                 });
3939                 for &(temporary_channel_id, counterparty_node_id) in temporary_channels {
3940                         result = result.and_then(|_| self.funding_transaction_generated_intern(
3941                                 temporary_channel_id,
3942                                 counterparty_node_id,
3943                                 funding_transaction.clone(),
3944                                 is_batch_funding,
3945                                 |chan, tx| {
3946                                         let mut output_index = None;
3947                                         let expected_spk = chan.context.get_funding_redeemscript().to_v0_p2wsh();
3948                                         for (idx, outp) in tx.output.iter().enumerate() {
3949                                                 if outp.script_pubkey == expected_spk && outp.value == chan.context.get_value_satoshis() {
3950                                                         if output_index.is_some() {
3951                                                                 return Err(APIError::APIMisuseError {
3952                                                                         err: "Multiple outputs matched the expected script and value".to_owned()
3953                                                                 });
3954                                                         }
3955                                                         output_index = Some(idx as u16);
3956                                                 }
3957                                         }
3958                                         if output_index.is_none() {
3959                                                 return Err(APIError::APIMisuseError {
3960                                                         err: "No output matched the script_pubkey and value in the FundingGenerationReady event".to_owned()
3961                                                 });
3962                                         }
3963                                         let outpoint = OutPoint { txid: tx.txid(), index: output_index.unwrap() };
3964                                         if let Some(funding_batch_state) = funding_batch_state.as_mut() {
3965                                                 // TODO(dual_funding): We only do batch funding for V1 channels at the moment, but we'll probably
3966                                                 // need to fix this somehow to not rely on using the outpoint for the channel ID if we
3967                                                 // want to support V2 batching here as well.
3968                                                 funding_batch_state.push((ChannelId::v1_from_funding_outpoint(outpoint), *counterparty_node_id, false));
3969                                         }
3970                                         Ok(outpoint)
3971                                 })
3972                         );
3973                 }
3974                 if let Err(ref e) = result {
3975                         // Remaining channels need to be removed on any error.
3976                         let e = format!("Error in transaction funding: {:?}", e);
3977                         let mut channels_to_remove = Vec::new();
3978                         channels_to_remove.extend(funding_batch_states.as_mut()
3979                                 .and_then(|states| states.remove(&txid))
3980                                 .into_iter().flatten()
3981                                 .map(|(chan_id, node_id, _state)| (chan_id, node_id))
3982                         );
3983                         channels_to_remove.extend(temporary_channels.iter()
3984                                 .map(|(&chan_id, &node_id)| (chan_id, node_id))
3985                         );
3986                         let mut shutdown_results = Vec::new();
3987                         {
3988                                 let per_peer_state = self.per_peer_state.read().unwrap();
3989                                 for (channel_id, counterparty_node_id) in channels_to_remove {
3990                                         per_peer_state.get(&counterparty_node_id)
3991                                                 .map(|peer_state_mutex| peer_state_mutex.lock().unwrap())
3992                                                 .and_then(|mut peer_state| peer_state.channel_by_id.remove(&channel_id))
3993                                                 .map(|mut chan| {
3994                                                         update_maps_on_chan_removal!(self, &chan.context());
3995                                                         let closure_reason = ClosureReason::ProcessingError { err: e.clone() };
3996                                                         shutdown_results.push(chan.context_mut().force_shutdown(false, closure_reason));
3997                                                 });
3998                                 }
3999                         }
4000                         mem::drop(funding_batch_states);
4001                         for shutdown_result in shutdown_results.drain(..) {
4002                                 self.finish_close_channel(shutdown_result);
4003                         }
4004                 }
4005                 result
4006         }
4007
4008         /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
4009         ///
4010         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4011         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4012         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4013         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4014         ///
4015         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4016         /// `counterparty_node_id` is provided.
4017         ///
4018         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4019         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4020         ///
4021         /// If an error is returned, none of the updates should be considered applied.
4022         ///
4023         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4024         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4025         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4026         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4027         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4028         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4029         /// [`APIMisuseError`]: APIError::APIMisuseError
4030         pub fn update_partial_channel_config(
4031                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config_update: &ChannelConfigUpdate,
4032         ) -> Result<(), APIError> {
4033                 if config_update.cltv_expiry_delta.map(|delta| delta < MIN_CLTV_EXPIRY_DELTA).unwrap_or(false) {
4034                         return Err(APIError::APIMisuseError {
4035                                 err: format!("The chosen CLTV expiry delta is below the minimum of {}", MIN_CLTV_EXPIRY_DELTA),
4036                         });
4037                 }
4038
4039                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4040                 let per_peer_state = self.per_peer_state.read().unwrap();
4041                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
4042                         .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id) })?;
4043                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4044                 let peer_state = &mut *peer_state_lock;
4045
4046                 for channel_id in channel_ids {
4047                         if !peer_state.has_channel(channel_id) {
4048                                 return Err(APIError::ChannelUnavailable {
4049                                         err: format!("Channel with id {} not found for the passed counterparty node_id {}", channel_id, counterparty_node_id),
4050                                 });
4051                         };
4052                 }
4053                 for channel_id in channel_ids {
4054                         if let Some(channel_phase) = peer_state.channel_by_id.get_mut(channel_id) {
4055                                 let mut config = channel_phase.context().config();
4056                                 config.apply(config_update);
4057                                 if !channel_phase.context_mut().update_config(&config) {
4058                                         continue;
4059                                 }
4060                                 if let ChannelPhase::Funded(channel) = channel_phase {
4061                                         if let Ok(msg) = self.get_channel_update_for_broadcast(channel) {
4062                                                 let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
4063                                                 pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate { msg });
4064                                         } else if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
4065                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
4066                                                         node_id: channel.context.get_counterparty_node_id(),
4067                                                         msg,
4068                                                 });
4069                                         }
4070                                 }
4071                                 continue;
4072                         } else {
4073                                 // This should not be reachable as we've already checked for non-existence in the previous channel_id loop.
4074                                 debug_assert!(false);
4075                                 return Err(APIError::ChannelUnavailable {
4076                                         err: format!(
4077                                                 "Channel with ID {} for passed counterparty_node_id {} disappeared after we confirmed its existence - this should not be reachable!",
4078                                                 channel_id, counterparty_node_id),
4079                                 });
4080                         };
4081                 }
4082                 Ok(())
4083         }
4084
4085         /// Atomically updates the [`ChannelConfig`] for the given channels.
4086         ///
4087         /// Once the updates are applied, each eligible channel (advertised with a known short channel
4088         /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
4089         /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
4090         /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
4091         ///
4092         /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
4093         /// `counterparty_node_id` is provided.
4094         ///
4095         /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
4096         /// below [`MIN_CLTV_EXPIRY_DELTA`].
4097         ///
4098         /// If an error is returned, none of the updates should be considered applied.
4099         ///
4100         /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
4101         /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
4102         /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
4103         /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
4104         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4105         /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
4106         /// [`APIMisuseError`]: APIError::APIMisuseError
4107         pub fn update_channel_config(
4108                 &self, counterparty_node_id: &PublicKey, channel_ids: &[ChannelId], config: &ChannelConfig,
4109         ) -> Result<(), APIError> {
4110                 return self.update_partial_channel_config(counterparty_node_id, channel_ids, &(*config).into());
4111         }
4112
4113         /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
4114         /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
4115         ///
4116         /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
4117         /// channel to a receiving node if the node lacks sufficient inbound liquidity.
4118         ///
4119         /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
4120         /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
4121         /// receiver's invoice route hints. These route hints will signal to LDK to generate an
4122         /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
4123         /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
4124         ///
4125         /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
4126         /// you from forwarding more than you received. See
4127         /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
4128         /// than expected.
4129         ///
4130         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4131         /// backwards.
4132         ///
4133         /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
4134         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4135         /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
4136         // TODO: when we move to deciding the best outbound channel at forward time, only take
4137         // `next_node_id` and not `next_hop_channel_id`
4138         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> {
4139                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4140
4141                 let next_hop_scid = {
4142                         let peer_state_lock = self.per_peer_state.read().unwrap();
4143                         let peer_state_mutex = peer_state_lock.get(&next_node_id)
4144                                 .ok_or_else(|| APIError::ChannelUnavailable { err: format!("Can't find a peer matching the passed counterparty node_id {}", next_node_id) })?;
4145                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4146                         let peer_state = &mut *peer_state_lock;
4147                         match peer_state.channel_by_id.get(next_hop_channel_id) {
4148                                 Some(ChannelPhase::Funded(chan)) => {
4149                                         if !chan.context.is_usable() {
4150                                                 return Err(APIError::ChannelUnavailable {
4151                                                         err: format!("Channel with id {} not fully established", next_hop_channel_id)
4152                                                 })
4153                                         }
4154                                         chan.context.get_short_channel_id().unwrap_or(chan.context.outbound_scid_alias())
4155                                 },
4156                                 Some(_) => return Err(APIError::ChannelUnavailable {
4157                                         err: format!("Channel with id {} for the passed counterparty node_id {} is still opening.",
4158                                                 next_hop_channel_id, next_node_id)
4159                                 }),
4160                                 None => {
4161                                         let error = format!("Channel with id {} not found for the passed counterparty node_id {}",
4162                                                 next_hop_channel_id, next_node_id);
4163                                         let logger = WithContext::from(&self.logger, Some(next_node_id), Some(*next_hop_channel_id));
4164                                         log_error!(logger, "{} when attempting to forward intercepted HTLC", error);
4165                                         return Err(APIError::ChannelUnavailable {
4166                                                 err: error
4167                                         })
4168                                 }
4169                         }
4170                 };
4171
4172                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4173                         .ok_or_else(|| APIError::APIMisuseError {
4174                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4175                         })?;
4176
4177                 let routing = match payment.forward_info.routing {
4178                         PendingHTLCRouting::Forward { onion_packet, blinded, .. } => {
4179                                 PendingHTLCRouting::Forward {
4180                                         onion_packet, blinded, short_channel_id: next_hop_scid
4181                                 }
4182                         },
4183                         _ => unreachable!() // Only `PendingHTLCRouting::Forward`s are intercepted
4184                 };
4185                 let skimmed_fee_msat =
4186                         payment.forward_info.outgoing_amt_msat.saturating_sub(amt_to_forward_msat);
4187                 let pending_htlc_info = PendingHTLCInfo {
4188                         skimmed_fee_msat: if skimmed_fee_msat == 0 { None } else { Some(skimmed_fee_msat) },
4189                         outgoing_amt_msat: amt_to_forward_msat, routing, ..payment.forward_info
4190                 };
4191
4192                 let mut per_source_pending_forward = [(
4193                         payment.prev_short_channel_id,
4194                         payment.prev_funding_outpoint,
4195                         payment.prev_channel_id,
4196                         payment.prev_user_channel_id,
4197                         vec![(pending_htlc_info, payment.prev_htlc_id)]
4198                 )];
4199                 self.forward_htlcs(&mut per_source_pending_forward);
4200                 Ok(())
4201         }
4202
4203         /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
4204         /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
4205         ///
4206         /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
4207         /// backwards.
4208         ///
4209         /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
4210         pub fn fail_intercepted_htlc(&self, intercept_id: InterceptId) -> Result<(), APIError> {
4211                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4212
4213                 let payment = self.pending_intercepted_htlcs.lock().unwrap().remove(&intercept_id)
4214                         .ok_or_else(|| APIError::APIMisuseError {
4215                                 err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0))
4216                         })?;
4217
4218                 if let PendingHTLCRouting::Forward { short_channel_id, .. } = payment.forward_info.routing {
4219                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4220                                 short_channel_id: payment.prev_short_channel_id,
4221                                 user_channel_id: Some(payment.prev_user_channel_id),
4222                                 outpoint: payment.prev_funding_outpoint,
4223                                 channel_id: payment.prev_channel_id,
4224                                 htlc_id: payment.prev_htlc_id,
4225                                 incoming_packet_shared_secret: payment.forward_info.incoming_shared_secret,
4226                                 phantom_shared_secret: None,
4227                                 blinded_failure: payment.forward_info.routing.blinded_failure(),
4228                         });
4229
4230                         let failure_reason = HTLCFailReason::from_failure_code(0x4000 | 10);
4231                         let destination = HTLCDestination::UnknownNextHop { requested_forward_scid: short_channel_id };
4232                         self.fail_htlc_backwards_internal(&htlc_source, &payment.forward_info.payment_hash, &failure_reason, destination);
4233                 } else { unreachable!() } // Only `PendingHTLCRouting::Forward`s are intercepted
4234
4235                 Ok(())
4236         }
4237
4238         /// Processes HTLCs which are pending waiting on random forward delay.
4239         ///
4240         /// Should only really ever be called in response to a PendingHTLCsForwardable event.
4241         /// Will likely generate further events.
4242         pub fn process_pending_htlc_forwards(&self) {
4243                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
4244
4245                 let mut new_events = VecDeque::new();
4246                 let mut failed_forwards = Vec::new();
4247                 let mut phantom_receives: Vec<(u64, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)> = Vec::new();
4248                 {
4249                         let mut forward_htlcs = HashMap::new();
4250                         mem::swap(&mut forward_htlcs, &mut self.forward_htlcs.lock().unwrap());
4251
4252                         for (short_chan_id, mut pending_forwards) in forward_htlcs {
4253                                 if short_chan_id != 0 {
4254                                         let mut forwarding_counterparty = None;
4255                                         macro_rules! forwarding_channel_not_found {
4256                                                 () => {
4257                                                         for forward_info in pending_forwards.drain(..) {
4258                                                                 match forward_info {
4259                                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4260                                                                                 prev_short_channel_id, prev_htlc_id, prev_channel_id, prev_funding_outpoint,
4261                                                                                 prev_user_channel_id, forward_info: PendingHTLCInfo {
4262                                                                                         routing, incoming_shared_secret, payment_hash, outgoing_amt_msat,
4263                                                                                         outgoing_cltv_value, ..
4264                                                                                 }
4265                                                                         }) => {
4266                                                                                 macro_rules! failure_handler {
4267                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr, $next_hop_unknown: expr) => {
4268                                                                                                 let logger = WithContext::from(&self.logger, forwarding_counterparty, Some(prev_channel_id));
4269                                                                                                 log_info!(logger, "Failed to accept/forward incoming HTLC: {}", $msg);
4270
4271                                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4272                                                                                                         short_channel_id: prev_short_channel_id,
4273                                                                                                         user_channel_id: Some(prev_user_channel_id),
4274                                                                                                         channel_id: prev_channel_id,
4275                                                                                                         outpoint: prev_funding_outpoint,
4276                                                                                                         htlc_id: prev_htlc_id,
4277                                                                                                         incoming_packet_shared_secret: incoming_shared_secret,
4278                                                                                                         phantom_shared_secret: $phantom_ss,
4279                                                                                                         blinded_failure: routing.blinded_failure(),
4280                                                                                                 });
4281
4282                                                                                                 let reason = if $next_hop_unknown {
4283                                                                                                         HTLCDestination::UnknownNextHop { requested_forward_scid: short_chan_id }
4284                                                                                                 } else {
4285                                                                                                         HTLCDestination::FailedPayment{ payment_hash }
4286                                                                                                 };
4287
4288                                                                                                 failed_forwards.push((htlc_source, payment_hash,
4289                                                                                                         HTLCFailReason::reason($err_code, $err_data),
4290                                                                                                         reason
4291                                                                                                 ));
4292                                                                                                 continue;
4293                                                                                         }
4294                                                                                 }
4295                                                                                 macro_rules! fail_forward {
4296                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4297                                                                                                 {
4298                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, true);
4299                                                                                                 }
4300                                                                                         }
4301                                                                                 }
4302                                                                                 macro_rules! failed_payment {
4303                                                                                         ($msg: expr, $err_code: expr, $err_data: expr, $phantom_ss: expr) => {
4304                                                                                                 {
4305                                                                                                         failure_handler!($msg, $err_code, $err_data, $phantom_ss, false);
4306                                                                                                 }
4307                                                                                         }
4308                                                                                 }
4309                                                                                 if let PendingHTLCRouting::Forward { ref onion_packet, .. } = routing {
4310                                                                                         let phantom_pubkey_res = self.node_signer.get_node_id(Recipient::PhantomNode);
4311                                                                                         if phantom_pubkey_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id, &self.chain_hash) {
4312                                                                                                 let phantom_shared_secret = self.node_signer.ecdh(Recipient::PhantomNode, &onion_packet.public_key.unwrap(), None).unwrap().secret_bytes();
4313                                                                                                 let next_hop = match onion_utils::decode_next_payment_hop(
4314                                                                                                         phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac,
4315                                                                                                         payment_hash, None, &self.node_signer
4316                                                                                                 ) {
4317                                                                                                         Ok(res) => res,
4318                                                                                                         Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
4319                                                                                                                 let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).to_byte_array();
4320                                                                                                                 // In this scenario, the phantom would have sent us an
4321                                                                                                                 // `update_fail_malformed_htlc`, meaning here we encrypt the error as
4322                                                                                                                 // if it came from us (the second-to-last hop) but contains the sha256
4323                                                                                                                 // of the onion.
4324                                                                                                                 failed_payment!(err_msg, err_code, sha256_of_onion.to_vec(), None);
4325                                                                                                         },
4326                                                                                                         Err(onion_utils::OnionDecodeErr::Relay { err_msg, err_code }) => {
4327                                                                                                                 failed_payment!(err_msg, err_code, Vec::new(), Some(phantom_shared_secret));
4328                                                                                                         },
4329                                                                                                 };
4330                                                                                                 match next_hop {
4331                                                                                                         onion_utils::Hop::Receive(hop_data) => {
4332                                                                                                                 let current_height: u32 = self.best_block.read().unwrap().height();
4333                                                                                                                 match create_recv_pending_htlc_info(hop_data,
4334                                                                                                                         incoming_shared_secret, payment_hash, outgoing_amt_msat,
4335                                                                                                                         outgoing_cltv_value, Some(phantom_shared_secret), false, None,
4336                                                                                                                         current_height, self.default_configuration.accept_mpp_keysend)
4337                                                                                                                 {
4338                                                                                                                         Ok(info) => phantom_receives.push((prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_user_channel_id, vec![(info, prev_htlc_id)])),
4339                                                                                                                         Err(InboundHTLCErr { err_code, err_data, msg }) => failed_payment!(msg, err_code, err_data, Some(phantom_shared_secret))
4340                                                                                                                 }
4341                                                                                                         },
4342                                                                                                         _ => panic!(),
4343                                                                                                 }
4344                                                                                         } else {
4345                                                                                                 fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4346                                                                                         }
4347                                                                                 } else {
4348                                                                                         fail_forward!(format!("Unknown short channel id {} for forward HTLC", short_chan_id), 0x4000 | 10, Vec::new(), None);
4349                                                                                 }
4350                                                                         },
4351                                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4352                                                                                 // Channel went away before we could fail it. This implies
4353                                                                                 // the channel is now on chain and our counterparty is
4354                                                                                 // trying to broadcast the HTLC-Timeout, but that's their
4355                                                                                 // problem, not ours.
4356                                                                         }
4357                                                                 }
4358                                                         }
4359                                                 }
4360                                         }
4361                                         let chan_info_opt = self.short_to_chan_info.read().unwrap().get(&short_chan_id).cloned();
4362                                         let (counterparty_node_id, forward_chan_id) = match chan_info_opt {
4363                                                 Some((cp_id, chan_id)) => (cp_id, chan_id),
4364                                                 None => {
4365                                                         forwarding_channel_not_found!();
4366                                                         continue;
4367                                                 }
4368                                         };
4369                                         forwarding_counterparty = Some(counterparty_node_id);
4370                                         let per_peer_state = self.per_peer_state.read().unwrap();
4371                                         let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
4372                                         if peer_state_mutex_opt.is_none() {
4373                                                 forwarding_channel_not_found!();
4374                                                 continue;
4375                                         }
4376                                         let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
4377                                         let peer_state = &mut *peer_state_lock;
4378                                         if let Some(ChannelPhase::Funded(ref mut chan)) = peer_state.channel_by_id.get_mut(&forward_chan_id) {
4379                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4380                                                 for forward_info in pending_forwards.drain(..) {
4381                                                         let queue_fail_htlc_res = match forward_info {
4382                                                                 HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4383                                                                         prev_short_channel_id, prev_htlc_id, prev_channel_id, prev_funding_outpoint,
4384                                                                         prev_user_channel_id, forward_info: PendingHTLCInfo {
4385                                                                                 incoming_shared_secret, payment_hash, outgoing_amt_msat, outgoing_cltv_value,
4386                                                                                 routing: PendingHTLCRouting::Forward {
4387                                                                                         onion_packet, blinded, ..
4388                                                                                 }, skimmed_fee_msat, ..
4389                                                                         },
4390                                                                 }) => {
4391                                                                         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);
4392                                                                         let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
4393                                                                                 short_channel_id: prev_short_channel_id,
4394                                                                                 user_channel_id: Some(prev_user_channel_id),
4395                                                                                 channel_id: prev_channel_id,
4396                                                                                 outpoint: prev_funding_outpoint,
4397                                                                                 htlc_id: prev_htlc_id,
4398                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4399                                                                                 // Phantom payments are only PendingHTLCRouting::Receive.
4400                                                                                 phantom_shared_secret: None,
4401                                                                                 blinded_failure: blinded.map(|b| b.failure),
4402                                                                         });
4403                                                                         let next_blinding_point = blinded.and_then(|b| {
4404                                                                                 let encrypted_tlvs_ss = self.node_signer.ecdh(
4405                                                                                         Recipient::Node, &b.inbound_blinding_point, None
4406                                                                                 ).unwrap().secret_bytes();
4407                                                                                 onion_utils::next_hop_pubkey(
4408                                                                                         &self.secp_ctx, b.inbound_blinding_point, &encrypted_tlvs_ss
4409                                                                                 ).ok()
4410                                                                         });
4411                                                                         if let Err(e) = chan.queue_add_htlc(outgoing_amt_msat,
4412                                                                                 payment_hash, outgoing_cltv_value, htlc_source.clone(),
4413                                                                                 onion_packet, skimmed_fee_msat, next_blinding_point, &self.fee_estimator,
4414                                                                                 &&logger)
4415                                                                         {
4416                                                                                 if let ChannelError::Ignore(msg) = e {
4417                                                                                         log_trace!(logger, "Failed to forward HTLC with payment_hash {}: {}", &payment_hash, msg);
4418                                                                                 } else {
4419                                                                                         panic!("Stated return value requirements in send_htlc() were not met");
4420                                                                                 }
4421                                                                                 let (failure_code, data) = self.get_htlc_temp_fail_err_and_data(0x1000|7, short_chan_id, chan);
4422                                                                                 failed_forwards.push((htlc_source, payment_hash,
4423                                                                                         HTLCFailReason::reason(failure_code, data),
4424                                                                                         HTLCDestination::NextHopChannel { node_id: Some(chan.context.get_counterparty_node_id()), channel_id: forward_chan_id }
4425                                                                                 ));
4426                                                                                 continue;
4427                                                                         }
4428                                                                         None
4429                                                                 },
4430                                                                 HTLCForwardInfo::AddHTLC { .. } => {
4431                                                                         panic!("short_channel_id != 0 should imply any pending_forward entries are of type Forward");
4432                                                                 },
4433                                                                 HTLCForwardInfo::FailHTLC { htlc_id, err_packet } => {
4434                                                                         log_trace!(logger, "Failing HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4435                                                                         Some((chan.queue_fail_htlc(htlc_id, err_packet, &&logger), htlc_id))
4436                                                                 },
4437                                                                 HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
4438                                                                         log_trace!(logger, "Failing malformed HTLC back to channel with short id {} (backward HTLC ID {}) after delay", short_chan_id, htlc_id);
4439                                                                         let res = chan.queue_fail_malformed_htlc(
4440                                                                                 htlc_id, failure_code, sha256_of_onion, &&logger
4441                                                                         );
4442                                                                         Some((res, htlc_id))
4443                                                                 },
4444                                                         };
4445                                                         if let Some((queue_fail_htlc_res, htlc_id)) = queue_fail_htlc_res {
4446                                                                 if let Err(e) = queue_fail_htlc_res {
4447                                                                         if let ChannelError::Ignore(msg) = e {
4448                                                                                 log_trace!(logger, "Failed to fail HTLC with ID {} backwards to short_id {}: {}", htlc_id, short_chan_id, msg);
4449                                                                         } else {
4450                                                                                 panic!("Stated return value requirements in queue_fail_{{malformed_}}htlc() were not met");
4451                                                                         }
4452                                                                         // fail-backs are best-effort, we probably already have one
4453                                                                         // pending, and if not that's OK, if not, the channel is on
4454                                                                         // the chain and sending the HTLC-Timeout is their problem.
4455                                                                         continue;
4456                                                                 }
4457                                                         }
4458                                                 }
4459                                         } else {
4460                                                 forwarding_channel_not_found!();
4461                                                 continue;
4462                                         }
4463                                 } else {
4464                                         'next_forwardable_htlc: for forward_info in pending_forwards.drain(..) {
4465                                                 match forward_info {
4466                                                         HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
4467                                                                 prev_short_channel_id, prev_htlc_id, prev_channel_id, prev_funding_outpoint,
4468                                                                 prev_user_channel_id, forward_info: PendingHTLCInfo {
4469                                                                         routing, incoming_shared_secret, payment_hash, incoming_amt_msat, outgoing_amt_msat,
4470                                                                         skimmed_fee_msat, ..
4471                                                                 }
4472                                                         }) => {
4473                                                                 let blinded_failure = routing.blinded_failure();
4474                                                                 let (cltv_expiry, onion_payload, payment_data, phantom_shared_secret, mut onion_fields) = match routing {
4475                                                                         PendingHTLCRouting::Receive {
4476                                                                                 payment_data, payment_metadata, incoming_cltv_expiry, phantom_shared_secret,
4477                                                                                 custom_tlvs, requires_blinded_error: _
4478                                                                         } => {
4479                                                                                 let _legacy_hop_data = Some(payment_data.clone());
4480                                                                                 let onion_fields = RecipientOnionFields { payment_secret: Some(payment_data.payment_secret),
4481                                                                                                 payment_metadata, custom_tlvs };
4482                                                                                 (incoming_cltv_expiry, OnionPayload::Invoice { _legacy_hop_data },
4483                                                                                         Some(payment_data), phantom_shared_secret, onion_fields)
4484                                                                         },
4485                                                                         PendingHTLCRouting::ReceiveKeysend { payment_data, payment_preimage, payment_metadata, incoming_cltv_expiry, custom_tlvs } => {
4486                                                                                 let onion_fields = RecipientOnionFields {
4487                                                                                         payment_secret: payment_data.as_ref().map(|data| data.payment_secret),
4488                                                                                         payment_metadata,
4489                                                                                         custom_tlvs,
4490                                                                                 };
4491                                                                                 (incoming_cltv_expiry, OnionPayload::Spontaneous(payment_preimage),
4492                                                                                         payment_data, None, onion_fields)
4493                                                                         },
4494                                                                         _ => {
4495                                                                                 panic!("short_channel_id == 0 should imply any pending_forward entries are of type Receive");
4496                                                                         }
4497                                                                 };
4498                                                                 let claimable_htlc = ClaimableHTLC {
4499                                                                         prev_hop: HTLCPreviousHopData {
4500                                                                                 short_channel_id: prev_short_channel_id,
4501                                                                                 user_channel_id: Some(prev_user_channel_id),
4502                                                                                 channel_id: prev_channel_id,
4503                                                                                 outpoint: prev_funding_outpoint,
4504                                                                                 htlc_id: prev_htlc_id,
4505                                                                                 incoming_packet_shared_secret: incoming_shared_secret,
4506                                                                                 phantom_shared_secret,
4507                                                                                 blinded_failure,
4508                                                                         },
4509                                                                         // We differentiate the received value from the sender intended value
4510                                                                         // if possible so that we don't prematurely mark MPP payments complete
4511                                                                         // if routing nodes overpay
4512                                                                         value: incoming_amt_msat.unwrap_or(outgoing_amt_msat),
4513                                                                         sender_intended_value: outgoing_amt_msat,
4514                                                                         timer_ticks: 0,
4515                                                                         total_value_received: None,
4516                                                                         total_msat: if let Some(data) = &payment_data { data.total_msat } else { outgoing_amt_msat },
4517                                                                         cltv_expiry,
4518                                                                         onion_payload,
4519                                                                         counterparty_skimmed_fee_msat: skimmed_fee_msat,
4520                                                                 };
4521
4522                                                                 let mut committed_to_claimable = false;
4523
4524                                                                 macro_rules! fail_htlc {
4525                                                                         ($htlc: expr, $payment_hash: expr) => {
4526                                                                                 debug_assert!(!committed_to_claimable);
4527                                                                                 let mut htlc_msat_height_data = $htlc.value.to_be_bytes().to_vec();
4528                                                                                 htlc_msat_height_data.extend_from_slice(
4529                                                                                         &self.best_block.read().unwrap().height().to_be_bytes(),
4530                                                                                 );
4531                                                                                 failed_forwards.push((HTLCSource::PreviousHopData(HTLCPreviousHopData {
4532                                                                                                 short_channel_id: $htlc.prev_hop.short_channel_id,
4533                                                                                                 user_channel_id: $htlc.prev_hop.user_channel_id,
4534                                                                                                 channel_id: prev_channel_id,
4535                                                                                                 outpoint: prev_funding_outpoint,
4536                                                                                                 htlc_id: $htlc.prev_hop.htlc_id,
4537                                                                                                 incoming_packet_shared_secret: $htlc.prev_hop.incoming_packet_shared_secret,
4538                                                                                                 phantom_shared_secret,
4539                                                                                                 blinded_failure,
4540                                                                                         }), payment_hash,
4541                                                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
4542                                                                                         HTLCDestination::FailedPayment { payment_hash: $payment_hash },
4543                                                                                 ));
4544                                                                                 continue 'next_forwardable_htlc;
4545                                                                         }
4546                                                                 }
4547                                                                 let phantom_shared_secret = claimable_htlc.prev_hop.phantom_shared_secret;
4548                                                                 let mut receiver_node_id = self.our_network_pubkey;
4549                                                                 if phantom_shared_secret.is_some() {
4550                                                                         receiver_node_id = self.node_signer.get_node_id(Recipient::PhantomNode)
4551                                                                                 .expect("Failed to get node_id for phantom node recipient");
4552                                                                 }
4553
4554                                                                 macro_rules! check_total_value {
4555                                                                         ($purpose: expr) => {{
4556                                                                                 let mut payment_claimable_generated = false;
4557                                                                                 let is_keysend = match $purpose {
4558                                                                                         events::PaymentPurpose::SpontaneousPayment(_) => true,
4559                                                                                         events::PaymentPurpose::InvoicePayment { .. } => false,
4560                                                                                 };
4561                                                                                 let mut claimable_payments = self.claimable_payments.lock().unwrap();
4562                                                                                 if claimable_payments.pending_claiming_payments.contains_key(&payment_hash) {
4563                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4564                                                                                 }
4565                                                                                 let ref mut claimable_payment = claimable_payments.claimable_payments
4566                                                                                         .entry(payment_hash)
4567                                                                                         // Note that if we insert here we MUST NOT fail_htlc!()
4568                                                                                         .or_insert_with(|| {
4569                                                                                                 committed_to_claimable = true;
4570                                                                                                 ClaimablePayment {
4571                                                                                                         purpose: $purpose.clone(), htlcs: Vec::new(), onion_fields: None,
4572                                                                                                 }
4573                                                                                         });
4574                                                                                 if $purpose != claimable_payment.purpose {
4575                                                                                         let log_keysend = |keysend| if keysend { "keysend" } else { "non-keysend" };
4576                                                                                         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));
4577                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4578                                                                                 }
4579                                                                                 if !self.default_configuration.accept_mpp_keysend && is_keysend && !claimable_payment.htlcs.is_empty() {
4580                                                                                         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);
4581                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4582                                                                                 }
4583                                                                                 if let Some(earlier_fields) = &mut claimable_payment.onion_fields {
4584                                                                                         if earlier_fields.check_merge(&mut onion_fields).is_err() {
4585                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4586                                                                                         }
4587                                                                                 } else {
4588                                                                                         claimable_payment.onion_fields = Some(onion_fields);
4589                                                                                 }
4590                                                                                 let ref mut htlcs = &mut claimable_payment.htlcs;
4591                                                                                 let mut total_value = claimable_htlc.sender_intended_value;
4592                                                                                 let mut earliest_expiry = claimable_htlc.cltv_expiry;
4593                                                                                 for htlc in htlcs.iter() {
4594                                                                                         total_value += htlc.sender_intended_value;
4595                                                                                         earliest_expiry = cmp::min(earliest_expiry, htlc.cltv_expiry);
4596                                                                                         if htlc.total_msat != claimable_htlc.total_msat {
4597                                                                                                 log_trace!(self.logger, "Failing HTLCs with payment_hash {} as the HTLCs had inconsistent total values (eg {} and {})",
4598                                                                                                         &payment_hash, claimable_htlc.total_msat, htlc.total_msat);
4599                                                                                                 total_value = msgs::MAX_VALUE_MSAT;
4600                                                                                         }
4601                                                                                         if total_value >= msgs::MAX_VALUE_MSAT { break; }
4602                                                                                 }
4603                                                                                 // The condition determining whether an MPP is complete must
4604                                                                                 // match exactly the condition used in `timer_tick_occurred`
4605                                                                                 if total_value >= msgs::MAX_VALUE_MSAT {
4606                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4607                                                                                 } else if total_value - claimable_htlc.sender_intended_value >= claimable_htlc.total_msat {
4608                                                                                         log_trace!(self.logger, "Failing HTLC with payment_hash {} as payment is already claimable",
4609                                                                                                 &payment_hash);
4610                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4611                                                                                 } else if total_value >= claimable_htlc.total_msat {
4612                                                                                         #[allow(unused_assignments)] {
4613                                                                                                 committed_to_claimable = true;
4614                                                                                         }
4615                                                                                         htlcs.push(claimable_htlc);
4616                                                                                         let amount_msat = htlcs.iter().map(|htlc| htlc.value).sum();
4617                                                                                         htlcs.iter_mut().for_each(|htlc| htlc.total_value_received = Some(amount_msat));
4618                                                                                         let counterparty_skimmed_fee_msat = htlcs.iter()
4619                                                                                                 .map(|htlc| htlc.counterparty_skimmed_fee_msat.unwrap_or(0)).sum();
4620                                                                                         debug_assert!(total_value.saturating_sub(amount_msat) <=
4621                                                                                                 counterparty_skimmed_fee_msat);
4622                                                                                         new_events.push_back((events::Event::PaymentClaimable {
4623                                                                                                 receiver_node_id: Some(receiver_node_id),
4624                                                                                                 payment_hash,
4625                                                                                                 purpose: $purpose,
4626                                                                                                 amount_msat,
4627                                                                                                 counterparty_skimmed_fee_msat,
4628                                                                                                 via_channel_id: Some(prev_channel_id),
4629                                                                                                 via_user_channel_id: Some(prev_user_channel_id),
4630                                                                                                 claim_deadline: Some(earliest_expiry - HTLC_FAIL_BACK_BUFFER),
4631                                                                                                 onion_fields: claimable_payment.onion_fields.clone(),
4632                                                                                         }, None));
4633                                                                                         payment_claimable_generated = true;
4634                                                                                 } else {
4635                                                                                         // Nothing to do - we haven't reached the total
4636                                                                                         // payment value yet, wait until we receive more
4637                                                                                         // MPP parts.
4638                                                                                         htlcs.push(claimable_htlc);
4639                                                                                         #[allow(unused_assignments)] {
4640                                                                                                 committed_to_claimable = true;
4641                                                                                         }
4642                                                                                 }
4643                                                                                 payment_claimable_generated
4644                                                                         }}
4645                                                                 }
4646
4647                                                                 // Check that the payment hash and secret are known. Note that we
4648                                                                 // MUST take care to handle the "unknown payment hash" and
4649                                                                 // "incorrect payment secret" cases here identically or we'd expose
4650                                                                 // that we are the ultimate recipient of the given payment hash.
4651                                                                 // Further, we must not expose whether we have any other HTLCs
4652                                                                 // associated with the same payment_hash pending or not.
4653                                                                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
4654                                                                 match payment_secrets.entry(payment_hash) {
4655                                                                         hash_map::Entry::Vacant(_) => {
4656                                                                                 match claimable_htlc.onion_payload {
4657                                                                                         OnionPayload::Invoice { .. } => {
4658                                                                                                 let payment_data = payment_data.unwrap();
4659                                                                                                 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) {
4660                                                                                                         Ok(result) => result,
4661                                                                                                         Err(()) => {
4662                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as payment verification failed", &payment_hash);
4663                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4664                                                                                                         }
4665                                                                                                 };
4666                                                                                                 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
4667                                                                                                         let expected_min_expiry_height = (self.current_best_block().height() + min_final_cltv_expiry_delta as u32) as u64;
4668                                                                                                         if (cltv_expiry as u64) < expected_min_expiry_height {
4669                                                                                                                 log_trace!(self.logger, "Failing new HTLC with payment_hash {} as its CLTV expiry was too soon (had {}, earliest expected {})",
4670                                                                                                                         &payment_hash, cltv_expiry, expected_min_expiry_height);
4671                                                                                                                 fail_htlc!(claimable_htlc, payment_hash);
4672                                                                                                         }
4673                                                                                                 }
4674                                                                                                 let purpose = events::PaymentPurpose::InvoicePayment {
4675                                                                                                         payment_preimage: payment_preimage.clone(),
4676                                                                                                         payment_secret: payment_data.payment_secret,
4677                                                                                                 };
4678                                                                                                 check_total_value!(purpose);
4679                                                                                         },
4680                                                                                         OnionPayload::Spontaneous(preimage) => {
4681                                                                                                 let purpose = events::PaymentPurpose::SpontaneousPayment(preimage);
4682                                                                                                 check_total_value!(purpose);
4683                                                                                         }
4684                                                                                 }
4685                                                                         },
4686                                                                         hash_map::Entry::Occupied(inbound_payment) => {
4687                                                                                 if let OnionPayload::Spontaneous(_) = claimable_htlc.onion_payload {
4688                                                                                         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);
4689                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4690                                                                                 }
4691                                                                                 let payment_data = payment_data.unwrap();
4692                                                                                 if inbound_payment.get().payment_secret != payment_data.payment_secret {
4693                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our expected payment secret.", &payment_hash);
4694                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4695                                                                                 } else if inbound_payment.get().min_value_msat.is_some() && payment_data.total_msat < inbound_payment.get().min_value_msat.unwrap() {
4696                                                                                         log_trace!(self.logger, "Failing new HTLC with payment_hash {} as it didn't match our minimum value (had {}, needed {}).",
4697                                                                                                 &payment_hash, payment_data.total_msat, inbound_payment.get().min_value_msat.unwrap());
4698                                                                                         fail_htlc!(claimable_htlc, payment_hash);
4699                                                                                 } else {
4700                                                                                         let purpose = events::PaymentPurpose::InvoicePayment {
4701                                                                                                 payment_preimage: inbound_payment.get().payment_preimage,
4702                                                                                                 payment_secret: payment_data.payment_secret,
4703                                                                                         };
4704                                                                                         let payment_claimable_generated = check_total_value!(purpose);
4705                                                                                         if payment_claimable_generated {
4706                                                                                                 inbound_payment.remove_entry();
4707                                                                                         }
4708                                                                                 }
4709                                                                         },
4710                                                                 };
4711                                                         },
4712                                                         HTLCForwardInfo::FailHTLC { .. } | HTLCForwardInfo::FailMalformedHTLC { .. } => {
4713                                                                 panic!("Got pending fail of our own HTLC");
4714                                                         }
4715                                                 }
4716                                         }
4717                                 }
4718                         }
4719                 }
4720
4721                 let best_block_height = self.best_block.read().unwrap().height();
4722                 self.pending_outbound_payments.check_retry_payments(&self.router, || self.list_usable_channels(),
4723                         || self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer, best_block_height,
4724                         &self.pending_events, &self.logger, |args| self.send_payment_along_path(args));
4725
4726                 for (htlc_source, payment_hash, failure_reason, destination) in failed_forwards.drain(..) {
4727                         self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
4728                 }
4729                 self.forward_htlcs(&mut phantom_receives);
4730
4731                 // Freeing the holding cell here is relatively redundant - in practice we'll do it when we
4732                 // next get a `get_and_clear_pending_msg_events` call, but some tests rely on it, and it's
4733                 // nice to do the work now if we can rather than while we're trying to get messages in the
4734                 // network stack.
4735                 self.check_free_holding_cells();
4736
4737                 if new_events.is_empty() { return }
4738                 let mut events = self.pending_events.lock().unwrap();
4739                 events.append(&mut new_events);
4740         }
4741
4742         /// Free the background events, generally called from [`PersistenceNotifierGuard`] constructors.
4743         ///
4744         /// Expects the caller to have a total_consistency_lock read lock.
4745         fn process_background_events(&self) -> NotifyOption {
4746                 debug_assert_ne!(self.total_consistency_lock.held_by_thread(), LockHeldState::NotHeldByThread);
4747
4748                 self.background_events_processed_since_startup.store(true, Ordering::Release);
4749
4750                 let mut background_events = Vec::new();
4751                 mem::swap(&mut *self.pending_background_events.lock().unwrap(), &mut background_events);
4752                 if background_events.is_empty() {
4753                         return NotifyOption::SkipPersistNoEvents;
4754                 }
4755
4756                 for event in background_events.drain(..) {
4757                         match event {
4758                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((funding_txo, _channel_id, update)) => {
4759                                         // The channel has already been closed, so no use bothering to care about the
4760                                         // monitor updating completing.
4761                                         let _ = self.chain_monitor.update_channel(funding_txo, &update);
4762                                 },
4763                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup { counterparty_node_id, funding_txo, channel_id, update } => {
4764                                         let mut updated_chan = false;
4765                                         {
4766                                                 let per_peer_state = self.per_peer_state.read().unwrap();
4767                                                 if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4768                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4769                                                         let peer_state = &mut *peer_state_lock;
4770                                                         match peer_state.channel_by_id.entry(channel_id) {
4771                                                                 hash_map::Entry::Occupied(mut chan_phase) => {
4772                                                                         if let ChannelPhase::Funded(chan) = chan_phase.get_mut() {
4773                                                                                 updated_chan = true;
4774                                                                                 handle_new_monitor_update!(self, funding_txo, channel_id, update.clone(),
4775                                                                                         peer_state_lock, peer_state, per_peer_state, chan);
4776                                                                         } else {
4777                                                                                 debug_assert!(false, "We shouldn't have an update for a non-funded channel");
4778                                                                         }
4779                                                                 },
4780                                                                 hash_map::Entry::Vacant(_) => {},
4781                                                         }
4782                                                 }
4783                                         }
4784                                         if !updated_chan {
4785                                                 // TODO: Track this as in-flight even though the channel is closed.
4786                                                 let _ = self.chain_monitor.update_channel(funding_txo, &update);
4787                                         }
4788                                 },
4789                                 BackgroundEvent::MonitorUpdatesComplete { counterparty_node_id, channel_id } => {
4790                                         let per_peer_state = self.per_peer_state.read().unwrap();
4791                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
4792                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4793                                                 let peer_state = &mut *peer_state_lock;
4794                                                 if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
4795                                                         handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, chan);
4796                                                 } else {
4797                                                         let update_actions = peer_state.monitor_update_blocked_actions
4798                                                                 .remove(&channel_id).unwrap_or(Vec::new());
4799                                                         mem::drop(peer_state_lock);
4800                                                         mem::drop(per_peer_state);
4801                                                         self.handle_monitor_update_completion_actions(update_actions);
4802                                                 }
4803                                         }
4804                                 },
4805                         }
4806                 }
4807                 NotifyOption::DoPersist
4808         }
4809
4810         #[cfg(any(test, feature = "_test_utils"))]
4811         /// Process background events, for functional testing
4812         pub fn test_process_background_events(&self) {
4813                 let _lck = self.total_consistency_lock.read().unwrap();
4814                 let _ = self.process_background_events();
4815         }
4816
4817         fn update_channel_fee(&self, chan_id: &ChannelId, chan: &mut Channel<SP>, new_feerate: u32) -> NotifyOption {
4818                 if !chan.context.is_outbound() { return NotifyOption::SkipPersistNoEvents; }
4819
4820                 let logger = WithChannelContext::from(&self.logger, &chan.context);
4821
4822                 // If the feerate has decreased by less than half, don't bother
4823                 if new_feerate <= chan.context.get_feerate_sat_per_1000_weight() && new_feerate * 2 > chan.context.get_feerate_sat_per_1000_weight() {
4824                         if new_feerate != chan.context.get_feerate_sat_per_1000_weight() {
4825                                 log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {}.",
4826                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4827                         }
4828                         return NotifyOption::SkipPersistNoEvents;
4829                 }
4830                 if !chan.context.is_live() {
4831                         log_trace!(logger, "Channel {} does not qualify for a feerate change from {} to {} as it cannot currently be updated (probably the peer is disconnected).",
4832                                 chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4833                         return NotifyOption::SkipPersistNoEvents;
4834                 }
4835                 log_trace!(logger, "Channel {} qualifies for a feerate change from {} to {}.",
4836                         &chan_id, chan.context.get_feerate_sat_per_1000_weight(), new_feerate);
4837
4838                 chan.queue_update_fee(new_feerate, &self.fee_estimator, &&logger);
4839                 NotifyOption::DoPersist
4840         }
4841
4842         #[cfg(fuzzing)]
4843         /// In chanmon_consistency we want to sometimes do the channel fee updates done in
4844         /// timer_tick_occurred, but we can't generate the disabled channel updates as it considers
4845         /// these a fuzz failure (as they usually indicate a channel force-close, which is exactly what
4846         /// it wants to detect). Thus, we have a variant exposed here for its benefit.
4847         pub fn maybe_update_chan_fees(&self) {
4848                 PersistenceNotifierGuard::optionally_notify(self, || {
4849                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4850
4851                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4852                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4853
4854                         let per_peer_state = self.per_peer_state.read().unwrap();
4855                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
4856                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4857                                 let peer_state = &mut *peer_state_lock;
4858                                 for (chan_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
4859                                         |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
4860                                 ) {
4861                                         let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4862                                                 anchor_feerate
4863                                         } else {
4864                                                 non_anchor_feerate
4865                                         };
4866                                         let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4867                                         if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4868                                 }
4869                         }
4870
4871                         should_persist
4872                 });
4873         }
4874
4875         /// Performs actions which should happen on startup and roughly once per minute thereafter.
4876         ///
4877         /// This currently includes:
4878         ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
4879         ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
4880         ///    than a minute, informing the network that they should no longer attempt to route over
4881         ///    the channel.
4882         ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
4883         ///    with the current [`ChannelConfig`].
4884         ///  * Removing peers which have disconnected but and no longer have any channels.
4885         ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
4886         ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
4887         ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
4888         ///    The latter is determined using the system clock in `std` and the highest seen block time
4889         ///    minus two hours in `no-std`.
4890         ///
4891         /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
4892         /// estimate fetches.
4893         ///
4894         /// [`ChannelUpdate`]: msgs::ChannelUpdate
4895         /// [`ChannelConfig`]: crate::util::config::ChannelConfig
4896         pub fn timer_tick_occurred(&self) {
4897                 PersistenceNotifierGuard::optionally_notify(self, || {
4898                         let mut should_persist = NotifyOption::SkipPersistNoEvents;
4899
4900                         let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4901                         let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
4902
4903                         let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
4904                         let mut timed_out_mpp_htlcs = Vec::new();
4905                         let mut pending_peers_awaiting_removal = Vec::new();
4906                         let mut shutdown_channels = Vec::new();
4907
4908                         let mut process_unfunded_channel_tick = |
4909                                 chan_id: &ChannelId,
4910                                 context: &mut ChannelContext<SP>,
4911                                 unfunded_context: &mut UnfundedChannelContext,
4912                                 pending_msg_events: &mut Vec<MessageSendEvent>,
4913                                 counterparty_node_id: PublicKey,
4914                         | {
4915                                 context.maybe_expire_prev_config();
4916                                 if unfunded_context.should_expire_unfunded_channel() {
4917                                         let logger = WithChannelContext::from(&self.logger, context);
4918                                         log_error!(logger,
4919                                                 "Force-closing pending channel with ID {} for not establishing in a timely manner", chan_id);
4920                                         update_maps_on_chan_removal!(self, &context);
4921                                         shutdown_channels.push(context.force_shutdown(false, ClosureReason::HolderForceClosed));
4922                                         pending_msg_events.push(MessageSendEvent::HandleError {
4923                                                 node_id: counterparty_node_id,
4924                                                 action: msgs::ErrorAction::SendErrorMessage {
4925                                                         msg: msgs::ErrorMessage {
4926                                                                 channel_id: *chan_id,
4927                                                                 data: "Force-closing pending channel due to timeout awaiting establishment handshake".to_owned(),
4928                                                         },
4929                                                 },
4930                                         });
4931                                         false
4932                                 } else {
4933                                         true
4934                                 }
4935                         };
4936
4937                         {
4938                                 let per_peer_state = self.per_peer_state.read().unwrap();
4939                                 for (counterparty_node_id, peer_state_mutex) in per_peer_state.iter() {
4940                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
4941                                         let peer_state = &mut *peer_state_lock;
4942                                         let pending_msg_events = &mut peer_state.pending_msg_events;
4943                                         let counterparty_node_id = *counterparty_node_id;
4944                                         peer_state.channel_by_id.retain(|chan_id, phase| {
4945                                                 match phase {
4946                                                         ChannelPhase::Funded(chan) => {
4947                                                                 let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4948                                                                         anchor_feerate
4949                                                                 } else {
4950                                                                         non_anchor_feerate
4951                                                                 };
4952                                                                 let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
4953                                                                 if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
4954
4955                                                                 if let Err(e) = chan.timer_check_closing_negotiation_progress() {
4956                                                                         let (needs_close, err) = convert_chan_phase_err!(self, e, chan, chan_id, FUNDED_CHANNEL);
4957                                                                         handle_errors.push((Err(err), counterparty_node_id));
4958                                                                         if needs_close { return false; }
4959                                                                 }
4960
4961                                                                 match chan.channel_update_status() {
4962                                                                         ChannelUpdateStatus::Enabled if !chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(0)),
4963                                                                         ChannelUpdateStatus::Disabled if chan.context.is_live() => chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(0)),
4964                                                                         ChannelUpdateStatus::DisabledStaged(_) if chan.context.is_live()
4965                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Enabled),
4966                                                                         ChannelUpdateStatus::EnabledStaged(_) if !chan.context.is_live()
4967                                                                                 => chan.set_channel_update_status(ChannelUpdateStatus::Disabled),
4968                                                                         ChannelUpdateStatus::DisabledStaged(mut n) if !chan.context.is_live() => {
4969                                                                                 n += 1;
4970                                                                                 if n >= DISABLE_GOSSIP_TICKS {
4971                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Disabled);
4972                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4973                                                                                                 let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
4974                                                                                                 pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
4975                                                                                                         msg: update
4976                                                                                                 });
4977                                                                                         }
4978                                                                                         should_persist = NotifyOption::DoPersist;
4979                                                                                 } else {
4980                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::DisabledStaged(n));
4981                                                                                 }
4982                                                                         },
4983                                                                         ChannelUpdateStatus::EnabledStaged(mut n) if chan.context.is_live() => {
4984                                                                                 n += 1;
4985                                                                                 if n >= ENABLE_GOSSIP_TICKS {
4986                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::Enabled);
4987                                                                                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
4988                                                                                                 let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
4989                                                                                                 pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
4990                                                                                                         msg: update
4991                                                                                                 });
4992                                                                                         }
4993                                                                                         should_persist = NotifyOption::DoPersist;
4994                                                                                 } else {
4995                                                                                         chan.set_channel_update_status(ChannelUpdateStatus::EnabledStaged(n));
4996                                                                                 }
4997                                                                         },
4998                                                                         _ => {},
4999                                                                 }
5000
5001                                                                 chan.context.maybe_expire_prev_config();
5002
5003                                                                 if chan.should_disconnect_peer_awaiting_response() {
5004                                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
5005                                                                         log_debug!(logger, "Disconnecting peer {} due to not making any progress on channel {}",
5006                                                                                         counterparty_node_id, chan_id);
5007                                                                         pending_msg_events.push(MessageSendEvent::HandleError {
5008                                                                                 node_id: counterparty_node_id,
5009                                                                                 action: msgs::ErrorAction::DisconnectPeerWithWarning {
5010                                                                                         msg: msgs::WarningMessage {
5011                                                                                                 channel_id: *chan_id,
5012                                                                                                 data: "Disconnecting due to timeout awaiting response".to_owned(),
5013                                                                                         },
5014                                                                                 },
5015                                                                         });
5016                                                                 }
5017
5018                                                                 true
5019                                                         },
5020                                                         ChannelPhase::UnfundedInboundV1(chan) => {
5021                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5022                                                                         pending_msg_events, counterparty_node_id)
5023                                                         },
5024                                                         ChannelPhase::UnfundedOutboundV1(chan) => {
5025                                                                 process_unfunded_channel_tick(chan_id, &mut chan.context, &mut chan.unfunded_context,
5026                                                                         pending_msg_events, counterparty_node_id)
5027                                                         },
5028                                                 }
5029                                         });
5030
5031                                         for (chan_id, req) in peer_state.inbound_channel_request_by_id.iter_mut() {
5032                                                 if { req.ticks_remaining -= 1 ; req.ticks_remaining } <= 0 {
5033                                                         let logger = WithContext::from(&self.logger, Some(counterparty_node_id), Some(*chan_id));
5034                                                         log_error!(logger, "Force-closing unaccepted inbound channel {} for not accepting in a timely manner", &chan_id);
5035                                                         peer_state.pending_msg_events.push(
5036                                                                 events::MessageSendEvent::HandleError {
5037                                                                         node_id: counterparty_node_id,
5038                                                                         action: msgs::ErrorAction::SendErrorMessage {
5039                                                                                 msg: msgs::ErrorMessage { channel_id: chan_id.clone(), data: "Channel force-closed".to_owned() }
5040                                                                         },
5041                                                                 }
5042                                                         );
5043                                                 }
5044                                         }
5045                                         peer_state.inbound_channel_request_by_id.retain(|_, req| req.ticks_remaining > 0);
5046
5047                                         if peer_state.ok_to_remove(true) {
5048                                                 pending_peers_awaiting_removal.push(counterparty_node_id);
5049                                         }
5050                                 }
5051                         }
5052
5053                         // When a peer disconnects but still has channels, the peer's `peer_state` entry in the
5054                         // `per_peer_state` is not removed by the `peer_disconnected` function. If the channels
5055                         // of to that peer is later closed while still being disconnected (i.e. force closed),
5056                         // we therefore need to remove the peer from `peer_state` separately.
5057                         // To avoid having to take the `per_peer_state` `write` lock once the channels are
5058                         // closed, we instead remove such peers awaiting removal here on a timer, to limit the
5059                         // negative effects on parallelism as much as possible.
5060                         if pending_peers_awaiting_removal.len() > 0 {
5061                                 let mut per_peer_state = self.per_peer_state.write().unwrap();
5062                                 for counterparty_node_id in pending_peers_awaiting_removal {
5063                                         match per_peer_state.entry(counterparty_node_id) {
5064                                                 hash_map::Entry::Occupied(entry) => {
5065                                                         // Remove the entry if the peer is still disconnected and we still
5066                                                         // have no channels to the peer.
5067                                                         let remove_entry = {
5068                                                                 let peer_state = entry.get().lock().unwrap();
5069                                                                 peer_state.ok_to_remove(true)
5070                                                         };
5071                                                         if remove_entry {
5072                                                                 entry.remove_entry();
5073                                                         }
5074                                                 },
5075                                                 hash_map::Entry::Vacant(_) => { /* The PeerState has already been removed */ }
5076                                         }
5077                                 }
5078                         }
5079
5080                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
5081                                 if payment.htlcs.is_empty() {
5082                                         // This should be unreachable
5083                                         debug_assert!(false);
5084                                         return false;
5085                                 }
5086                                 if let OnionPayload::Invoice { .. } = payment.htlcs[0].onion_payload {
5087                                         // Check if we've received all the parts we need for an MPP (the value of the parts adds to total_msat).
5088                                         // In this case we're not going to handle any timeouts of the parts here.
5089                                         // This condition determining whether the MPP is complete here must match
5090                                         // exactly the condition used in `process_pending_htlc_forwards`.
5091                                         if payment.htlcs[0].total_msat <= payment.htlcs.iter()
5092                                                 .fold(0, |total, htlc| total + htlc.sender_intended_value)
5093                                         {
5094                                                 return true;
5095                                         } else if payment.htlcs.iter_mut().any(|htlc| {
5096                                                 htlc.timer_ticks += 1;
5097                                                 return htlc.timer_ticks >= MPP_TIMEOUT_TICKS
5098                                         }) {
5099                                                 timed_out_mpp_htlcs.extend(payment.htlcs.drain(..)
5100                                                         .map(|htlc: ClaimableHTLC| (htlc.prev_hop, *payment_hash)));
5101                                                 return false;
5102                                         }
5103                                 }
5104                                 true
5105                         });
5106
5107                         for htlc_source in timed_out_mpp_htlcs.drain(..) {
5108                                 let source = HTLCSource::PreviousHopData(htlc_source.0.clone());
5109                                 let reason = HTLCFailReason::from_failure_code(23);
5110                                 let receiver = HTLCDestination::FailedPayment { payment_hash: htlc_source.1 };
5111                                 self.fail_htlc_backwards_internal(&source, &htlc_source.1, &reason, receiver);
5112                         }
5113
5114                         for (err, counterparty_node_id) in handle_errors.drain(..) {
5115                                 let _ = handle_error!(self, err, counterparty_node_id);
5116                         }
5117
5118                         for shutdown_res in shutdown_channels {
5119                                 self.finish_close_channel(shutdown_res);
5120                         }
5121
5122                         #[cfg(feature = "std")]
5123                         let duration_since_epoch = std::time::SystemTime::now()
5124                                 .duration_since(std::time::SystemTime::UNIX_EPOCH)
5125                                 .expect("SystemTime::now() should come after SystemTime::UNIX_EPOCH");
5126                         #[cfg(not(feature = "std"))]
5127                         let duration_since_epoch = Duration::from_secs(
5128                                 self.highest_seen_timestamp.load(Ordering::Acquire).saturating_sub(7200) as u64
5129                         );
5130
5131                         self.pending_outbound_payments.remove_stale_payments(
5132                                 duration_since_epoch, &self.pending_events
5133                         );
5134
5135                         // Technically we don't need to do this here, but if we have holding cell entries in a
5136                         // channel that need freeing, it's better to do that here and block a background task
5137                         // than block the message queueing pipeline.
5138                         if self.check_free_holding_cells() {
5139                                 should_persist = NotifyOption::DoPersist;
5140                         }
5141
5142                         should_persist
5143                 });
5144         }
5145
5146         /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
5147         /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
5148         /// along the path (including in our own channel on which we received it).
5149         ///
5150         /// Note that in some cases around unclean shutdown, it is possible the payment may have
5151         /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
5152         /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
5153         /// may have already been failed automatically by LDK if it was nearing its expiration time.
5154         ///
5155         /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
5156         /// [`ChannelManager::claim_funds`]), you should still monitor for
5157         /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
5158         /// startup during which time claims that were in-progress at shutdown may be replayed.
5159         pub fn fail_htlc_backwards(&self, payment_hash: &PaymentHash) {
5160                 self.fail_htlc_backwards_with_reason(payment_hash, FailureCode::IncorrectOrUnknownPaymentDetails);
5161         }
5162
5163         /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
5164         /// reason for the failure.
5165         ///
5166         /// See [`FailureCode`] for valid failure codes.
5167         pub fn fail_htlc_backwards_with_reason(&self, payment_hash: &PaymentHash, failure_code: FailureCode) {
5168                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5169
5170                 let removed_source = self.claimable_payments.lock().unwrap().claimable_payments.remove(payment_hash);
5171                 if let Some(payment) = removed_source {
5172                         for htlc in payment.htlcs {
5173                                 let reason = self.get_htlc_fail_reason_from_failure_code(failure_code, &htlc);
5174                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5175                                 let receiver = HTLCDestination::FailedPayment { payment_hash: *payment_hash };
5176                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5177                         }
5178                 }
5179         }
5180
5181         /// Gets error data to form an [`HTLCFailReason`] given a [`FailureCode`] and [`ClaimableHTLC`].
5182         fn get_htlc_fail_reason_from_failure_code(&self, failure_code: FailureCode, htlc: &ClaimableHTLC) -> HTLCFailReason {
5183                 match failure_code {
5184                         FailureCode::TemporaryNodeFailure => HTLCFailReason::from_failure_code(failure_code.into()),
5185                         FailureCode::RequiredNodeFeatureMissing => HTLCFailReason::from_failure_code(failure_code.into()),
5186                         FailureCode::IncorrectOrUnknownPaymentDetails => {
5187                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5188                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5189                                 HTLCFailReason::reason(failure_code.into(), htlc_msat_height_data)
5190                         },
5191                         FailureCode::InvalidOnionPayload(data) => {
5192                                 let fail_data = match data {
5193                                         Some((typ, offset)) => [BigSize(typ).encode(), offset.encode()].concat(),
5194                                         None => Vec::new(),
5195                                 };
5196                                 HTLCFailReason::reason(failure_code.into(), fail_data)
5197                         }
5198                 }
5199         }
5200
5201         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5202         /// that we want to return and a channel.
5203         ///
5204         /// This is for failures on the channel on which the HTLC was *received*, not failures
5205         /// forwarding
5206         fn get_htlc_inbound_temp_fail_err_and_data(&self, desired_err_code: u16, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5207                 // We can't be sure what SCID was used when relaying inbound towards us, so we have to
5208                 // guess somewhat. If its a public channel, we figure best to just use the real SCID (as
5209                 // we're not leaking that we have a channel with the counterparty), otherwise we try to use
5210                 // an inbound SCID alias before the real SCID.
5211                 let scid_pref = if chan.context.should_announce() {
5212                         chan.context.get_short_channel_id().or(chan.context.latest_inbound_scid_alias())
5213                 } else {
5214                         chan.context.latest_inbound_scid_alias().or(chan.context.get_short_channel_id())
5215                 };
5216                 if let Some(scid) = scid_pref {
5217                         self.get_htlc_temp_fail_err_and_data(desired_err_code, scid, chan)
5218                 } else {
5219                         (0x4000|10, Vec::new())
5220                 }
5221         }
5222
5223
5224         /// Gets an HTLC onion failure code and error data for an `UPDATE` error, given the error code
5225         /// that we want to return and a channel.
5226         fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<SP>) -> (u16, Vec<u8>) {
5227                 debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
5228                 if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
5229                         let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
5230                         if desired_err_code == 0x1000 | 20 {
5231                                 // No flags for `disabled_flags` are currently defined so they're always two zero bytes.
5232                                 // See https://github.com/lightning/bolts/blob/341ec84/04-onion-routing.md?plain=1#L1008
5233                                 0u16.write(&mut enc).expect("Writes cannot fail");
5234                         }
5235                         (upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
5236                         msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
5237                         upd.write(&mut enc).expect("Writes cannot fail");
5238                         (desired_err_code, enc.0)
5239                 } else {
5240                         // If we fail to get a unicast channel_update, it implies we don't yet have an SCID,
5241                         // which means we really shouldn't have gotten a payment to be forwarded over this
5242                         // channel yet, or if we did it's from a route hint. Either way, returning an error of
5243                         // PERM|no_such_channel should be fine.
5244                         (0x4000|10, Vec::new())
5245                 }
5246         }
5247
5248         // Fail a list of HTLCs that were just freed from the holding cell. The HTLCs need to be
5249         // failed backwards or, if they were one of our outgoing HTLCs, then their failure needs to
5250         // be surfaced to the user.
5251         fn fail_holding_cell_htlcs(
5252                 &self, mut htlcs_to_fail: Vec<(HTLCSource, PaymentHash)>, channel_id: ChannelId,
5253                 counterparty_node_id: &PublicKey
5254         ) {
5255                 let (failure_code, onion_failure_data) = {
5256                         let per_peer_state = self.per_peer_state.read().unwrap();
5257                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
5258                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
5259                                 let peer_state = &mut *peer_state_lock;
5260                                 match peer_state.channel_by_id.entry(channel_id) {
5261                                         hash_map::Entry::Occupied(chan_phase_entry) => {
5262                                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get() {
5263                                                         self.get_htlc_inbound_temp_fail_err_and_data(0x1000|7, &chan)
5264                                                 } else {
5265                                                         // We shouldn't be trying to fail holding cell HTLCs on an unfunded channel.
5266                                                         debug_assert!(false);
5267                                                         (0x4000|10, Vec::new())
5268                                                 }
5269                                         },
5270                                         hash_map::Entry::Vacant(_) => (0x4000|10, Vec::new())
5271                                 }
5272                         } else { (0x4000|10, Vec::new()) }
5273                 };
5274
5275                 for (htlc_src, payment_hash) in htlcs_to_fail.drain(..) {
5276                         let reason = HTLCFailReason::reason(failure_code, onion_failure_data.clone());
5277                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id };
5278                         self.fail_htlc_backwards_internal(&htlc_src, &payment_hash, &reason, receiver);
5279                 }
5280         }
5281
5282         /// Fails an HTLC backwards to the sender of it to us.
5283         /// Note that we do not assume that channels corresponding to failed HTLCs are still available.
5284         fn fail_htlc_backwards_internal(&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason, destination: HTLCDestination) {
5285                 // Ensure that no peer state channel storage lock is held when calling this function.
5286                 // This ensures that future code doesn't introduce a lock-order requirement for
5287                 // `forward_htlcs` to be locked after the `per_peer_state` peer locks, which calling
5288                 // this function with any `per_peer_state` peer lock acquired would.
5289                 #[cfg(debug_assertions)]
5290                 for (_, peer) in self.per_peer_state.read().unwrap().iter() {
5291                         debug_assert_ne!(peer.held_by_thread(), LockHeldState::HeldByThread);
5292                 }
5293
5294                 //TODO: There is a timing attack here where if a node fails an HTLC back to us they can
5295                 //identify whether we sent it or not based on the (I presume) very different runtime
5296                 //between the branches here. We should make this async and move it into the forward HTLCs
5297                 //timer handling.
5298
5299                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
5300                 // from block_connected which may run during initialization prior to the chain_monitor
5301                 // being fully configured. See the docs for `ChannelManagerReadArgs` for more.
5302                 match source {
5303                         HTLCSource::OutboundRoute { ref path, ref session_priv, ref payment_id, .. } => {
5304                                 if self.pending_outbound_payments.fail_htlc(source, payment_hash, onion_error, path,
5305                                         session_priv, payment_id, self.probing_cookie_secret, &self.secp_ctx,
5306                                         &self.pending_events, &self.logger)
5307                                 { self.push_pending_forwards_ev(); }
5308                         },
5309                         HTLCSource::PreviousHopData(HTLCPreviousHopData {
5310                                 ref short_channel_id, ref htlc_id, ref incoming_packet_shared_secret,
5311                                 ref phantom_shared_secret, outpoint: _, ref blinded_failure, ref channel_id, ..
5312                         }) => {
5313                                 log_trace!(
5314                                         WithContext::from(&self.logger, None, Some(*channel_id)),
5315                                         "Failing {}HTLC with payment_hash {} backwards from us: {:?}",
5316                                         if blinded_failure.is_some() { "blinded " } else { "" }, &payment_hash, onion_error
5317                                 );
5318                                 let failure = match blinded_failure {
5319                                         Some(BlindedFailure::FromIntroductionNode) => {
5320                                                 let blinded_onion_error = HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32]);
5321                                                 let err_packet = blinded_onion_error.get_encrypted_failure_packet(
5322                                                         incoming_packet_shared_secret, phantom_shared_secret
5323                                                 );
5324                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5325                                         },
5326                                         Some(BlindedFailure::FromBlindedNode) => {
5327                                                 HTLCForwardInfo::FailMalformedHTLC {
5328                                                         htlc_id: *htlc_id,
5329                                                         failure_code: INVALID_ONION_BLINDING,
5330                                                         sha256_of_onion: [0; 32]
5331                                                 }
5332                                         },
5333                                         None => {
5334                                                 let err_packet = onion_error.get_encrypted_failure_packet(
5335                                                         incoming_packet_shared_secret, phantom_shared_secret
5336                                                 );
5337                                                 HTLCForwardInfo::FailHTLC { htlc_id: *htlc_id, err_packet }
5338                                         }
5339                                 };
5340
5341                                 let mut push_forward_ev = false;
5342                                 let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
5343                                 if forward_htlcs.is_empty() {
5344                                         push_forward_ev = true;
5345                                 }
5346                                 match forward_htlcs.entry(*short_channel_id) {
5347                                         hash_map::Entry::Occupied(mut entry) => {
5348                                                 entry.get_mut().push(failure);
5349                                         },
5350                                         hash_map::Entry::Vacant(entry) => {
5351                                                 entry.insert(vec!(failure));
5352                                         }
5353                                 }
5354                                 mem::drop(forward_htlcs);
5355                                 if push_forward_ev { self.push_pending_forwards_ev(); }
5356                                 let mut pending_events = self.pending_events.lock().unwrap();
5357                                 pending_events.push_back((events::Event::HTLCHandlingFailed {
5358                                         prev_channel_id: *channel_id,
5359                                         failed_next_destination: destination,
5360                                 }, None));
5361                         },
5362                 }
5363         }
5364
5365         /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
5366         /// [`MessageSendEvent`]s needed to claim the payment.
5367         ///
5368         /// This method is guaranteed to ensure the payment has been claimed but only if the current
5369         /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
5370         /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
5371         /// successful. It will generally be available in the next [`process_pending_events`] call.
5372         ///
5373         /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
5374         /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
5375         /// event matches your expectation. If you fail to do so and call this method, you may provide
5376         /// the sender "proof-of-payment" when they did not fulfill the full expected payment.
5377         ///
5378         /// This function will fail the payment if it has custom TLVs with even type numbers, as we
5379         /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
5380         /// [`claim_funds_with_known_custom_tlvs`].
5381         ///
5382         /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
5383         /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
5384         /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
5385         /// [`process_pending_events`]: EventsProvider::process_pending_events
5386         /// [`create_inbound_payment`]: Self::create_inbound_payment
5387         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
5388         /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
5389         pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
5390                 self.claim_payment_internal(payment_preimage, false);
5391         }
5392
5393         /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
5394         /// even type numbers.
5395         ///
5396         /// # Note
5397         ///
5398         /// You MUST check you've understood all even TLVs before using this to
5399         /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
5400         ///
5401         /// [`claim_funds`]: Self::claim_funds
5402         pub fn claim_funds_with_known_custom_tlvs(&self, payment_preimage: PaymentPreimage) {
5403                 self.claim_payment_internal(payment_preimage, true);
5404         }
5405
5406         fn claim_payment_internal(&self, payment_preimage: PaymentPreimage, custom_tlvs_known: bool) {
5407                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
5408
5409                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
5410
5411                 let mut sources = {
5412                         let mut claimable_payments = self.claimable_payments.lock().unwrap();
5413                         if let Some(payment) = claimable_payments.claimable_payments.remove(&payment_hash) {
5414                                 let mut receiver_node_id = self.our_network_pubkey;
5415                                 for htlc in payment.htlcs.iter() {
5416                                         if htlc.prev_hop.phantom_shared_secret.is_some() {
5417                                                 let phantom_pubkey = self.node_signer.get_node_id(Recipient::PhantomNode)
5418                                                         .expect("Failed to get node_id for phantom node recipient");
5419                                                 receiver_node_id = phantom_pubkey;
5420                                                 break;
5421                                         }
5422                                 }
5423
5424                                 let htlcs = payment.htlcs.iter().map(events::ClaimedHTLC::from).collect();
5425                                 let sender_intended_value = payment.htlcs.first().map(|htlc| htlc.total_msat);
5426                                 let dup_purpose = claimable_payments.pending_claiming_payments.insert(payment_hash,
5427                                         ClaimingPayment { amount_msat: payment.htlcs.iter().map(|source| source.value).sum(),
5428                                         payment_purpose: payment.purpose, receiver_node_id, htlcs, sender_intended_value
5429                                 });
5430                                 if dup_purpose.is_some() {
5431                                         debug_assert!(false, "Shouldn't get a duplicate pending claim event ever");
5432                                         log_error!(self.logger, "Got a duplicate pending claimable event on payment hash {}! Please report this bug",
5433                                                 &payment_hash);
5434                                 }
5435
5436                                 if let Some(RecipientOnionFields { ref custom_tlvs, .. }) = payment.onion_fields {
5437                                         if !custom_tlvs_known && custom_tlvs.iter().any(|(typ, _)| typ % 2 == 0) {
5438                                                 log_info!(self.logger, "Rejecting payment with payment hash {} as we cannot accept payment with unknown even TLVs: {}",
5439                                                         &payment_hash, log_iter!(custom_tlvs.iter().map(|(typ, _)| typ).filter(|typ| *typ % 2 == 0)));
5440                                                 claimable_payments.pending_claiming_payments.remove(&payment_hash);
5441                                                 mem::drop(claimable_payments);
5442                                                 for htlc in payment.htlcs {
5443                                                         let reason = self.get_htlc_fail_reason_from_failure_code(FailureCode::InvalidOnionPayload(None), &htlc);
5444                                                         let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5445                                                         let receiver = HTLCDestination::FailedPayment { payment_hash };
5446                                                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5447                                                 }
5448                                                 return;
5449                                         }
5450                                 }
5451
5452                                 payment.htlcs
5453                         } else { return; }
5454                 };
5455                 debug_assert!(!sources.is_empty());
5456
5457                 // Just in case one HTLC has been failed between when we generated the `PaymentClaimable`
5458                 // and when we got here we need to check that the amount we're about to claim matches the
5459                 // amount we told the user in the last `PaymentClaimable`. We also do a sanity-check that
5460                 // the MPP parts all have the same `total_msat`.
5461                 let mut claimable_amt_msat = 0;
5462                 let mut prev_total_msat = None;
5463                 let mut expected_amt_msat = None;
5464                 let mut valid_mpp = true;
5465                 let mut errs = Vec::new();
5466                 let per_peer_state = self.per_peer_state.read().unwrap();
5467                 for htlc in sources.iter() {
5468                         if prev_total_msat.is_some() && prev_total_msat != Some(htlc.total_msat) {
5469                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different expected total amounts - this should not be reachable!");
5470                                 debug_assert!(false);
5471                                 valid_mpp = false;
5472                                 break;
5473                         }
5474                         prev_total_msat = Some(htlc.total_msat);
5475
5476                         if expected_amt_msat.is_some() && expected_amt_msat != htlc.total_value_received {
5477                                 log_error!(self.logger, "Somehow ended up with an MPP payment with different received total amounts - this should not be reachable!");
5478                                 debug_assert!(false);
5479                                 valid_mpp = false;
5480                                 break;
5481                         }
5482                         expected_amt_msat = htlc.total_value_received;
5483                         claimable_amt_msat += htlc.value;
5484                 }
5485                 mem::drop(per_peer_state);
5486                 if sources.is_empty() || expected_amt_msat.is_none() {
5487                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5488                         log_info!(self.logger, "Attempted to claim an incomplete payment which no longer had any available HTLCs!");
5489                         return;
5490                 }
5491                 if claimable_amt_msat != expected_amt_msat.unwrap() {
5492                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5493                         log_info!(self.logger, "Attempted to claim an incomplete payment, expected {} msat, had {} available to claim.",
5494                                 expected_amt_msat.unwrap(), claimable_amt_msat);
5495                         return;
5496                 }
5497                 if valid_mpp {
5498                         for htlc in sources.drain(..) {
5499                                 let prev_hop_chan_id = htlc.prev_hop.channel_id;
5500                                 if let Err((pk, err)) = self.claim_funds_from_hop(
5501                                         htlc.prev_hop, payment_preimage,
5502                                         |_, definitely_duplicate| {
5503                                                 debug_assert!(!definitely_duplicate, "We shouldn't claim duplicatively from a payment");
5504                                                 Some(MonitorUpdateCompletionAction::PaymentClaimed { payment_hash })
5505                                         }
5506                                 ) {
5507                                         if let msgs::ErrorAction::IgnoreError = err.err.action {
5508                                                 // We got a temporary failure updating monitor, but will claim the
5509                                                 // HTLC when the monitor updating is restored (or on chain).
5510                                                 let logger = WithContext::from(&self.logger, None, Some(prev_hop_chan_id));
5511                                                 log_error!(logger, "Temporary failure claiming HTLC, treating as success: {}", err.err.err);
5512                                         } else { errs.push((pk, err)); }
5513                                 }
5514                         }
5515                 }
5516                 if !valid_mpp {
5517                         for htlc in sources.drain(..) {
5518                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
5519                                 htlc_msat_height_data.extend_from_slice(&self.best_block.read().unwrap().height().to_be_bytes());
5520                                 let source = HTLCSource::PreviousHopData(htlc.prev_hop);
5521                                 let reason = HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data);
5522                                 let receiver = HTLCDestination::FailedPayment { payment_hash };
5523                                 self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
5524                         }
5525                         self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5526                 }
5527
5528                 // Now we can handle any errors which were generated.
5529                 for (counterparty_node_id, err) in errs.drain(..) {
5530                         let res: Result<(), _> = Err(err);
5531                         let _ = handle_error!(self, res, counterparty_node_id);
5532                 }
5533         }
5534
5535         fn claim_funds_from_hop<ComplFunc: FnOnce(Option<u64>, bool) -> Option<MonitorUpdateCompletionAction>>(&self,
5536                 prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage, completion_action: ComplFunc)
5537         -> Result<(), (PublicKey, MsgHandleErrInternal)> {
5538                 //TODO: Delay the claimed_funds relaying just like we do outbound relay!
5539
5540                 // If we haven't yet run background events assume we're still deserializing and shouldn't
5541                 // actually pass `ChannelMonitorUpdate`s to users yet. Instead, queue them up as
5542                 // `BackgroundEvent`s.
5543                 let during_init = !self.background_events_processed_since_startup.load(Ordering::Acquire);
5544
5545                 // As we may call handle_monitor_update_completion_actions in rather rare cases, check that
5546                 // the required mutexes are not held before we start.
5547                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5548                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5549
5550                 {
5551                         let per_peer_state = self.per_peer_state.read().unwrap();
5552                         let chan_id = prev_hop.channel_id;
5553                         let counterparty_node_id_opt = match self.short_to_chan_info.read().unwrap().get(&prev_hop.short_channel_id) {
5554                                 Some((cp_id, _dup_chan_id)) => Some(cp_id.clone()),
5555                                 None => None
5556                         };
5557
5558                         let peer_state_opt = counterparty_node_id_opt.as_ref().map(
5559                                 |counterparty_node_id| per_peer_state.get(counterparty_node_id)
5560                                         .map(|peer_mutex| peer_mutex.lock().unwrap())
5561                         ).unwrap_or(None);
5562
5563                         if peer_state_opt.is_some() {
5564                                 let mut peer_state_lock = peer_state_opt.unwrap();
5565                                 let peer_state = &mut *peer_state_lock;
5566                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(chan_id) {
5567                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
5568                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
5569                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
5570                                                 let fulfill_res = chan.get_update_fulfill_htlc_and_commit(prev_hop.htlc_id, payment_preimage, &&logger);
5571
5572                                                 match fulfill_res {
5573                                                         UpdateFulfillCommitFetch::NewClaim { htlc_value_msat, monitor_update } => {
5574                                                                 if let Some(action) = completion_action(Some(htlc_value_msat), false) {
5575                                                                         log_trace!(logger, "Tracking monitor update completion action for channel {}: {:?}",
5576                                                                                 chan_id, action);
5577                                                                         peer_state.monitor_update_blocked_actions.entry(chan_id).or_insert(Vec::new()).push(action);
5578                                                                 }
5579                                                                 if !during_init {
5580                                                                         handle_new_monitor_update!(self, prev_hop.outpoint, prev_hop.channel_id, monitor_update, peer_state_lock,
5581                                                                                 peer_state, per_peer_state, chan);
5582                                                                 } else {
5583                                                                         // If we're running during init we cannot update a monitor directly -
5584                                                                         // they probably haven't actually been loaded yet. Instead, push the
5585                                                                         // monitor update as a background event.
5586                                                                         self.pending_background_events.lock().unwrap().push(
5587                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5588                                                                                         counterparty_node_id,
5589                                                                                         funding_txo: prev_hop.outpoint,
5590                                                                                         channel_id: prev_hop.channel_id,
5591                                                                                         update: monitor_update.clone(),
5592                                                                                 });
5593                                                                 }
5594                                                         }
5595                                                         UpdateFulfillCommitFetch::DuplicateClaim {} => {
5596                                                                 let action = if let Some(action) = completion_action(None, true) {
5597                                                                         action
5598                                                                 } else {
5599                                                                         return Ok(());
5600                                                                 };
5601                                                                 mem::drop(peer_state_lock);
5602
5603                                                                 log_trace!(logger, "Completing monitor update completion action for channel {} as claim was redundant: {:?}",
5604                                                                         chan_id, action);
5605                                                                 let (node_id, _funding_outpoint, channel_id, blocker) =
5606                                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5607                                                                         downstream_counterparty_node_id: node_id,
5608                                                                         downstream_funding_outpoint: funding_outpoint,
5609                                                                         blocking_action: blocker, downstream_channel_id: channel_id,
5610                                                                 } = action {
5611                                                                         (node_id, funding_outpoint, channel_id, blocker)
5612                                                                 } else {
5613                                                                         debug_assert!(false,
5614                                                                                 "Duplicate claims should always free another channel immediately");
5615                                                                         return Ok(());
5616                                                                 };
5617                                                                 if let Some(peer_state_mtx) = per_peer_state.get(&node_id) {
5618                                                                         let mut peer_state = peer_state_mtx.lock().unwrap();
5619                                                                         if let Some(blockers) = peer_state
5620                                                                                 .actions_blocking_raa_monitor_updates
5621                                                                                 .get_mut(&channel_id)
5622                                                                         {
5623                                                                                 let mut found_blocker = false;
5624                                                                                 blockers.retain(|iter| {
5625                                                                                         // Note that we could actually be blocked, in
5626                                                                                         // which case we need to only remove the one
5627                                                                                         // blocker which was added duplicatively.
5628                                                                                         let first_blocker = !found_blocker;
5629                                                                                         if *iter == blocker { found_blocker = true; }
5630                                                                                         *iter != blocker || !first_blocker
5631                                                                                 });
5632                                                                                 debug_assert!(found_blocker);
5633                                                                         }
5634                                                                 } else {
5635                                                                         debug_assert!(false);
5636                                                                 }
5637                                                         }
5638                                                 }
5639                                         }
5640                                         return Ok(());
5641                                 }
5642                         }
5643                 }
5644                 let preimage_update = ChannelMonitorUpdate {
5645                         update_id: CLOSED_CHANNEL_UPDATE_ID,
5646                         counterparty_node_id: None,
5647                         updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
5648                                 payment_preimage,
5649                         }],
5650                         channel_id: Some(prev_hop.channel_id),
5651                 };
5652
5653                 if !during_init {
5654                         // We update the ChannelMonitor on the backward link, after
5655                         // receiving an `update_fulfill_htlc` from the forward link.
5656                         let update_res = self.chain_monitor.update_channel(prev_hop.outpoint, &preimage_update);
5657                         if update_res != ChannelMonitorUpdateStatus::Completed {
5658                                 // TODO: This needs to be handled somehow - if we receive a monitor update
5659                                 // with a preimage we *must* somehow manage to propagate it to the upstream
5660                                 // channel, or we must have an ability to receive the same event and try
5661                                 // again on restart.
5662                                 log_error!(WithContext::from(&self.logger, None, Some(prev_hop.channel_id)),
5663                                         "Critical error: failed to update channel monitor with preimage {:?}: {:?}",
5664                                         payment_preimage, update_res);
5665                         }
5666                 } else {
5667                         // If we're running during init we cannot update a monitor directly - they probably
5668                         // haven't actually been loaded yet. Instead, push the monitor update as a background
5669                         // event.
5670                         // Note that while it's safe to use `ClosedMonitorUpdateRegeneratedOnStartup` here (the
5671                         // channel is already closed) we need to ultimately handle the monitor update
5672                         // completion action only after we've completed the monitor update. This is the only
5673                         // way to guarantee this update *will* be regenerated on startup (otherwise if this was
5674                         // from a forwarded HTLC the downstream preimage may be deleted before we claim
5675                         // upstream). Thus, we need to transition to some new `BackgroundEvent` type which will
5676                         // complete the monitor update completion action from `completion_action`.
5677                         self.pending_background_events.lock().unwrap().push(
5678                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((
5679                                         prev_hop.outpoint, prev_hop.channel_id, preimage_update,
5680                                 )));
5681                 }
5682                 // Note that we do process the completion action here. This totally could be a
5683                 // duplicate claim, but we have no way of knowing without interrogating the
5684                 // `ChannelMonitor` we've provided the above update to. Instead, note that `Event`s are
5685                 // generally always allowed to be duplicative (and it's specifically noted in
5686                 // `PaymentForwarded`).
5687                 self.handle_monitor_update_completion_actions(completion_action(None, false));
5688                 Ok(())
5689         }
5690
5691         fn finalize_claims(&self, sources: Vec<HTLCSource>) {
5692                 self.pending_outbound_payments.finalize_claims(sources, &self.pending_events);
5693         }
5694
5695         fn claim_funds_internal(&self, source: HTLCSource, payment_preimage: PaymentPreimage,
5696                 forwarded_htlc_value_msat: Option<u64>, from_onchain: bool, startup_replay: bool,
5697                 next_channel_counterparty_node_id: Option<PublicKey>, next_channel_outpoint: OutPoint,
5698                 next_channel_id: ChannelId,
5699         ) {
5700                 match source {
5701                         HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } => {
5702                                 debug_assert!(self.background_events_processed_since_startup.load(Ordering::Acquire),
5703                                         "We don't support claim_htlc claims during startup - monitors may not be available yet");
5704                                 if let Some(pubkey) = next_channel_counterparty_node_id {
5705                                         debug_assert_eq!(pubkey, path.hops[0].pubkey);
5706                                 }
5707                                 let ev_completion_action = EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
5708                                         channel_funding_outpoint: next_channel_outpoint, channel_id: next_channel_id,
5709                                         counterparty_node_id: path.hops[0].pubkey,
5710                                 };
5711                                 self.pending_outbound_payments.claim_htlc(payment_id, payment_preimage,
5712                                         session_priv, path, from_onchain, ev_completion_action, &self.pending_events,
5713                                         &self.logger);
5714                         },
5715                         HTLCSource::PreviousHopData(hop_data) => {
5716                                 let prev_channel_id = hop_data.channel_id;
5717                                 let completed_blocker = RAAMonitorUpdateBlockingAction::from_prev_hop_data(&hop_data);
5718                                 #[cfg(debug_assertions)]
5719                                 let claiming_chan_funding_outpoint = hop_data.outpoint;
5720                                 #[cfg(debug_assertions)]
5721                                 let claiming_channel_id = hop_data.channel_id;
5722                                 let res = self.claim_funds_from_hop(hop_data, payment_preimage,
5723                                         |htlc_claim_value_msat, definitely_duplicate| {
5724                                                 let chan_to_release =
5725                                                         if let Some(node_id) = next_channel_counterparty_node_id {
5726                                                                 Some((node_id, next_channel_outpoint, next_channel_id, completed_blocker))
5727                                                         } else {
5728                                                                 // We can only get `None` here if we are processing a
5729                                                                 // `ChannelMonitor`-originated event, in which case we
5730                                                                 // don't care about ensuring we wake the downstream
5731                                                                 // channel's monitor updating - the channel is already
5732                                                                 // closed.
5733                                                                 None
5734                                                         };
5735
5736                                                 if definitely_duplicate && startup_replay {
5737                                                         // On startup we may get redundant claims which are related to
5738                                                         // monitor updates still in flight. In that case, we shouldn't
5739                                                         // immediately free, but instead let that monitor update complete
5740                                                         // in the background.
5741                                                         #[cfg(debug_assertions)] {
5742                                                                 let background_events = self.pending_background_events.lock().unwrap();
5743                                                                 // There should be a `BackgroundEvent` pending...
5744                                                                 assert!(background_events.iter().any(|ev| {
5745                                                                         match ev {
5746                                                                                 // to apply a monitor update that blocked the claiming channel,
5747                                                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
5748                                                                                         funding_txo, update, ..
5749                                                                                 } => {
5750                                                                                         if *funding_txo == claiming_chan_funding_outpoint {
5751                                                                                                 assert!(update.updates.iter().any(|upd|
5752                                                                                                         if let ChannelMonitorUpdateStep::PaymentPreimage {
5753                                                                                                                 payment_preimage: update_preimage
5754                                                                                                         } = upd {
5755                                                                                                                 payment_preimage == *update_preimage
5756                                                                                                         } else { false }
5757                                                                                                 ), "{:?}", update);
5758                                                                                                 true
5759                                                                                         } else { false }
5760                                                                                 },
5761                                                                                 // or the channel we'd unblock is already closed,
5762                                                                                 BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup(
5763                                                                                         (funding_txo, _channel_id, monitor_update)
5764                                                                                 ) => {
5765                                                                                         if *funding_txo == next_channel_outpoint {
5766                                                                                                 assert_eq!(monitor_update.updates.len(), 1);
5767                                                                                                 assert!(matches!(
5768                                                                                                         monitor_update.updates[0],
5769                                                                                                         ChannelMonitorUpdateStep::ChannelForceClosed { .. }
5770                                                                                                 ));
5771                                                                                                 true
5772                                                                                         } else { false }
5773                                                                                 },
5774                                                                                 // or the monitor update has completed and will unblock
5775                                                                                 // immediately once we get going.
5776                                                                                 BackgroundEvent::MonitorUpdatesComplete {
5777                                                                                         channel_id, ..
5778                                                                                 } =>
5779                                                                                         *channel_id == claiming_channel_id,
5780                                                                         }
5781                                                                 }), "{:?}", *background_events);
5782                                                         }
5783                                                         None
5784                                                 } else if definitely_duplicate {
5785                                                         if let Some(other_chan) = chan_to_release {
5786                                                                 Some(MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5787                                                                         downstream_counterparty_node_id: other_chan.0,
5788                                                                         downstream_funding_outpoint: other_chan.1,
5789                                                                         downstream_channel_id: other_chan.2,
5790                                                                         blocking_action: other_chan.3,
5791                                                                 })
5792                                                         } else { None }
5793                                                 } else {
5794                                                         let fee_earned_msat = if let Some(forwarded_htlc_value) = forwarded_htlc_value_msat {
5795                                                                 if let Some(claimed_htlc_value) = htlc_claim_value_msat {
5796                                                                         Some(claimed_htlc_value - forwarded_htlc_value)
5797                                                                 } else { None }
5798                                                         } else { None };
5799                                                         Some(MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5800                                                                 event: events::Event::PaymentForwarded {
5801                                                                         fee_earned_msat,
5802                                                                         claim_from_onchain_tx: from_onchain,
5803                                                                         prev_channel_id: Some(prev_channel_id),
5804                                                                         next_channel_id: Some(next_channel_id),
5805                                                                         outbound_amount_forwarded_msat: forwarded_htlc_value_msat,
5806                                                                 },
5807                                                                 downstream_counterparty_and_funding_outpoint: chan_to_release,
5808                                                         })
5809                                                 }
5810                                         });
5811                                 if let Err((pk, err)) = res {
5812                                         let result: Result<(), _> = Err(err);
5813                                         let _ = handle_error!(self, result, pk);
5814                                 }
5815                         },
5816                 }
5817         }
5818
5819         /// Gets the node_id held by this ChannelManager
5820         pub fn get_our_node_id(&self) -> PublicKey {
5821                 self.our_network_pubkey.clone()
5822         }
5823
5824         fn handle_monitor_update_completion_actions<I: IntoIterator<Item=MonitorUpdateCompletionAction>>(&self, actions: I) {
5825                 debug_assert_ne!(self.pending_events.held_by_thread(), LockHeldState::HeldByThread);
5826                 debug_assert_ne!(self.claimable_payments.held_by_thread(), LockHeldState::HeldByThread);
5827                 debug_assert_ne!(self.per_peer_state.held_by_thread(), LockHeldState::HeldByThread);
5828
5829                 for action in actions.into_iter() {
5830                         match action {
5831                                 MonitorUpdateCompletionAction::PaymentClaimed { payment_hash } => {
5832                                         let payment = self.claimable_payments.lock().unwrap().pending_claiming_payments.remove(&payment_hash);
5833                                         if let Some(ClaimingPayment {
5834                                                 amount_msat,
5835                                                 payment_purpose: purpose,
5836                                                 receiver_node_id,
5837                                                 htlcs,
5838                                                 sender_intended_value: sender_intended_total_msat,
5839                                         }) = payment {
5840                                                 self.pending_events.lock().unwrap().push_back((events::Event::PaymentClaimed {
5841                                                         payment_hash,
5842                                                         purpose,
5843                                                         amount_msat,
5844                                                         receiver_node_id: Some(receiver_node_id),
5845                                                         htlcs,
5846                                                         sender_intended_total_msat,
5847                                                 }, None));
5848                                         }
5849                                 },
5850                                 MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
5851                                         event, downstream_counterparty_and_funding_outpoint
5852                                 } => {
5853                                         self.pending_events.lock().unwrap().push_back((event, None));
5854                                         if let Some((node_id, funding_outpoint, channel_id, blocker)) = downstream_counterparty_and_funding_outpoint {
5855                                                 self.handle_monitor_update_release(node_id, funding_outpoint, channel_id, Some(blocker));
5856                                         }
5857                                 },
5858                                 MonitorUpdateCompletionAction::FreeOtherChannelImmediately {
5859                                         downstream_counterparty_node_id, downstream_funding_outpoint, downstream_channel_id, blocking_action,
5860                                 } => {
5861                                         self.handle_monitor_update_release(
5862                                                 downstream_counterparty_node_id,
5863                                                 downstream_funding_outpoint,
5864                                                 downstream_channel_id,
5865                                                 Some(blocking_action),
5866                                         );
5867                                 },
5868                         }
5869                 }
5870         }
5871
5872         /// Handles a channel reentering a functional state, either due to reconnect or a monitor
5873         /// update completion.
5874         fn handle_channel_resumption(&self, pending_msg_events: &mut Vec<MessageSendEvent>,
5875                 channel: &mut Channel<SP>, raa: Option<msgs::RevokeAndACK>,
5876                 commitment_update: Option<msgs::CommitmentUpdate>, order: RAACommitmentOrder,
5877                 pending_forwards: Vec<(PendingHTLCInfo, u64)>, funding_broadcastable: Option<Transaction>,
5878                 channel_ready: Option<msgs::ChannelReady>, announcement_sigs: Option<msgs::AnnouncementSignatures>)
5879         -> Option<(u64, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)> {
5880                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5881                 log_trace!(logger, "Handling channel resumption for channel {} with {} RAA, {} commitment update, {} pending forwards, {}broadcasting funding, {} channel ready, {} announcement",
5882                         &channel.context.channel_id(),
5883                         if raa.is_some() { "an" } else { "no" },
5884                         if commitment_update.is_some() { "a" } else { "no" }, pending_forwards.len(),
5885                         if funding_broadcastable.is_some() { "" } else { "not " },
5886                         if channel_ready.is_some() { "sending" } else { "without" },
5887                         if announcement_sigs.is_some() { "sending" } else { "without" });
5888
5889                 let mut htlc_forwards = None;
5890
5891                 let counterparty_node_id = channel.context.get_counterparty_node_id();
5892                 if !pending_forwards.is_empty() {
5893                         htlc_forwards = Some((channel.context.get_short_channel_id().unwrap_or(channel.context.outbound_scid_alias()),
5894                                 channel.context.get_funding_txo().unwrap(), channel.context.channel_id(), channel.context.get_user_id(), pending_forwards));
5895                 }
5896
5897                 if let Some(msg) = channel_ready {
5898                         send_channel_ready!(self, pending_msg_events, channel, msg);
5899                 }
5900                 if let Some(msg) = announcement_sigs {
5901                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
5902                                 node_id: counterparty_node_id,
5903                                 msg,
5904                         });
5905                 }
5906
5907                 macro_rules! handle_cs { () => {
5908                         if let Some(update) = commitment_update {
5909                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
5910                                         node_id: counterparty_node_id,
5911                                         updates: update,
5912                                 });
5913                         }
5914                 } }
5915                 macro_rules! handle_raa { () => {
5916                         if let Some(revoke_and_ack) = raa {
5917                                 pending_msg_events.push(events::MessageSendEvent::SendRevokeAndACK {
5918                                         node_id: counterparty_node_id,
5919                                         msg: revoke_and_ack,
5920                                 });
5921                         }
5922                 } }
5923                 match order {
5924                         RAACommitmentOrder::CommitmentFirst => {
5925                                 handle_cs!();
5926                                 handle_raa!();
5927                         },
5928                         RAACommitmentOrder::RevokeAndACKFirst => {
5929                                 handle_raa!();
5930                                 handle_cs!();
5931                         },
5932                 }
5933
5934                 if let Some(tx) = funding_broadcastable {
5935                         log_info!(logger, "Broadcasting funding transaction with txid {}", tx.txid());
5936                         self.tx_broadcaster.broadcast_transactions(&[&tx]);
5937                 }
5938
5939                 {
5940                         let mut pending_events = self.pending_events.lock().unwrap();
5941                         emit_channel_pending_event!(pending_events, channel);
5942                         emit_channel_ready_event!(pending_events, channel);
5943                 }
5944
5945                 htlc_forwards
5946         }
5947
5948         fn channel_monitor_updated(&self, funding_txo: &OutPoint, channel_id: &ChannelId, highest_applied_update_id: u64, counterparty_node_id: Option<&PublicKey>) {
5949                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
5950
5951                 let counterparty_node_id = match counterparty_node_id {
5952                         Some(cp_id) => cp_id.clone(),
5953                         None => {
5954                                 // TODO: Once we can rely on the counterparty_node_id from the
5955                                 // monitor event, this and the outpoint_to_peer map should be removed.
5956                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
5957                                 match outpoint_to_peer.get(&funding_txo) {
5958                                         Some(cp_id) => cp_id.clone(),
5959                                         None => return,
5960                                 }
5961                         }
5962                 };
5963                 let per_peer_state = self.per_peer_state.read().unwrap();
5964                 let mut peer_state_lock;
5965                 let peer_state_mutex_opt = per_peer_state.get(&counterparty_node_id);
5966                 if peer_state_mutex_opt.is_none() { return }
5967                 peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
5968                 let peer_state = &mut *peer_state_lock;
5969                 let channel =
5970                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get_mut(&channel_id) {
5971                                 chan
5972                         } else {
5973                                 let update_actions = peer_state.monitor_update_blocked_actions
5974                                         .remove(&channel_id).unwrap_or(Vec::new());
5975                                 mem::drop(peer_state_lock);
5976                                 mem::drop(per_peer_state);
5977                                 self.handle_monitor_update_completion_actions(update_actions);
5978                                 return;
5979                         };
5980                 let remaining_in_flight =
5981                         if let Some(pending) = peer_state.in_flight_monitor_updates.get_mut(funding_txo) {
5982                                 pending.retain(|upd| upd.update_id > highest_applied_update_id);
5983                                 pending.len()
5984                         } else { 0 };
5985                 let logger = WithChannelContext::from(&self.logger, &channel.context);
5986                 log_trace!(logger, "ChannelMonitor updated to {}. Current highest is {}. {} pending in-flight updates.",
5987                         highest_applied_update_id, channel.context.get_latest_monitor_update_id(),
5988                         remaining_in_flight);
5989                 if !channel.is_awaiting_monitor_update() || channel.context.get_latest_monitor_update_id() != highest_applied_update_id {
5990                         return;
5991                 }
5992                 handle_monitor_update_completion!(self, peer_state_lock, peer_state, per_peer_state, channel);
5993         }
5994
5995         /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
5996         ///
5997         /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
5998         /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
5999         /// the channel.
6000         ///
6001         /// The `user_channel_id` parameter will be provided back in
6002         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
6003         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
6004         ///
6005         /// Note that this method will return an error and reject the channel, if it requires support
6006         /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
6007         /// used to accept such channels.
6008         ///
6009         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
6010         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
6011         pub fn accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
6012                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, false, user_channel_id)
6013         }
6014
6015         /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
6016         /// it as confirmed immediately.
6017         ///
6018         /// The `user_channel_id` parameter will be provided back in
6019         /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
6020         /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
6021         ///
6022         /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
6023         /// and (if the counterparty agrees), enables forwarding of payments immediately.
6024         ///
6025         /// This fully trusts that the counterparty has honestly and correctly constructed the funding
6026         /// transaction and blindly assumes that it will eventually confirm.
6027         ///
6028         /// If it does not confirm before we decide to close the channel, or if the funding transaction
6029         /// does not pay to the correct script the correct amount, *you will lose funds*.
6030         ///
6031         /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
6032         /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
6033         pub fn accept_inbound_channel_from_trusted_peer_0conf(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, user_channel_id: u128) -> Result<(), APIError> {
6034                 self.do_accept_inbound_channel(temporary_channel_id, counterparty_node_id, true, user_channel_id)
6035         }
6036
6037         fn do_accept_inbound_channel(&self, temporary_channel_id: &ChannelId, counterparty_node_id: &PublicKey, accept_0conf: bool, user_channel_id: u128) -> Result<(), APIError> {
6038
6039                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(*temporary_channel_id));
6040                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
6041
6042                 let peers_without_funded_channels =
6043                         self.peers_without_funded_channels(|peer| { peer.total_channel_count() > 0 });
6044                 let per_peer_state = self.per_peer_state.read().unwrap();
6045                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6046                 .ok_or_else(|| {
6047                         let err_str = format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id);
6048                         log_error!(logger, "{}", err_str);
6049
6050                         APIError::ChannelUnavailable { err: err_str }
6051                 })?;
6052                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6053                 let peer_state = &mut *peer_state_lock;
6054                 let is_only_peer_channel = peer_state.total_channel_count() == 1;
6055
6056                 // Find (and remove) the channel in the unaccepted table. If it's not there, something weird is
6057                 // happening and return an error. N.B. that we create channel with an outbound SCID of zero so
6058                 // that we can delay allocating the SCID until after we're sure that the checks below will
6059                 // succeed.
6060                 let mut channel = match peer_state.inbound_channel_request_by_id.remove(temporary_channel_id) {
6061                         Some(unaccepted_channel) => {
6062                                 let best_block_height = self.best_block.read().unwrap().height();
6063                                 InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6064                                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features,
6065                                         &unaccepted_channel.open_channel_msg, user_channel_id, &self.default_configuration, best_block_height,
6066                                         &self.logger, accept_0conf).map_err(|e| {
6067                                                 let err_str = e.to_string();
6068                                                 log_error!(logger, "{}", err_str);
6069
6070                                                 APIError::ChannelUnavailable { err: err_str }
6071                                         })
6072                                 }
6073                         _ => {
6074                                 let err_str = "No such channel awaiting to be accepted.".to_owned();
6075                                 log_error!(logger, "{}", err_str);
6076
6077                                 Err(APIError::APIMisuseError { err: err_str })
6078                         }
6079                 }?;
6080
6081                 if accept_0conf {
6082                         // This should have been correctly configured by the call to InboundV1Channel::new.
6083                         debug_assert!(channel.context.minimum_depth().unwrap() == 0);
6084                 } else if channel.context.get_channel_type().requires_zero_conf() {
6085                         let send_msg_err_event = events::MessageSendEvent::HandleError {
6086                                 node_id: channel.context.get_counterparty_node_id(),
6087                                 action: msgs::ErrorAction::SendErrorMessage{
6088                                         msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "No zero confirmation channels accepted".to_owned(), }
6089                                 }
6090                         };
6091                         peer_state.pending_msg_events.push(send_msg_err_event);
6092                         let err_str = "Please use accept_inbound_channel_from_trusted_peer_0conf to accept channels with zero confirmations.".to_owned();
6093                         log_error!(logger, "{}", err_str);
6094
6095                         return Err(APIError::APIMisuseError { err: err_str });
6096                 } else {
6097                         // If this peer already has some channels, a new channel won't increase our number of peers
6098                         // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6099                         // channels per-peer we can accept channels from a peer with existing ones.
6100                         if is_only_peer_channel && peers_without_funded_channels >= MAX_UNFUNDED_CHANNEL_PEERS {
6101                                 let send_msg_err_event = events::MessageSendEvent::HandleError {
6102                                         node_id: channel.context.get_counterparty_node_id(),
6103                                         action: msgs::ErrorAction::SendErrorMessage{
6104                                                 msg: msgs::ErrorMessage { channel_id: temporary_channel_id.clone(), data: "Have too many peers with unfunded channels, not accepting new ones".to_owned(), }
6105                                         }
6106                                 };
6107                                 peer_state.pending_msg_events.push(send_msg_err_event);
6108                                 let err_str = "Too many peers with unfunded channels, refusing to accept new ones".to_owned();
6109                                 log_error!(logger, "{}", err_str);
6110
6111                                 return Err(APIError::APIMisuseError { err: err_str });
6112                         }
6113                 }
6114
6115                 // Now that we know we have a channel, assign an outbound SCID alias.
6116                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6117                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6118
6119                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6120                         node_id: channel.context.get_counterparty_node_id(),
6121                         msg: channel.accept_inbound_channel(),
6122                 });
6123
6124                 peer_state.channel_by_id.insert(temporary_channel_id.clone(), ChannelPhase::UnfundedInboundV1(channel));
6125
6126                 Ok(())
6127         }
6128
6129         /// Gets the number of peers which match the given filter and do not have any funded, outbound,
6130         /// or 0-conf channels.
6131         ///
6132         /// The filter is called for each peer and provided with the number of unfunded, inbound, and
6133         /// non-0-conf channels we have with the peer.
6134         fn peers_without_funded_channels<Filter>(&self, maybe_count_peer: Filter) -> usize
6135         where Filter: Fn(&PeerState<SP>) -> bool {
6136                 let mut peers_without_funded_channels = 0;
6137                 let best_block_height = self.best_block.read().unwrap().height();
6138                 {
6139                         let peer_state_lock = self.per_peer_state.read().unwrap();
6140                         for (_, peer_mtx) in peer_state_lock.iter() {
6141                                 let peer = peer_mtx.lock().unwrap();
6142                                 if !maybe_count_peer(&*peer) { continue; }
6143                                 let num_unfunded_channels = Self::unfunded_channel_count(&peer, best_block_height);
6144                                 if num_unfunded_channels == peer.total_channel_count() {
6145                                         peers_without_funded_channels += 1;
6146                                 }
6147                         }
6148                 }
6149                 return peers_without_funded_channels;
6150         }
6151
6152         fn unfunded_channel_count(
6153                 peer: &PeerState<SP>, best_block_height: u32
6154         ) -> usize {
6155                 let mut num_unfunded_channels = 0;
6156                 for (_, phase) in peer.channel_by_id.iter() {
6157                         match phase {
6158                                 ChannelPhase::Funded(chan) => {
6159                                         // This covers non-zero-conf inbound `Channel`s that we are currently monitoring, but those
6160                                         // which have not yet had any confirmations on-chain.
6161                                         if !chan.context.is_outbound() && chan.context.minimum_depth().unwrap_or(1) != 0 &&
6162                                                 chan.context.get_funding_tx_confirmations(best_block_height) == 0
6163                                         {
6164                                                 num_unfunded_channels += 1;
6165                                         }
6166                                 },
6167                                 ChannelPhase::UnfundedInboundV1(chan) => {
6168                                         if chan.context.minimum_depth().unwrap_or(1) != 0 {
6169                                                 num_unfunded_channels += 1;
6170                                         }
6171                                 },
6172                                 ChannelPhase::UnfundedOutboundV1(_) => {
6173                                         // Outbound channels don't contribute to the unfunded count in the DoS context.
6174                                         continue;
6175                                 }
6176                         }
6177                 }
6178                 num_unfunded_channels + peer.inbound_channel_request_by_id.len()
6179         }
6180
6181         fn internal_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) -> Result<(), MsgHandleErrInternal> {
6182                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6183                 // likely to be lost on restart!
6184                 if msg.chain_hash != self.chain_hash {
6185                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Unknown genesis block hash".to_owned(), msg.temporary_channel_id.clone()));
6186                 }
6187
6188                 if !self.default_configuration.accept_inbound_channels {
6189                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No inbound channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6190                 }
6191
6192                 // Get the number of peers with channels, but without funded ones. We don't care too much
6193                 // about peers that never open a channel, so we filter by peers that have at least one
6194                 // channel, and then limit the number of those with unfunded channels.
6195                 let channeled_peers_without_funding =
6196                         self.peers_without_funded_channels(|node| node.total_channel_count() > 0);
6197
6198                 let per_peer_state = self.per_peer_state.read().unwrap();
6199                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6200                     .ok_or_else(|| {
6201                                 debug_assert!(false);
6202                                 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.clone())
6203                         })?;
6204                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6205                 let peer_state = &mut *peer_state_lock;
6206
6207                 // If this peer already has some channels, a new channel won't increase our number of peers
6208                 // with unfunded channels, so as long as we aren't over the maximum number of unfunded
6209                 // channels per-peer we can accept channels from a peer with existing ones.
6210                 if peer_state.total_channel_count() == 0 &&
6211                         channeled_peers_without_funding >= MAX_UNFUNDED_CHANNEL_PEERS &&
6212                         !self.default_configuration.manually_accept_inbound_channels
6213                 {
6214                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6215                                 "Have too many peers with unfunded channels, not accepting new ones".to_owned(),
6216                                 msg.temporary_channel_id.clone()));
6217                 }
6218
6219                 let best_block_height = self.best_block.read().unwrap().height();
6220                 if Self::unfunded_channel_count(peer_state, best_block_height) >= MAX_UNFUNDED_CHANS_PER_PEER {
6221                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
6222                                 format!("Refusing more than {} unfunded channels.", MAX_UNFUNDED_CHANS_PER_PEER),
6223                                 msg.temporary_channel_id.clone()));
6224                 }
6225
6226                 let channel_id = msg.temporary_channel_id;
6227                 let channel_exists = peer_state.has_channel(&channel_id);
6228                 if channel_exists {
6229                         return Err(MsgHandleErrInternal::send_err_msg_no_close("temporary_channel_id collision for the same peer!".to_owned(), msg.temporary_channel_id.clone()));
6230                 }
6231
6232                 // If we're doing manual acceptance checks on the channel, then defer creation until we're sure we want to accept.
6233                 if self.default_configuration.manually_accept_inbound_channels {
6234                         let channel_type = channel::channel_type_from_open_channel(
6235                                         &msg, &peer_state.latest_features, &self.channel_type_features()
6236                                 ).map_err(|e|
6237                                         MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id)
6238                                 )?;
6239                         let mut pending_events = self.pending_events.lock().unwrap();
6240                         pending_events.push_back((events::Event::OpenChannelRequest {
6241                                 temporary_channel_id: msg.temporary_channel_id.clone(),
6242                                 counterparty_node_id: counterparty_node_id.clone(),
6243                                 funding_satoshis: msg.funding_satoshis,
6244                                 push_msat: msg.push_msat,
6245                                 channel_type,
6246                         }, None));
6247                         peer_state.inbound_channel_request_by_id.insert(channel_id, InboundChannelRequest {
6248                                 open_channel_msg: msg.clone(),
6249                                 ticks_remaining: UNACCEPTED_INBOUND_CHANNEL_AGE_LIMIT_TICKS,
6250                         });
6251                         return Ok(());
6252                 }
6253
6254                 // Otherwise create the channel right now.
6255                 let mut random_bytes = [0u8; 16];
6256                 random_bytes.copy_from_slice(&self.entropy_source.get_secure_random_bytes()[..16]);
6257                 let user_channel_id = u128::from_be_bytes(random_bytes);
6258                 let mut channel = match InboundV1Channel::new(&self.fee_estimator, &self.entropy_source, &self.signer_provider,
6259                         counterparty_node_id.clone(), &self.channel_type_features(), &peer_state.latest_features, msg, user_channel_id,
6260                         &self.default_configuration, best_block_height, &self.logger, /*is_0conf=*/false)
6261                 {
6262                         Err(e) => {
6263                                 return Err(MsgHandleErrInternal::from_chan_no_close(e, msg.temporary_channel_id));
6264                         },
6265                         Ok(res) => res
6266                 };
6267
6268                 let channel_type = channel.context.get_channel_type();
6269                 if channel_type.requires_zero_conf() {
6270                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No zero confirmation channels accepted".to_owned(), msg.temporary_channel_id.clone()));
6271                 }
6272                 if channel_type.requires_anchors_zero_fee_htlc_tx() {
6273                         return Err(MsgHandleErrInternal::send_err_msg_no_close("No channels with anchor outputs accepted".to_owned(), msg.temporary_channel_id.clone()));
6274                 }
6275
6276                 let outbound_scid_alias = self.create_and_insert_outbound_scid_alias();
6277                 channel.context.set_outbound_scid_alias(outbound_scid_alias);
6278
6279                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAcceptChannel {
6280                         node_id: counterparty_node_id.clone(),
6281                         msg: channel.accept_inbound_channel(),
6282                 });
6283                 peer_state.channel_by_id.insert(channel_id, ChannelPhase::UnfundedInboundV1(channel));
6284                 Ok(())
6285         }
6286
6287         fn internal_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) -> Result<(), MsgHandleErrInternal> {
6288                 // Note that the ChannelManager is NOT re-persisted on disk after this, so any changes are
6289                 // likely to be lost on restart!
6290                 let (value, output_script, user_id) = {
6291                         let per_peer_state = self.per_peer_state.read().unwrap();
6292                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6293                                 .ok_or_else(|| {
6294                                         debug_assert!(false);
6295                                         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)
6296                                 })?;
6297                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6298                         let peer_state = &mut *peer_state_lock;
6299                         match peer_state.channel_by_id.entry(msg.temporary_channel_id) {
6300                                 hash_map::Entry::Occupied(mut phase) => {
6301                                         match phase.get_mut() {
6302                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
6303                                                         try_chan_phase_entry!(self, chan.accept_channel(&msg, &self.default_configuration.channel_handshake_limits, &peer_state.latest_features), phase);
6304                                                         (chan.context.get_value_satoshis(), chan.context.get_funding_redeemscript().to_v0_p2wsh(), chan.context.get_user_id())
6305                                                 },
6306                                                 _ => {
6307                                                         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.temporary_channel_id));
6308                                                 }
6309                                         }
6310                                 },
6311                                 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.temporary_channel_id))
6312                         }
6313                 };
6314                 let mut pending_events = self.pending_events.lock().unwrap();
6315                 pending_events.push_back((events::Event::FundingGenerationReady {
6316                         temporary_channel_id: msg.temporary_channel_id,
6317                         counterparty_node_id: *counterparty_node_id,
6318                         channel_value_satoshis: value,
6319                         output_script,
6320                         user_channel_id: user_id,
6321                 }, None));
6322                 Ok(())
6323         }
6324
6325         fn internal_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) -> Result<(), MsgHandleErrInternal> {
6326                 let best_block = *self.best_block.read().unwrap();
6327
6328                 let per_peer_state = self.per_peer_state.read().unwrap();
6329                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6330                         .ok_or_else(|| {
6331                                 debug_assert!(false);
6332                                 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)
6333                         })?;
6334
6335                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6336                 let peer_state = &mut *peer_state_lock;
6337                 let (mut chan, funding_msg_opt, monitor) =
6338                         match peer_state.channel_by_id.remove(&msg.temporary_channel_id) {
6339                                 Some(ChannelPhase::UnfundedInboundV1(inbound_chan)) => {
6340                                         let logger = WithChannelContext::from(&self.logger, &inbound_chan.context);
6341                                         match inbound_chan.funding_created(msg, best_block, &self.signer_provider, &&logger) {
6342                                                 Ok(res) => res,
6343                                                 Err((inbound_chan, err)) => {
6344                                                         // We've already removed this inbound channel from the map in `PeerState`
6345                                                         // above so at this point we just need to clean up any lingering entries
6346                                                         // concerning this channel as it is safe to do so.
6347                                                         debug_assert!(matches!(err, ChannelError::Close(_)));
6348                                                         // Really we should be returning the channel_id the peer expects based
6349                                                         // on their funding info here, but they're horribly confused anyway, so
6350                                                         // there's not a lot we can do to save them.
6351                                                         return Err(convert_chan_phase_err!(self, err, &mut ChannelPhase::UnfundedInboundV1(inbound_chan), &msg.temporary_channel_id).1);
6352                                                 },
6353                                         }
6354                                 },
6355                                 Some(mut phase) => {
6356                                         let err_msg = format!("Got an unexpected funding_created message from peer with counterparty_node_id {}", counterparty_node_id);
6357                                         let err = ChannelError::Close(err_msg);
6358                                         return Err(convert_chan_phase_err!(self, err, &mut phase, &msg.temporary_channel_id).1);
6359                                 },
6360                                 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))
6361                         };
6362
6363                 let funded_channel_id = chan.context.channel_id();
6364
6365                 macro_rules! fail_chan { ($err: expr) => { {
6366                         // Note that at this point we've filled in the funding outpoint on our
6367                         // channel, but its actually in conflict with another channel. Thus, if
6368                         // we call `convert_chan_phase_err` immediately (thus calling
6369                         // `update_maps_on_chan_removal`), we'll remove the existing channel
6370                         // from `outpoint_to_peer`. Thus, we must first unset the funding outpoint
6371                         // on the channel.
6372                         let err = ChannelError::Close($err.to_owned());
6373                         chan.unset_funding_info(msg.temporary_channel_id);
6374                         return Err(convert_chan_phase_err!(self, err, chan, &funded_channel_id, UNFUNDED_CHANNEL).1);
6375                 } } }
6376
6377                 match peer_state.channel_by_id.entry(funded_channel_id) {
6378                         hash_map::Entry::Occupied(_) => {
6379                                 fail_chan!("Already had channel with the new channel_id");
6380                         },
6381                         hash_map::Entry::Vacant(e) => {
6382                                 let mut outpoint_to_peer_lock = self.outpoint_to_peer.lock().unwrap();
6383                                 match outpoint_to_peer_lock.entry(monitor.get_funding_txo().0) {
6384                                         hash_map::Entry::Occupied(_) => {
6385                                                 fail_chan!("The funding_created message had the same funding_txid as an existing channel - funding is not possible");
6386                                         },
6387                                         hash_map::Entry::Vacant(i_e) => {
6388                                                 let monitor_res = self.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
6389                                                 if let Ok(persist_state) = monitor_res {
6390                                                         i_e.insert(chan.context.get_counterparty_node_id());
6391                                                         mem::drop(outpoint_to_peer_lock);
6392
6393                                                         // There's no problem signing a counterparty's funding transaction if our monitor
6394                                                         // hasn't persisted to disk yet - we can't lose money on a transaction that we haven't
6395                                                         // accepted payment from yet. We do, however, need to wait to send our channel_ready
6396                                                         // until we have persisted our monitor.
6397                                                         if let Some(msg) = funding_msg_opt {
6398                                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
6399                                                                         node_id: counterparty_node_id.clone(),
6400                                                                         msg,
6401                                                                 });
6402                                                         }
6403
6404                                                         if let ChannelPhase::Funded(chan) = e.insert(ChannelPhase::Funded(chan)) {
6405                                                                 handle_new_monitor_update!(self, persist_state, peer_state_lock, peer_state,
6406                                                                         per_peer_state, chan, INITIAL_MONITOR);
6407                                                         } else {
6408                                                                 unreachable!("This must be a funded channel as we just inserted it.");
6409                                                         }
6410                                                         Ok(())
6411                                                 } else {
6412                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6413                                                         log_error!(logger, "Persisting initial ChannelMonitor failed, implying the funding outpoint was duplicated");
6414                                                         fail_chan!("Duplicate funding outpoint");
6415                                                 }
6416                                         }
6417                                 }
6418                         }
6419                 }
6420         }
6421
6422         fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
6423                 let best_block = *self.best_block.read().unwrap();
6424                 let per_peer_state = self.per_peer_state.read().unwrap();
6425                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6426                         .ok_or_else(|| {
6427                                 debug_assert!(false);
6428                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6429                         })?;
6430
6431                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6432                 let peer_state = &mut *peer_state_lock;
6433                 match peer_state.channel_by_id.entry(msg.channel_id) {
6434                         hash_map::Entry::Occupied(chan_phase_entry) => {
6435                                 if matches!(chan_phase_entry.get(), ChannelPhase::UnfundedOutboundV1(_)) {
6436                                         let chan = if let ChannelPhase::UnfundedOutboundV1(chan) = chan_phase_entry.remove() { chan } else { unreachable!() };
6437                                         let logger = WithContext::from(
6438                                                 &self.logger,
6439                                                 Some(chan.context.get_counterparty_node_id()),
6440                                                 Some(chan.context.channel_id())
6441                                         );
6442                                         let res =
6443                                                 chan.funding_signed(&msg, best_block, &self.signer_provider, &&logger);
6444                                         match res {
6445                                                 Ok((mut chan, monitor)) => {
6446                                                         if let Ok(persist_status) = self.chain_monitor.watch_channel(chan.context.get_funding_txo().unwrap(), monitor) {
6447                                                                 // We really should be able to insert here without doing a second
6448                                                                 // lookup, but sadly rust stdlib doesn't currently allow keeping
6449                                                                 // the original Entry around with the value removed.
6450                                                                 let mut chan = peer_state.channel_by_id.entry(msg.channel_id).or_insert(ChannelPhase::Funded(chan));
6451                                                                 if let ChannelPhase::Funded(ref mut chan) = &mut chan {
6452                                                                         handle_new_monitor_update!(self, persist_status, peer_state_lock, peer_state, per_peer_state, chan, INITIAL_MONITOR);
6453                                                                 } else { unreachable!(); }
6454                                                                 Ok(())
6455                                                         } else {
6456                                                                 let e = ChannelError::Close("Channel funding outpoint was a duplicate".to_owned());
6457                                                                 // We weren't able to watch the channel to begin with, so no
6458                                                                 // updates should be made on it. Previously, full_stack_target
6459                                                                 // found an (unreachable) panic when the monitor update contained
6460                                                                 // within `shutdown_finish` was applied.
6461                                                                 chan.unset_funding_info(msg.channel_id);
6462                                                                 return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::Funded(chan), &msg.channel_id).1);
6463                                                         }
6464                                                 },
6465                                                 Err((chan, e)) => {
6466                                                         debug_assert!(matches!(e, ChannelError::Close(_)),
6467                                                                 "We don't have a channel anymore, so the error better have expected close");
6468                                                         // We've already removed this outbound channel from the map in
6469                                                         // `PeerState` above so at this point we just need to clean up any
6470                                                         // lingering entries concerning this channel as it is safe to do so.
6471                                                         return Err(convert_chan_phase_err!(self, e, &mut ChannelPhase::UnfundedOutboundV1(chan), &msg.channel_id).1);
6472                                                 }
6473                                         }
6474                                 } else {
6475                                         return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id));
6476                                 }
6477                         },
6478                         hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
6479                 }
6480         }
6481
6482         fn internal_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) -> Result<(), MsgHandleErrInternal> {
6483                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6484                 // closing a channel), so any changes are likely to be lost on restart!
6485                 let per_peer_state = self.per_peer_state.read().unwrap();
6486                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6487                         .ok_or_else(|| {
6488                                 debug_assert!(false);
6489                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6490                         })?;
6491                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6492                 let peer_state = &mut *peer_state_lock;
6493                 match peer_state.channel_by_id.entry(msg.channel_id) {
6494                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6495                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6496                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6497                                         let announcement_sigs_opt = try_chan_phase_entry!(self, chan.channel_ready(&msg, &self.node_signer,
6498                                                 self.chain_hash, &self.default_configuration, &self.best_block.read().unwrap(), &&logger), chan_phase_entry);
6499                                         if let Some(announcement_sigs) = announcement_sigs_opt {
6500                                                 log_trace!(logger, "Sending announcement_signatures for channel {}", chan.context.channel_id());
6501                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
6502                                                         node_id: counterparty_node_id.clone(),
6503                                                         msg: announcement_sigs,
6504                                                 });
6505                                         } else if chan.context.is_usable() {
6506                                                 // If we're sending an announcement_signatures, we'll send the (public)
6507                                                 // channel_update after sending a channel_announcement when we receive our
6508                                                 // counterparty's announcement_signatures. Thus, we only bother to send a
6509                                                 // channel_update here if the channel is not public, i.e. we're not sending an
6510                                                 // announcement_signatures.
6511                                                 log_trace!(logger, "Sending private initial channel_update for our counterparty on channel {}", chan.context.channel_id());
6512                                                 if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
6513                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
6514                                                                 node_id: counterparty_node_id.clone(),
6515                                                                 msg,
6516                                                         });
6517                                                 }
6518                                         }
6519
6520                                         {
6521                                                 let mut pending_events = self.pending_events.lock().unwrap();
6522                                                 emit_channel_ready_event!(pending_events, chan);
6523                                         }
6524
6525                                         Ok(())
6526                                 } else {
6527                                         try_chan_phase_entry!(self, Err(ChannelError::Close(
6528                                                 "Got a channel_ready message for an unfunded channel!".into())), chan_phase_entry)
6529                                 }
6530                         },
6531                         hash_map::Entry::Vacant(_) => {
6532                                 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))
6533                         }
6534                 }
6535         }
6536
6537         fn internal_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) -> Result<(), MsgHandleErrInternal> {
6538                 let mut dropped_htlcs: Vec<(HTLCSource, PaymentHash)> = Vec::new();
6539                 let mut finish_shutdown = None;
6540                 {
6541                         let per_peer_state = self.per_peer_state.read().unwrap();
6542                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6543                                 .ok_or_else(|| {
6544                                         debug_assert!(false);
6545                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6546                                 })?;
6547                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6548                         let peer_state = &mut *peer_state_lock;
6549                         if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6550                                 let phase = chan_phase_entry.get_mut();
6551                                 match phase {
6552                                         ChannelPhase::Funded(chan) => {
6553                                                 if !chan.received_shutdown() {
6554                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6555                                                         log_info!(logger, "Received a shutdown message from our counterparty for channel {}{}.",
6556                                                                 msg.channel_id,
6557                                                                 if chan.sent_shutdown() { " after we initiated shutdown" } else { "" });
6558                                                 }
6559
6560                                                 let funding_txo_opt = chan.context.get_funding_txo();
6561                                                 let (shutdown, monitor_update_opt, htlcs) = try_chan_phase_entry!(self,
6562                                                         chan.shutdown(&self.signer_provider, &peer_state.latest_features, &msg), chan_phase_entry);
6563                                                 dropped_htlcs = htlcs;
6564
6565                                                 if let Some(msg) = shutdown {
6566                                                         // We can send the `shutdown` message before updating the `ChannelMonitor`
6567                                                         // here as we don't need the monitor update to complete until we send a
6568                                                         // `shutdown_signed`, which we'll delay if we're pending a monitor update.
6569                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
6570                                                                 node_id: *counterparty_node_id,
6571                                                                 msg,
6572                                                         });
6573                                                 }
6574                                                 // Update the monitor with the shutdown script if necessary.
6575                                                 if let Some(monitor_update) = monitor_update_opt {
6576                                                         handle_new_monitor_update!(self, funding_txo_opt.unwrap(), chan.context.channel_id(), monitor_update,
6577                                                                 peer_state_lock, peer_state, per_peer_state, chan);
6578                                                 }
6579                                         },
6580                                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
6581                                                 let context = phase.context_mut();
6582                                                 let logger = WithChannelContext::from(&self.logger, context);
6583                                                 log_error!(logger, "Immediately closing unfunded channel {} as peer asked to cooperatively shut it down (which is unnecessary)", &msg.channel_id);
6584                                                 let mut chan = remove_channel_phase!(self, chan_phase_entry);
6585                                                 finish_shutdown = Some(chan.context_mut().force_shutdown(false, ClosureReason::CounterpartyCoopClosedUnfundedChannel));
6586                                         },
6587                                 }
6588                         } else {
6589                                 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))
6590                         }
6591                 }
6592                 for htlc_source in dropped_htlcs.drain(..) {
6593                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id.clone()), channel_id: msg.channel_id };
6594                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
6595                         self.fail_htlc_backwards_internal(&htlc_source.0, &htlc_source.1, &reason, receiver);
6596                 }
6597                 if let Some(shutdown_res) = finish_shutdown {
6598                         self.finish_close_channel(shutdown_res);
6599                 }
6600
6601                 Ok(())
6602         }
6603
6604         fn internal_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) -> Result<(), MsgHandleErrInternal> {
6605                 let per_peer_state = self.per_peer_state.read().unwrap();
6606                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6607                         .ok_or_else(|| {
6608                                 debug_assert!(false);
6609                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6610                         })?;
6611                 let (tx, chan_option, shutdown_result) = {
6612                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6613                         let peer_state = &mut *peer_state_lock;
6614                         match peer_state.channel_by_id.entry(msg.channel_id.clone()) {
6615                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6616                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6617                                                 let (closing_signed, tx, shutdown_result) = try_chan_phase_entry!(self, chan.closing_signed(&self.fee_estimator, &msg), chan_phase_entry);
6618                                                 debug_assert_eq!(shutdown_result.is_some(), chan.is_shutdown());
6619                                                 if let Some(msg) = closing_signed {
6620                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
6621                                                                 node_id: counterparty_node_id.clone(),
6622                                                                 msg,
6623                                                         });
6624                                                 }
6625                                                 if tx.is_some() {
6626                                                         // We're done with this channel, we've got a signed closing transaction and
6627                                                         // will send the closing_signed back to the remote peer upon return. This
6628                                                         // also implies there are no pending HTLCs left on the channel, so we can
6629                                                         // fully delete it from tracking (the channel monitor is still around to
6630                                                         // watch for old state broadcasts)!
6631                                                         (tx, Some(remove_channel_phase!(self, chan_phase_entry)), shutdown_result)
6632                                                 } else { (tx, None, shutdown_result) }
6633                                         } else {
6634                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6635                                                         "Got a closing_signed message for an unfunded channel!".into())), chan_phase_entry);
6636                                         }
6637                                 },
6638                                 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))
6639                         }
6640                 };
6641                 if let Some(broadcast_tx) = tx {
6642                         let channel_id = chan_option.as_ref().map(|channel| channel.context().channel_id());
6643                         log_info!(WithContext::from(&self.logger, Some(*counterparty_node_id), channel_id), "Broadcasting {}", log_tx!(broadcast_tx));
6644                         self.tx_broadcaster.broadcast_transactions(&[&broadcast_tx]);
6645                 }
6646                 if let Some(ChannelPhase::Funded(chan)) = chan_option {
6647                         if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
6648                                 let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
6649                                 pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
6650                                         msg: update
6651                                 });
6652                         }
6653                 }
6654                 mem::drop(per_peer_state);
6655                 if let Some(shutdown_result) = shutdown_result {
6656                         self.finish_close_channel(shutdown_result);
6657                 }
6658                 Ok(())
6659         }
6660
6661         fn internal_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) -> Result<(), MsgHandleErrInternal> {
6662                 //TODO: BOLT 4 points out a specific attack where a peer may re-send an onion packet and
6663                 //determine the state of the payment based on our response/if we forward anything/the time
6664                 //we take to respond. We should take care to avoid allowing such an attack.
6665                 //
6666                 //TODO: There exists a further attack where a node may garble the onion data, forward it to
6667                 //us repeatedly garbled in different ways, and compare our error messages, which are
6668                 //encrypted with the same key. It's not immediately obvious how to usefully exploit that,
6669                 //but we should prevent it anyway.
6670
6671                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6672                 // closing a channel), so any changes are likely to be lost on restart!
6673
6674                 let decoded_hop_res = self.decode_update_add_htlc_onion(msg, counterparty_node_id);
6675                 let per_peer_state = self.per_peer_state.read().unwrap();
6676                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6677                         .ok_or_else(|| {
6678                                 debug_assert!(false);
6679                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6680                         })?;
6681                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6682                 let peer_state = &mut *peer_state_lock;
6683                 match peer_state.channel_by_id.entry(msg.channel_id) {
6684                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6685                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6686                                         let pending_forward_info = match decoded_hop_res {
6687                                                 Ok((next_hop, shared_secret, next_packet_pk_opt)) =>
6688                                                         self.construct_pending_htlc_status(
6689                                                                 msg, counterparty_node_id, shared_secret, next_hop,
6690                                                                 chan.context.config().accept_underpaying_htlcs, next_packet_pk_opt,
6691                                                         ),
6692                                                 Err(e) => PendingHTLCStatus::Fail(e)
6693                                         };
6694                                         let create_pending_htlc_status = |chan: &Channel<SP>, pending_forward_info: PendingHTLCStatus, error_code: u16| {
6695                                                 if msg.blinding_point.is_some() {
6696                                                         return PendingHTLCStatus::Fail(HTLCFailureMsg::Malformed(
6697                                                                         msgs::UpdateFailMalformedHTLC {
6698                                                                                 channel_id: msg.channel_id,
6699                                                                                 htlc_id: msg.htlc_id,
6700                                                                                 sha256_of_onion: [0; 32],
6701                                                                                 failure_code: INVALID_ONION_BLINDING,
6702                                                                         }
6703                                                         ))
6704                                                 }
6705                                                 // If the update_add is completely bogus, the call will Err and we will close,
6706                                                 // but if we've sent a shutdown and they haven't acknowledged it yet, we just
6707                                                 // want to reject the new HTLC and fail it backwards instead of forwarding.
6708                                                 match pending_forward_info {
6709                                                         PendingHTLCStatus::Forward(PendingHTLCInfo {
6710                                                                 ref incoming_shared_secret, ref routing, ..
6711                                                         }) => {
6712                                                                 let reason = if routing.blinded_failure().is_some() {
6713                                                                         HTLCFailReason::reason(INVALID_ONION_BLINDING, vec![0; 32])
6714                                                                 } else if (error_code & 0x1000) != 0 {
6715                                                                         let (real_code, error_data) = self.get_htlc_inbound_temp_fail_err_and_data(error_code, chan);
6716                                                                         HTLCFailReason::reason(real_code, error_data)
6717                                                                 } else {
6718                                                                         HTLCFailReason::from_failure_code(error_code)
6719                                                                 }.get_encrypted_failure_packet(incoming_shared_secret, &None);
6720                                                                 let msg = msgs::UpdateFailHTLC {
6721                                                                         channel_id: msg.channel_id,
6722                                                                         htlc_id: msg.htlc_id,
6723                                                                         reason
6724                                                                 };
6725                                                                 PendingHTLCStatus::Fail(HTLCFailureMsg::Relay(msg))
6726                                                         },
6727                                                         _ => pending_forward_info
6728                                                 }
6729                                         };
6730                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6731                                         try_chan_phase_entry!(self, chan.update_add_htlc(&msg, pending_forward_info, create_pending_htlc_status, &self.fee_estimator, &&logger), chan_phase_entry);
6732                                 } else {
6733                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6734                                                 "Got an update_add_htlc message for an unfunded channel!".into())), chan_phase_entry);
6735                                 }
6736                         },
6737                         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))
6738                 }
6739                 Ok(())
6740         }
6741
6742         fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
6743                 let funding_txo;
6744                 let (htlc_source, forwarded_htlc_value) = {
6745                         let per_peer_state = self.per_peer_state.read().unwrap();
6746                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6747                                 .ok_or_else(|| {
6748                                         debug_assert!(false);
6749                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6750                                 })?;
6751                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6752                         let peer_state = &mut *peer_state_lock;
6753                         match peer_state.channel_by_id.entry(msg.channel_id) {
6754                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
6755                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6756                                                 let res = try_chan_phase_entry!(self, chan.update_fulfill_htlc(&msg), chan_phase_entry);
6757                                                 if let HTLCSource::PreviousHopData(prev_hop) = &res.0 {
6758                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6759                                                         log_trace!(logger,
6760                                                                 "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
6761                                                                 msg.channel_id);
6762                                                         peer_state.actions_blocking_raa_monitor_updates.entry(msg.channel_id)
6763                                                                 .or_insert_with(Vec::new)
6764                                                                 .push(RAAMonitorUpdateBlockingAction::from_prev_hop_data(&prev_hop));
6765                                                 }
6766                                                 // Note that we do not need to push an `actions_blocking_raa_monitor_updates`
6767                                                 // entry here, even though we *do* need to block the next RAA monitor update.
6768                                                 // We do this instead in the `claim_funds_internal` by attaching a
6769                                                 // `ReleaseRAAChannelMonitorUpdate` action to the event generated when the
6770                                                 // outbound HTLC is claimed. This is guaranteed to all complete before we
6771                                                 // process the RAA as messages are processed from single peers serially.
6772                                                 funding_txo = chan.context.get_funding_txo().expect("We won't accept a fulfill until funded");
6773                                                 res
6774                                         } else {
6775                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
6776                                                         "Got an update_fulfill_htlc message for an unfunded channel!".into())), chan_phase_entry);
6777                                         }
6778                                 },
6779                                 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))
6780                         }
6781                 };
6782                 self.claim_funds_internal(htlc_source, msg.payment_preimage.clone(), Some(forwarded_htlc_value),
6783                         false, false, Some(*counterparty_node_id), funding_txo, msg.channel_id);
6784                 Ok(())
6785         }
6786
6787         fn internal_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) -> Result<(), MsgHandleErrInternal> {
6788                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6789                 // closing a channel), so any changes are likely to be lost on restart!
6790                 let per_peer_state = self.per_peer_state.read().unwrap();
6791                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6792                         .ok_or_else(|| {
6793                                 debug_assert!(false);
6794                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6795                         })?;
6796                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6797                 let peer_state = &mut *peer_state_lock;
6798                 match peer_state.channel_by_id.entry(msg.channel_id) {
6799                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6800                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6801                                         try_chan_phase_entry!(self, chan.update_fail_htlc(&msg, HTLCFailReason::from_msg(msg)), chan_phase_entry);
6802                                 } else {
6803                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6804                                                 "Got an update_fail_htlc message for an unfunded channel!".into())), chan_phase_entry);
6805                                 }
6806                         },
6807                         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))
6808                 }
6809                 Ok(())
6810         }
6811
6812         fn internal_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) -> Result<(), MsgHandleErrInternal> {
6813                 // Note that the ChannelManager is NOT re-persisted on disk after this (unless we error
6814                 // closing a channel), so any changes are likely to be lost on restart!
6815                 let per_peer_state = self.per_peer_state.read().unwrap();
6816                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6817                         .ok_or_else(|| {
6818                                 debug_assert!(false);
6819                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6820                         })?;
6821                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6822                 let peer_state = &mut *peer_state_lock;
6823                 match peer_state.channel_by_id.entry(msg.channel_id) {
6824                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6825                                 if (msg.failure_code & 0x8000) == 0 {
6826                                         let chan_err: ChannelError = ChannelError::Close("Got update_fail_malformed_htlc with BADONION not set".to_owned());
6827                                         try_chan_phase_entry!(self, Err(chan_err), chan_phase_entry);
6828                                 }
6829                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6830                                         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);
6831                                 } else {
6832                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6833                                                 "Got an update_fail_malformed_htlc message for an unfunded channel!".into())), chan_phase_entry);
6834                                 }
6835                                 Ok(())
6836                         },
6837                         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))
6838                 }
6839         }
6840
6841         fn internal_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) -> Result<(), MsgHandleErrInternal> {
6842                 let per_peer_state = self.per_peer_state.read().unwrap();
6843                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
6844                         .ok_or_else(|| {
6845                                 debug_assert!(false);
6846                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
6847                         })?;
6848                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6849                 let peer_state = &mut *peer_state_lock;
6850                 match peer_state.channel_by_id.entry(msg.channel_id) {
6851                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
6852                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
6853                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
6854                                         let funding_txo = chan.context.get_funding_txo();
6855                                         let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &&logger), chan_phase_entry);
6856                                         if let Some(monitor_update) = monitor_update_opt {
6857                                                 handle_new_monitor_update!(self, funding_txo.unwrap(), chan.context.channel_id(), monitor_update, peer_state_lock,
6858                                                         peer_state, per_peer_state, chan);
6859                                         }
6860                                         Ok(())
6861                                 } else {
6862                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
6863                                                 "Got a commitment_signed message for an unfunded channel!".into())), chan_phase_entry);
6864                                 }
6865                         },
6866                         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))
6867                 }
6868         }
6869
6870         #[inline]
6871         fn forward_htlcs(&self, per_source_pending_forwards: &mut [(u64, OutPoint, ChannelId, u128, Vec<(PendingHTLCInfo, u64)>)]) {
6872                 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 {
6873                         let mut push_forward_event = false;
6874                         let mut new_intercept_events = VecDeque::new();
6875                         let mut failed_intercept_forwards = Vec::new();
6876                         if !pending_forwards.is_empty() {
6877                                 for (forward_info, prev_htlc_id) in pending_forwards.drain(..) {
6878                                         let scid = match forward_info.routing {
6879                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
6880                                                 PendingHTLCRouting::Receive { .. } => 0,
6881                                                 PendingHTLCRouting::ReceiveKeysend { .. } => 0,
6882                                         };
6883                                         // Pull this now to avoid introducing a lock order with `forward_htlcs`.
6884                                         let is_our_scid = self.short_to_chan_info.read().unwrap().contains_key(&scid);
6885
6886                                         let mut forward_htlcs = self.forward_htlcs.lock().unwrap();
6887                                         let forward_htlcs_empty = forward_htlcs.is_empty();
6888                                         match forward_htlcs.entry(scid) {
6889                                                 hash_map::Entry::Occupied(mut entry) => {
6890                                                         entry.get_mut().push(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6891                                                                 prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_htlc_id, prev_user_channel_id, forward_info }));
6892                                                 },
6893                                                 hash_map::Entry::Vacant(entry) => {
6894                                                         if !is_our_scid && forward_info.incoming_amt_msat.is_some() &&
6895                                                            fake_scid::is_valid_intercept(&self.fake_scid_rand_bytes, scid, &self.chain_hash)
6896                                                         {
6897                                                                 let intercept_id = InterceptId(Sha256::hash(&forward_info.incoming_shared_secret).to_byte_array());
6898                                                                 let mut pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
6899                                                                 match pending_intercepts.entry(intercept_id) {
6900                                                                         hash_map::Entry::Vacant(entry) => {
6901                                                                                 new_intercept_events.push_back((events::Event::HTLCIntercepted {
6902                                                                                         requested_next_hop_scid: scid,
6903                                                                                         payment_hash: forward_info.payment_hash,
6904                                                                                         inbound_amount_msat: forward_info.incoming_amt_msat.unwrap(),
6905                                                                                         expected_outbound_amount_msat: forward_info.outgoing_amt_msat,
6906                                                                                         intercept_id
6907                                                                                 }, None));
6908                                                                                 entry.insert(PendingAddHTLCInfo {
6909                                                                                         prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_htlc_id, prev_user_channel_id, forward_info });
6910                                                                         },
6911                                                                         hash_map::Entry::Occupied(_) => {
6912                                                                                 let logger = WithContext::from(&self.logger, None, Some(prev_channel_id));
6913                                                                                 log_info!(logger, "Failed to forward incoming HTLC: detected duplicate intercepted payment over short channel id {}", scid);
6914                                                                                 let htlc_source = HTLCSource::PreviousHopData(HTLCPreviousHopData {
6915                                                                                         short_channel_id: prev_short_channel_id,
6916                                                                                         user_channel_id: Some(prev_user_channel_id),
6917                                                                                         outpoint: prev_funding_outpoint,
6918                                                                                         channel_id: prev_channel_id,
6919                                                                                         htlc_id: prev_htlc_id,
6920                                                                                         incoming_packet_shared_secret: forward_info.incoming_shared_secret,
6921                                                                                         phantom_shared_secret: None,
6922                                                                                         blinded_failure: forward_info.routing.blinded_failure(),
6923                                                                                 });
6924
6925                                                                                 failed_intercept_forwards.push((htlc_source, forward_info.payment_hash,
6926                                                                                                 HTLCFailReason::from_failure_code(0x4000 | 10),
6927                                                                                                 HTLCDestination::InvalidForward { requested_forward_scid: scid },
6928                                                                                 ));
6929                                                                         }
6930                                                                 }
6931                                                         } else {
6932                                                                 // We don't want to generate a PendingHTLCsForwardable event if only intercepted
6933                                                                 // payments are being processed.
6934                                                                 if forward_htlcs_empty {
6935                                                                         push_forward_event = true;
6936                                                                 }
6937                                                                 entry.insert(vec!(HTLCForwardInfo::AddHTLC(PendingAddHTLCInfo {
6938                                                                         prev_short_channel_id, prev_funding_outpoint, prev_channel_id, prev_htlc_id, prev_user_channel_id, forward_info })));
6939                                                         }
6940                                                 }
6941                                         }
6942                                 }
6943                         }
6944
6945                         for (htlc_source, payment_hash, failure_reason, destination) in failed_intercept_forwards.drain(..) {
6946                                 self.fail_htlc_backwards_internal(&htlc_source, &payment_hash, &failure_reason, destination);
6947                         }
6948
6949                         if !new_intercept_events.is_empty() {
6950                                 let mut events = self.pending_events.lock().unwrap();
6951                                 events.append(&mut new_intercept_events);
6952                         }
6953                         if push_forward_event { self.push_pending_forwards_ev() }
6954                 }
6955         }
6956
6957         fn push_pending_forwards_ev(&self) {
6958                 let mut pending_events = self.pending_events.lock().unwrap();
6959                 let is_processing_events = self.pending_events_processor.load(Ordering::Acquire);
6960                 let num_forward_events = pending_events.iter().filter(|(ev, _)|
6961                         if let events::Event::PendingHTLCsForwardable { .. } = ev { true } else { false }
6962                 ).count();
6963                 // We only want to push a PendingHTLCsForwardable event if no others are queued. Processing
6964                 // events is done in batches and they are not removed until we're done processing each
6965                 // batch. Since handling a `PendingHTLCsForwardable` event will call back into the
6966                 // `ChannelManager`, we'll still see the original forwarding event not removed. Phantom
6967                 // payments will need an additional forwarding event before being claimed to make them look
6968                 // real by taking more time.
6969                 if (is_processing_events && num_forward_events <= 1) || num_forward_events < 1 {
6970                         pending_events.push_back((Event::PendingHTLCsForwardable {
6971                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
6972                         }, None));
6973                 }
6974         }
6975
6976         /// Checks whether [`ChannelMonitorUpdate`]s generated by the receipt of a remote
6977         /// [`msgs::RevokeAndACK`] should be held for the given channel until some other action
6978         /// completes. Note that this needs to happen in the same [`PeerState`] mutex as any release of
6979         /// the [`ChannelMonitorUpdate`] in question.
6980         fn raa_monitor_updates_held(&self,
6981                 actions_blocking_raa_monitor_updates: &BTreeMap<ChannelId, Vec<RAAMonitorUpdateBlockingAction>>,
6982                 channel_funding_outpoint: OutPoint, channel_id: ChannelId, counterparty_node_id: PublicKey
6983         ) -> bool {
6984                 actions_blocking_raa_monitor_updates
6985                         .get(&channel_id).map(|v| !v.is_empty()).unwrap_or(false)
6986                 || self.pending_events.lock().unwrap().iter().any(|(_, action)| {
6987                         action == &Some(EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
6988                                 channel_funding_outpoint,
6989                                 channel_id,
6990                                 counterparty_node_id,
6991                         })
6992                 })
6993         }
6994
6995         #[cfg(any(test, feature = "_test_utils"))]
6996         pub(crate) fn test_raa_monitor_updates_held(&self,
6997                 counterparty_node_id: PublicKey, channel_id: ChannelId
6998         ) -> bool {
6999                 let per_peer_state = self.per_peer_state.read().unwrap();
7000                 if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
7001                         let mut peer_state_lck = peer_state_mtx.lock().unwrap();
7002                         let peer_state = &mut *peer_state_lck;
7003
7004                         if let Some(chan) = peer_state.channel_by_id.get(&channel_id) {
7005                                 return self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
7006                                         chan.context().get_funding_txo().unwrap(), channel_id, counterparty_node_id);
7007                         }
7008                 }
7009                 false
7010         }
7011
7012         fn internal_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) -> Result<(), MsgHandleErrInternal> {
7013                 let htlcs_to_fail = {
7014                         let per_peer_state = self.per_peer_state.read().unwrap();
7015                         let mut peer_state_lock = per_peer_state.get(counterparty_node_id)
7016                                 .ok_or_else(|| {
7017                                         debug_assert!(false);
7018                                         MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7019                                 }).map(|mtx| mtx.lock().unwrap())?;
7020                         let peer_state = &mut *peer_state_lock;
7021                         match peer_state.channel_by_id.entry(msg.channel_id) {
7022                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7023                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7024                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
7025                                                 let funding_txo_opt = chan.context.get_funding_txo();
7026                                                 let mon_update_blocked = if let Some(funding_txo) = funding_txo_opt {
7027                                                         self.raa_monitor_updates_held(
7028                                                                 &peer_state.actions_blocking_raa_monitor_updates, funding_txo, msg.channel_id,
7029                                                                 *counterparty_node_id)
7030                                                 } else { false };
7031                                                 let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
7032                                                         chan.revoke_and_ack(&msg, &self.fee_estimator, &&logger, mon_update_blocked), chan_phase_entry);
7033                                                 if let Some(monitor_update) = monitor_update_opt {
7034                                                         let funding_txo = funding_txo_opt
7035                                                                 .expect("Funding outpoint must have been set for RAA handling to succeed");
7036                                                         handle_new_monitor_update!(self, funding_txo, chan.context.channel_id(), monitor_update,
7037                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7038                                                 }
7039                                                 htlcs_to_fail
7040                                         } else {
7041                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7042                                                         "Got a revoke_and_ack message for an unfunded channel!".into())), chan_phase_entry);
7043                                         }
7044                                 },
7045                                 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))
7046                         }
7047                 };
7048                 self.fail_holding_cell_htlcs(htlcs_to_fail, msg.channel_id, counterparty_node_id);
7049                 Ok(())
7050         }
7051
7052         fn internal_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) -> Result<(), MsgHandleErrInternal> {
7053                 let per_peer_state = self.per_peer_state.read().unwrap();
7054                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7055                         .ok_or_else(|| {
7056                                 debug_assert!(false);
7057                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7058                         })?;
7059                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7060                 let peer_state = &mut *peer_state_lock;
7061                 match peer_state.channel_by_id.entry(msg.channel_id) {
7062                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7063                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7064                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7065                                         try_chan_phase_entry!(self, chan.update_fee(&self.fee_estimator, &msg, &&logger), chan_phase_entry);
7066                                 } else {
7067                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7068                                                 "Got an update_fee message for an unfunded channel!".into())), chan_phase_entry);
7069                                 }
7070                         },
7071                         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))
7072                 }
7073                 Ok(())
7074         }
7075
7076         fn internal_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) -> Result<(), MsgHandleErrInternal> {
7077                 let per_peer_state = self.per_peer_state.read().unwrap();
7078                 let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7079                         .ok_or_else(|| {
7080                                 debug_assert!(false);
7081                                 MsgHandleErrInternal::send_err_msg_no_close(format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id), msg.channel_id)
7082                         })?;
7083                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7084                 let peer_state = &mut *peer_state_lock;
7085                 match peer_state.channel_by_id.entry(msg.channel_id) {
7086                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7087                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7088                                         if !chan.context.is_usable() {
7089                                                 return Err(MsgHandleErrInternal::from_no_close(LightningError{err: "Got an announcement_signatures before we were ready for it".to_owned(), action: msgs::ErrorAction::IgnoreError}));
7090                                         }
7091
7092                                         peer_state.pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
7093                                                 msg: try_chan_phase_entry!(self, chan.announcement_signatures(
7094                                                         &self.node_signer, self.chain_hash, self.best_block.read().unwrap().height(),
7095                                                         msg, &self.default_configuration
7096                                                 ), chan_phase_entry),
7097                                                 // Note that announcement_signatures fails if the channel cannot be announced,
7098                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
7099                                                 update_msg: Some(self.get_channel_update_for_broadcast(chan).unwrap()),
7100                                         });
7101                                 } else {
7102                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7103                                                 "Got an announcement_signatures message for an unfunded channel!".into())), chan_phase_entry);
7104                                 }
7105                         },
7106                         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))
7107                 }
7108                 Ok(())
7109         }
7110
7111         /// Returns DoPersist if anything changed, otherwise either SkipPersistNoEvents or an Err.
7112         fn internal_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) -> Result<NotifyOption, MsgHandleErrInternal> {
7113                 let (chan_counterparty_node_id, chan_id) = match self.short_to_chan_info.read().unwrap().get(&msg.contents.short_channel_id) {
7114                         Some((cp_id, chan_id)) => (cp_id.clone(), chan_id.clone()),
7115                         None => {
7116                                 // It's not a local channel
7117                                 return Ok(NotifyOption::SkipPersistNoEvents)
7118                         }
7119                 };
7120                 let per_peer_state = self.per_peer_state.read().unwrap();
7121                 let peer_state_mutex_opt = per_peer_state.get(&chan_counterparty_node_id);
7122                 if peer_state_mutex_opt.is_none() {
7123                         return Ok(NotifyOption::SkipPersistNoEvents)
7124                 }
7125                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
7126                 let peer_state = &mut *peer_state_lock;
7127                 match peer_state.channel_by_id.entry(chan_id) {
7128                         hash_map::Entry::Occupied(mut chan_phase_entry) => {
7129                                 if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7130                                         if chan.context.get_counterparty_node_id() != *counterparty_node_id {
7131                                                 if chan.context.should_announce() {
7132                                                         // If the announcement is about a channel of ours which is public, some
7133                                                         // other peer may simply be forwarding all its gossip to us. Don't provide
7134                                                         // a scary-looking error message and return Ok instead.
7135                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7136                                                 }
7137                                                 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));
7138                                         }
7139                                         let were_node_one = self.get_our_node_id().serialize()[..] < chan.context.get_counterparty_node_id().serialize()[..];
7140                                         let msg_from_node_one = msg.contents.flags & 1 == 0;
7141                                         if were_node_one == msg_from_node_one {
7142                                                 return Ok(NotifyOption::SkipPersistNoEvents);
7143                                         } else {
7144                                                 let logger = WithChannelContext::from(&self.logger, &chan.context);
7145                                                 log_debug!(logger, "Received channel_update {:?} for channel {}.", msg, chan_id);
7146                                                 let did_change = try_chan_phase_entry!(self, chan.channel_update(&msg), chan_phase_entry);
7147                                                 // If nothing changed after applying their update, we don't need to bother
7148                                                 // persisting.
7149                                                 if !did_change {
7150                                                         return Ok(NotifyOption::SkipPersistNoEvents);
7151                                                 }
7152                                         }
7153                                 } else {
7154                                         return try_chan_phase_entry!(self, Err(ChannelError::Close(
7155                                                 "Got a channel_update for an unfunded channel!".into())), chan_phase_entry);
7156                                 }
7157                         },
7158                         hash_map::Entry::Vacant(_) => return Ok(NotifyOption::SkipPersistNoEvents)
7159                 }
7160                 Ok(NotifyOption::DoPersist)
7161         }
7162
7163         fn internal_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) -> Result<NotifyOption, MsgHandleErrInternal> {
7164                 let htlc_forwards;
7165                 let need_lnd_workaround = {
7166                         let per_peer_state = self.per_peer_state.read().unwrap();
7167
7168                         let peer_state_mutex = per_peer_state.get(counterparty_node_id)
7169                                 .ok_or_else(|| {
7170                                         debug_assert!(false);
7171                                         MsgHandleErrInternal::send_err_msg_no_close(
7172                                                 format!("Can't find a peer matching the passed counterparty node_id {}", counterparty_node_id),
7173                                                 msg.channel_id
7174                                         )
7175                                 })?;
7176                         let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), Some(msg.channel_id));
7177                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7178                         let peer_state = &mut *peer_state_lock;
7179                         match peer_state.channel_by_id.entry(msg.channel_id) {
7180                                 hash_map::Entry::Occupied(mut chan_phase_entry) => {
7181                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
7182                                                 // Currently, we expect all holding cell update_adds to be dropped on peer
7183                                                 // disconnect, so Channel's reestablish will never hand us any holding cell
7184                                                 // freed HTLCs to fail backwards. If in the future we no longer drop pending
7185                                                 // add-HTLCs on disconnect, we may be handed HTLCs to fail backwards here.
7186                                                 let responses = try_chan_phase_entry!(self, chan.channel_reestablish(
7187                                                         msg, &&logger, &self.node_signer, self.chain_hash,
7188                                                         &self.default_configuration, &*self.best_block.read().unwrap()), chan_phase_entry);
7189                                                 let mut channel_update = None;
7190                                                 if let Some(msg) = responses.shutdown_msg {
7191                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
7192                                                                 node_id: counterparty_node_id.clone(),
7193                                                                 msg,
7194                                                         });
7195                                                 } else if chan.context.is_usable() {
7196                                                         // If the channel is in a usable state (ie the channel is not being shut
7197                                                         // down), send a unicast channel_update to our counterparty to make sure
7198                                                         // they have the latest channel parameters.
7199                                                         if let Ok(msg) = self.get_channel_update_for_unicast(chan) {
7200                                                                 channel_update = Some(events::MessageSendEvent::SendChannelUpdate {
7201                                                                         node_id: chan.context.get_counterparty_node_id(),
7202                                                                         msg,
7203                                                                 });
7204                                                         }
7205                                                 }
7206                                                 let need_lnd_workaround = chan.context.workaround_lnd_bug_4006.take();
7207                                                 htlc_forwards = self.handle_channel_resumption(
7208                                                         &mut peer_state.pending_msg_events, chan, responses.raa, responses.commitment_update, responses.order,
7209                                                         Vec::new(), None, responses.channel_ready, responses.announcement_sigs);
7210                                                 if let Some(upd) = channel_update {
7211                                                         peer_state.pending_msg_events.push(upd);
7212                                                 }
7213                                                 need_lnd_workaround
7214                                         } else {
7215                                                 return try_chan_phase_entry!(self, Err(ChannelError::Close(
7216                                                         "Got a channel_reestablish message for an unfunded channel!".into())), chan_phase_entry);
7217                                         }
7218                                 },
7219                                 hash_map::Entry::Vacant(_) => {
7220                                         log_debug!(logger, "Sending bogus ChannelReestablish for unknown channel {} to force channel closure",
7221                                                 msg.channel_id);
7222                                         // Unfortunately, lnd doesn't force close on errors
7223                                         // (https://github.com/lightningnetwork/lnd/blob/abb1e3463f3a83bbb843d5c399869dbe930ad94f/htlcswitch/link.go#L2119).
7224                                         // One of the few ways to get an lnd counterparty to force close is by
7225                                         // replicating what they do when restoring static channel backups (SCBs). They
7226                                         // send an invalid `ChannelReestablish` with `0` commitment numbers and an
7227                                         // invalid `your_last_per_commitment_secret`.
7228                                         //
7229                                         // Since we received a `ChannelReestablish` for a channel that doesn't exist, we
7230                                         // can assume it's likely the channel closed from our point of view, but it
7231                                         // remains open on the counterparty's side. By sending this bogus
7232                                         // `ChannelReestablish` message now as a response to theirs, we trigger them to
7233                                         // force close broadcasting their latest state. If the closing transaction from
7234                                         // our point of view remains unconfirmed, it'll enter a race with the
7235                                         // counterparty's to-be-broadcast latest commitment transaction.
7236                                         peer_state.pending_msg_events.push(MessageSendEvent::SendChannelReestablish {
7237                                                 node_id: *counterparty_node_id,
7238                                                 msg: msgs::ChannelReestablish {
7239                                                         channel_id: msg.channel_id,
7240                                                         next_local_commitment_number: 0,
7241                                                         next_remote_commitment_number: 0,
7242                                                         your_last_per_commitment_secret: [1u8; 32],
7243                                                         my_current_per_commitment_point: PublicKey::from_slice(&[2u8; 33]).unwrap(),
7244                                                         next_funding_txid: None,
7245                                                 },
7246                                         });
7247                                         return Err(MsgHandleErrInternal::send_err_msg_no_close(
7248                                                 format!("Got a message for a channel from the wrong node! No such channel for the passed counterparty_node_id {}",
7249                                                         counterparty_node_id), msg.channel_id)
7250                                         )
7251                                 }
7252                         }
7253                 };
7254
7255                 let mut persist = NotifyOption::SkipPersistHandleEvents;
7256                 if let Some(forwards) = htlc_forwards {
7257                         self.forward_htlcs(&mut [forwards][..]);
7258                         persist = NotifyOption::DoPersist;
7259                 }
7260
7261                 if let Some(channel_ready_msg) = need_lnd_workaround {
7262                         self.internal_channel_ready(counterparty_node_id, &channel_ready_msg)?;
7263                 }
7264                 Ok(persist)
7265         }
7266
7267         /// Process pending events from the [`chain::Watch`], returning whether any events were processed.
7268         fn process_pending_monitor_events(&self) -> bool {
7269                 debug_assert!(self.total_consistency_lock.try_write().is_err()); // Caller holds read lock
7270
7271                 let mut failed_channels = Vec::new();
7272                 let mut pending_monitor_events = self.chain_monitor.release_pending_monitor_events();
7273                 let has_pending_monitor_events = !pending_monitor_events.is_empty();
7274                 for (funding_outpoint, channel_id, mut monitor_events, counterparty_node_id) in pending_monitor_events.drain(..) {
7275                         for monitor_event in monitor_events.drain(..) {
7276                                 match monitor_event {
7277                                         MonitorEvent::HTLCEvent(htlc_update) => {
7278                                                 let logger = WithContext::from(&self.logger, counterparty_node_id, Some(channel_id));
7279                                                 if let Some(preimage) = htlc_update.payment_preimage {
7280                                                         log_trace!(logger, "Claiming HTLC with preimage {} from our monitor", preimage);
7281                                                         self.claim_funds_internal(htlc_update.source, preimage, htlc_update.htlc_value_satoshis.map(|v| v * 1000), true, false, counterparty_node_id, funding_outpoint, channel_id);
7282                                                 } else {
7283                                                         log_trace!(logger, "Failing HTLC with hash {} from our monitor", &htlc_update.payment_hash);
7284                                                         let receiver = HTLCDestination::NextHopChannel { node_id: counterparty_node_id, channel_id };
7285                                                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
7286                                                         self.fail_htlc_backwards_internal(&htlc_update.source, &htlc_update.payment_hash, &reason, receiver);
7287                                                 }
7288                                         },
7289                                         MonitorEvent::HolderForceClosed(_funding_outpoint) => {
7290                                                 let counterparty_node_id_opt = match counterparty_node_id {
7291                                                         Some(cp_id) => Some(cp_id),
7292                                                         None => {
7293                                                                 // TODO: Once we can rely on the counterparty_node_id from the
7294                                                                 // monitor event, this and the outpoint_to_peer map should be removed.
7295                                                                 let outpoint_to_peer = self.outpoint_to_peer.lock().unwrap();
7296                                                                 outpoint_to_peer.get(&funding_outpoint).cloned()
7297                                                         }
7298                                                 };
7299                                                 if let Some(counterparty_node_id) = counterparty_node_id_opt {
7300                                                         let per_peer_state = self.per_peer_state.read().unwrap();
7301                                                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7302                                                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7303                                                                 let peer_state = &mut *peer_state_lock;
7304                                                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7305                                                                 if let hash_map::Entry::Occupied(chan_phase_entry) = peer_state.channel_by_id.entry(channel_id) {
7306                                                                         if let ChannelPhase::Funded(mut chan) = remove_channel_phase!(self, chan_phase_entry) {
7307                                                                                 failed_channels.push(chan.context.force_shutdown(false, ClosureReason::HolderForceClosed));
7308                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7309                                                                                         let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
7310                                                                                         pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
7311                                                                                                 msg: update
7312                                                                                         });
7313                                                                                 }
7314                                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
7315                                                                                         node_id: chan.context.get_counterparty_node_id(),
7316                                                                                         action: msgs::ErrorAction::DisconnectPeer {
7317                                                                                                 msg: Some(msgs::ErrorMessage { channel_id: chan.context.channel_id(), data: "Channel force-closed".to_owned() })
7318                                                                                         },
7319                                                                                 });
7320                                                                         }
7321                                                                 }
7322                                                         }
7323                                                 }
7324                                         },
7325                                         MonitorEvent::Completed { funding_txo, channel_id, monitor_update_id } => {
7326                                                 self.channel_monitor_updated(&funding_txo, &channel_id, monitor_update_id, counterparty_node_id.as_ref());
7327                                         },
7328                                 }
7329                         }
7330                 }
7331
7332                 for failure in failed_channels.drain(..) {
7333                         self.finish_close_channel(failure);
7334                 }
7335
7336                 has_pending_monitor_events
7337         }
7338
7339         /// In chanmon_consistency_target, we'd like to be able to restore monitor updating without
7340         /// handling all pending events (i.e. not PendingHTLCsForwardable). Thus, we expose monitor
7341         /// update events as a separate process method here.
7342         #[cfg(fuzzing)]
7343         pub fn process_monitor_events(&self) {
7344                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7345                 self.process_pending_monitor_events();
7346         }
7347
7348         /// Check the holding cell in each channel and free any pending HTLCs in them if possible.
7349         /// Returns whether there were any updates such as if pending HTLCs were freed or a monitor
7350         /// update was applied.
7351         fn check_free_holding_cells(&self) -> bool {
7352                 let mut has_monitor_update = false;
7353                 let mut failed_htlcs = Vec::new();
7354
7355                 // Walk our list of channels and find any that need to update. Note that when we do find an
7356                 // update, if it includes actions that must be taken afterwards, we have to drop the
7357                 // per-peer state lock as well as the top level per_peer_state lock. Thus, we loop until we
7358                 // manage to go through all our peers without finding a single channel to update.
7359                 'peer_loop: loop {
7360                         let per_peer_state = self.per_peer_state.read().unwrap();
7361                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7362                                 'chan_loop: loop {
7363                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7364                                         let peer_state: &mut PeerState<_> = &mut *peer_state_lock;
7365                                         for (channel_id, chan) in peer_state.channel_by_id.iter_mut().filter_map(
7366                                                 |(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
7367                                         ) {
7368                                                 let counterparty_node_id = chan.context.get_counterparty_node_id();
7369                                                 let funding_txo = chan.context.get_funding_txo();
7370                                                 let (monitor_opt, holding_cell_failed_htlcs) =
7371                                                         chan.maybe_free_holding_cell_htlcs(&self.fee_estimator, &&WithChannelContext::from(&self.logger, &chan.context));
7372                                                 if !holding_cell_failed_htlcs.is_empty() {
7373                                                         failed_htlcs.push((holding_cell_failed_htlcs, *channel_id, counterparty_node_id));
7374                                                 }
7375                                                 if let Some(monitor_update) = monitor_opt {
7376                                                         has_monitor_update = true;
7377
7378                                                         handle_new_monitor_update!(self, funding_txo.unwrap(), chan.context.channel_id(), monitor_update,
7379                                                                 peer_state_lock, peer_state, per_peer_state, chan);
7380                                                         continue 'peer_loop;
7381                                                 }
7382                                         }
7383                                         break 'chan_loop;
7384                                 }
7385                         }
7386                         break 'peer_loop;
7387                 }
7388
7389                 let has_update = has_monitor_update || !failed_htlcs.is_empty();
7390                 for (failures, channel_id, counterparty_node_id) in failed_htlcs.drain(..) {
7391                         self.fail_holding_cell_htlcs(failures, channel_id, &counterparty_node_id);
7392                 }
7393
7394                 has_update
7395         }
7396
7397         /// When a call to a [`ChannelSigner`] method returns an error, this indicates that the signer
7398         /// is (temporarily) unavailable, and the operation should be retried later.
7399         ///
7400         /// This method allows for that retry - either checking for any signer-pending messages to be
7401         /// attempted in every channel, or in the specifically provided channel.
7402         ///
7403         /// [`ChannelSigner`]: crate::sign::ChannelSigner
7404         #[cfg(async_signing)]
7405         pub fn signer_unblocked(&self, channel_opt: Option<(PublicKey, ChannelId)>) {
7406                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
7407
7408                 let unblock_chan = |phase: &mut ChannelPhase<SP>, pending_msg_events: &mut Vec<MessageSendEvent>| {
7409                         let node_id = phase.context().get_counterparty_node_id();
7410                         match phase {
7411                                 ChannelPhase::Funded(chan) => {
7412                                         let msgs = chan.signer_maybe_unblocked(&self.logger);
7413                                         if let Some(updates) = msgs.commitment_update {
7414                                                 pending_msg_events.push(events::MessageSendEvent::UpdateHTLCs {
7415                                                         node_id,
7416                                                         updates,
7417                                                 });
7418                                         }
7419                                         if let Some(msg) = msgs.funding_signed {
7420                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingSigned {
7421                                                         node_id,
7422                                                         msg,
7423                                                 });
7424                                         }
7425                                         if let Some(msg) = msgs.channel_ready {
7426                                                 send_channel_ready!(self, pending_msg_events, chan, msg);
7427                                         }
7428                                 }
7429                                 ChannelPhase::UnfundedOutboundV1(chan) => {
7430                                         if let Some(msg) = chan.signer_maybe_unblocked(&self.logger) {
7431                                                 pending_msg_events.push(events::MessageSendEvent::SendFundingCreated {
7432                                                         node_id,
7433                                                         msg,
7434                                                 });
7435                                         }
7436                                 }
7437                                 ChannelPhase::UnfundedInboundV1(_) => {},
7438                         }
7439                 };
7440
7441                 let per_peer_state = self.per_peer_state.read().unwrap();
7442                 if let Some((counterparty_node_id, channel_id)) = channel_opt {
7443                         if let Some(peer_state_mutex) = per_peer_state.get(&counterparty_node_id) {
7444                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7445                                 let peer_state = &mut *peer_state_lock;
7446                                 if let Some(chan) = peer_state.channel_by_id.get_mut(&channel_id) {
7447                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7448                                 }
7449                         }
7450                 } else {
7451                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7452                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7453                                 let peer_state = &mut *peer_state_lock;
7454                                 for (_, chan) in peer_state.channel_by_id.iter_mut() {
7455                                         unblock_chan(chan, &mut peer_state.pending_msg_events);
7456                                 }
7457                         }
7458                 }
7459         }
7460
7461         /// Check whether any channels have finished removing all pending updates after a shutdown
7462         /// exchange and can now send a closing_signed.
7463         /// Returns whether any closing_signed messages were generated.
7464         fn maybe_generate_initial_closing_signed(&self) -> bool {
7465                 let mut handle_errors: Vec<(PublicKey, Result<(), _>)> = Vec::new();
7466                 let mut has_update = false;
7467                 let mut shutdown_results = Vec::new();
7468                 {
7469                         let per_peer_state = self.per_peer_state.read().unwrap();
7470
7471                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
7472                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
7473                                 let peer_state = &mut *peer_state_lock;
7474                                 let pending_msg_events = &mut peer_state.pending_msg_events;
7475                                 peer_state.channel_by_id.retain(|channel_id, phase| {
7476                                         match phase {
7477                                                 ChannelPhase::Funded(chan) => {
7478                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
7479                                                         match chan.maybe_propose_closing_signed(&self.fee_estimator, &&logger) {
7480                                                                 Ok((msg_opt, tx_opt, shutdown_result_opt)) => {
7481                                                                         if let Some(msg) = msg_opt {
7482                                                                                 has_update = true;
7483                                                                                 pending_msg_events.push(events::MessageSendEvent::SendClosingSigned {
7484                                                                                         node_id: chan.context.get_counterparty_node_id(), msg,
7485                                                                                 });
7486                                                                         }
7487                                                                         debug_assert_eq!(shutdown_result_opt.is_some(), chan.is_shutdown());
7488                                                                         if let Some(shutdown_result) = shutdown_result_opt {
7489                                                                                 shutdown_results.push(shutdown_result);
7490                                                                         }
7491                                                                         if let Some(tx) = tx_opt {
7492                                                                                 // We're done with this channel. We got a closing_signed and sent back
7493                                                                                 // a closing_signed with a closing transaction to broadcast.
7494                                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&chan) {
7495                                                                                         let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
7496                                                                                         pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
7497                                                                                                 msg: update
7498                                                                                         });
7499                                                                                 }
7500
7501                                                                                 log_info!(logger, "Broadcasting {}", log_tx!(tx));
7502                                                                                 self.tx_broadcaster.broadcast_transactions(&[&tx]);
7503                                                                                 update_maps_on_chan_removal!(self, &chan.context);
7504                                                                                 false
7505                                                                         } else { true }
7506                                                                 },
7507                                                                 Err(e) => {
7508                                                                         has_update = true;
7509                                                                         let (close_channel, res) = convert_chan_phase_err!(self, e, chan, channel_id, FUNDED_CHANNEL);
7510                                                                         handle_errors.push((chan.context.get_counterparty_node_id(), Err(res)));
7511                                                                         !close_channel
7512                                                                 }
7513                                                         }
7514                                                 },
7515                                                 _ => true, // Retain unfunded channels if present.
7516                                         }
7517                                 });
7518                         }
7519                 }
7520
7521                 for (counterparty_node_id, err) in handle_errors.drain(..) {
7522                         let _ = handle_error!(self, err, counterparty_node_id);
7523                 }
7524
7525                 for shutdown_result in shutdown_results.drain(..) {
7526                         self.finish_close_channel(shutdown_result);
7527                 }
7528
7529                 has_update
7530         }
7531
7532         /// Handle a list of channel failures during a block_connected or block_disconnected call,
7533         /// pushing the channel monitor update (if any) to the background events queue and removing the
7534         /// Channel object.
7535         fn handle_init_event_channel_failures(&self, mut failed_channels: Vec<ShutdownResult>) {
7536                 for mut failure in failed_channels.drain(..) {
7537                         // Either a commitment transactions has been confirmed on-chain or
7538                         // Channel::block_disconnected detected that the funding transaction has been
7539                         // reorganized out of the main chain.
7540                         // We cannot broadcast our latest local state via monitor update (as
7541                         // Channel::force_shutdown tries to make us do) as we may still be in initialization,
7542                         // so we track the update internally and handle it when the user next calls
7543                         // timer_tick_occurred, guaranteeing we're running normally.
7544                         if let Some((counterparty_node_id, funding_txo, channel_id, update)) = failure.monitor_update.take() {
7545                                 assert_eq!(update.updates.len(), 1);
7546                                 if let ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } = update.updates[0] {
7547                                         assert!(should_broadcast);
7548                                 } else { unreachable!(); }
7549                                 self.pending_background_events.lock().unwrap().push(
7550                                         BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
7551                                                 counterparty_node_id, funding_txo, update, channel_id,
7552                                         });
7553                         }
7554                         self.finish_close_channel(failure);
7555                 }
7556         }
7557
7558         /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
7559         /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
7560         /// not have an expiration unless otherwise set on the builder.
7561         ///
7562         /// # Privacy
7563         ///
7564         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the offer.
7565         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7566         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7567         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7568         /// order to send the [`InvoiceRequest`].
7569         ///
7570         /// Also, uses a derived signing pubkey in the offer for recipient privacy.
7571         ///
7572         /// # Limitations
7573         ///
7574         /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
7575         /// reply path.
7576         ///
7577         /// # Errors
7578         ///
7579         /// Errors if the parameterized [`Router`] is unable to create a blinded path for the offer.
7580         ///
7581         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7582         ///
7583         /// [`Offer`]: crate::offers::offer::Offer
7584         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7585         pub fn create_offer_builder(
7586                 &self, description: String
7587         ) -> Result<OfferBuilder<DerivedMetadata, secp256k1::All>, Bolt12SemanticError> {
7588                 let node_id = self.get_our_node_id();
7589                 let expanded_key = &self.inbound_payment_key;
7590                 let entropy = &*self.entropy_source;
7591                 let secp_ctx = &self.secp_ctx;
7592
7593                 let path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7594                 let builder = OfferBuilder::deriving_signing_pubkey(
7595                         description, node_id, expanded_key, entropy, secp_ctx
7596                 )
7597                         .chain_hash(self.chain_hash)
7598                         .path(path);
7599
7600                 Ok(builder)
7601         }
7602
7603         /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
7604         /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
7605         ///
7606         /// # Payment
7607         ///
7608         /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
7609         /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
7610         ///
7611         /// The builder will have the provided expiration set. Any changes to the expiration on the
7612         /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
7613         /// block time minus two hours is used for the current time when determining if the refund has
7614         /// expired.
7615         ///
7616         /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
7617         /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
7618         /// with an [`Event::InvoiceRequestFailed`].
7619         ///
7620         /// If `max_total_routing_fee_msat` is not specified, The default from
7621         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7622         ///
7623         /// # Privacy
7624         ///
7625         /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the refund.
7626         /// However, if one is not found, uses a one-hop [`BlindedPath`] with
7627         /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
7628         /// the node must be announced, otherwise, there is no way to find a path to the introduction in
7629         /// order to send the [`Bolt12Invoice`].
7630         ///
7631         /// Also, uses a derived payer id in the refund for payer privacy.
7632         ///
7633         /// # Limitations
7634         ///
7635         /// Requires a direct connection to an introduction node in the responding
7636         /// [`Bolt12Invoice::payment_paths`].
7637         ///
7638         /// # Errors
7639         ///
7640         /// Errors if:
7641         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7642         /// - `amount_msats` is invalid, or
7643         /// - the parameterized [`Router`] is unable to create a blinded path for the refund.
7644         ///
7645         /// This is not exported to bindings users as builder patterns don't map outside of move semantics.
7646         ///
7647         /// [`Refund`]: crate::offers::refund::Refund
7648         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7649         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7650         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7651         pub fn create_refund_builder(
7652                 &self, description: String, amount_msats: u64, absolute_expiry: Duration,
7653                 payment_id: PaymentId, retry_strategy: Retry, max_total_routing_fee_msat: Option<u64>
7654         ) -> Result<RefundBuilder<secp256k1::All>, Bolt12SemanticError> {
7655                 let node_id = self.get_our_node_id();
7656                 let expanded_key = &self.inbound_payment_key;
7657                 let entropy = &*self.entropy_source;
7658                 let secp_ctx = &self.secp_ctx;
7659
7660                 let path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7661                 let builder = RefundBuilder::deriving_payer_id(
7662                         description, node_id, expanded_key, entropy, secp_ctx, amount_msats, payment_id
7663                 )?
7664                         .chain_hash(self.chain_hash)
7665                         .absolute_expiry(absolute_expiry)
7666                         .path(path);
7667
7668                 let expiration = StaleExpiration::AbsoluteTimeout(absolute_expiry);
7669                 self.pending_outbound_payments
7670                         .add_new_awaiting_invoice(
7671                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat,
7672                         )
7673                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7674
7675                 Ok(builder)
7676         }
7677
7678         /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
7679         /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
7680         /// [`Bolt12Invoice`] once it is received.
7681         ///
7682         /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
7683         /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
7684         /// The optional parameters are used in the builder, if `Some`:
7685         /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
7686         ///   [`Offer::expects_quantity`] is `true`.
7687         /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
7688         /// - `payer_note` for [`InvoiceRequest::payer_note`].
7689         ///
7690         /// If `max_total_routing_fee_msat` is not specified, The default from
7691         /// [`RouteParameters::from_payment_params_and_value`] is applied.
7692         ///
7693         /// # Payment
7694         ///
7695         /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
7696         /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
7697         /// been sent.
7698         ///
7699         /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
7700         /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
7701         /// payment will fail with an [`Event::InvoiceRequestFailed`].
7702         ///
7703         /// # Privacy
7704         ///
7705         /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
7706         /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
7707         /// node must be announced. Otherwise, there is no way to find a path to the introduction node
7708         /// in order to send the [`Bolt12Invoice`].
7709         ///
7710         /// # Limitations
7711         ///
7712         /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
7713         /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
7714         /// [`Bolt12Invoice::payment_paths`].
7715         ///
7716         /// # Errors
7717         ///
7718         /// Errors if:
7719         /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
7720         /// - the provided parameters are invalid for the offer,
7721         /// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
7722         ///   request.
7723         ///
7724         /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
7725         /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
7726         /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
7727         /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
7728         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7729         /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
7730         /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
7731         pub fn pay_for_offer(
7732                 &self, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
7733                 payer_note: Option<String>, payment_id: PaymentId, retry_strategy: Retry,
7734                 max_total_routing_fee_msat: Option<u64>
7735         ) -> Result<(), Bolt12SemanticError> {
7736                 let expanded_key = &self.inbound_payment_key;
7737                 let entropy = &*self.entropy_source;
7738                 let secp_ctx = &self.secp_ctx;
7739
7740                 let builder = offer
7741                         .request_invoice_deriving_payer_id(expanded_key, entropy, secp_ctx, payment_id)?
7742                         .chain_hash(self.chain_hash)?;
7743                 let builder = match quantity {
7744                         None => builder,
7745                         Some(quantity) => builder.quantity(quantity)?,
7746                 };
7747                 let builder = match amount_msats {
7748                         None => builder,
7749                         Some(amount_msats) => builder.amount_msats(amount_msats)?,
7750                 };
7751                 let builder = match payer_note {
7752                         None => builder,
7753                         Some(payer_note) => builder.payer_note(payer_note),
7754                 };
7755                 let invoice_request = builder.build_and_sign()?;
7756                 let reply_path = self.create_blinded_path().map_err(|_| Bolt12SemanticError::MissingPaths)?;
7757
7758                 let expiration = StaleExpiration::TimerTicks(1);
7759                 self.pending_outbound_payments
7760                         .add_new_awaiting_invoice(
7761                                 payment_id, expiration, retry_strategy, max_total_routing_fee_msat
7762                         )
7763                         .map_err(|_| Bolt12SemanticError::DuplicatePaymentId)?;
7764
7765                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7766                 if offer.paths().is_empty() {
7767                         let message = new_pending_onion_message(
7768                                 OffersMessage::InvoiceRequest(invoice_request),
7769                                 Destination::Node(offer.signing_pubkey()),
7770                                 Some(reply_path),
7771                         );
7772                         pending_offers_messages.push(message);
7773                 } else {
7774                         // Send as many invoice requests as there are paths in the offer (with an upper bound).
7775                         // Using only one path could result in a failure if the path no longer exists. But only
7776                         // one invoice for a given payment id will be paid, even if more than one is received.
7777                         const REQUEST_LIMIT: usize = 10;
7778                         for path in offer.paths().into_iter().take(REQUEST_LIMIT) {
7779                                 let message = new_pending_onion_message(
7780                                         OffersMessage::InvoiceRequest(invoice_request.clone()),
7781                                         Destination::BlindedPath(path.clone()),
7782                                         Some(reply_path.clone()),
7783                                 );
7784                                 pending_offers_messages.push(message);
7785                         }
7786                 }
7787
7788                 Ok(())
7789         }
7790
7791         /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
7792         /// message.
7793         ///
7794         /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
7795         /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
7796         /// [`PaymentPreimage`].
7797         ///
7798         /// # Limitations
7799         ///
7800         /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
7801         /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
7802         /// node meeting the aforementioned criteria, but there's no guarantee that they will be
7803         /// received and no retries will be made.
7804         ///
7805         /// # Errors
7806         ///
7807         /// Errors if the parameterized [`Router`] is unable to create a blinded payment path or reply
7808         /// path for the invoice.
7809         ///
7810         /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
7811         pub fn request_refund_payment(&self, refund: &Refund) -> Result<(), Bolt12SemanticError> {
7812                 let expanded_key = &self.inbound_payment_key;
7813                 let entropy = &*self.entropy_source;
7814                 let secp_ctx = &self.secp_ctx;
7815
7816                 let amount_msats = refund.amount_msats();
7817                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7818
7819                 match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
7820                         Ok((payment_hash, payment_secret)) => {
7821                                 let payment_paths = self.create_blinded_payment_paths(amount_msats, payment_secret)
7822                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7823
7824                                 #[cfg(feature = "std")]
7825                                 let builder = refund.respond_using_derived_keys(
7826                                         payment_paths, payment_hash, expanded_key, entropy
7827                                 )?;
7828                                 #[cfg(not(feature = "std"))]
7829                                 let created_at = Duration::from_secs(
7830                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7831                                 );
7832                                 #[cfg(not(feature = "std"))]
7833                                 let builder = refund.respond_using_derived_keys_no_std(
7834                                         payment_paths, payment_hash, created_at, expanded_key, entropy
7835                                 )?;
7836                                 let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
7837                                 let reply_path = self.create_blinded_path()
7838                                         .map_err(|_| Bolt12SemanticError::MissingPaths)?;
7839
7840                                 let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
7841                                 if refund.paths().is_empty() {
7842                                         let message = new_pending_onion_message(
7843                                                 OffersMessage::Invoice(invoice),
7844                                                 Destination::Node(refund.payer_id()),
7845                                                 Some(reply_path),
7846                                         );
7847                                         pending_offers_messages.push(message);
7848                                 } else {
7849                                         for path in refund.paths() {
7850                                                 let message = new_pending_onion_message(
7851                                                         OffersMessage::Invoice(invoice.clone()),
7852                                                         Destination::BlindedPath(path.clone()),
7853                                                         Some(reply_path.clone()),
7854                                                 );
7855                                                 pending_offers_messages.push(message);
7856                                         }
7857                                 }
7858
7859                                 Ok(())
7860                         },
7861                         Err(()) => Err(Bolt12SemanticError::InvalidAmount),
7862                 }
7863         }
7864
7865         /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
7866         /// to pay us.
7867         ///
7868         /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
7869         /// [`PaymentHash`] and [`PaymentPreimage`] for you.
7870         ///
7871         /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which
7872         /// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with
7873         /// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be
7874         /// passed directly to [`claim_funds`].
7875         ///
7876         /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
7877         ///
7878         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7879         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7880         ///
7881         /// # Note
7882         ///
7883         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7884         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7885         ///
7886         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7887         ///
7888         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7889         /// on versions of LDK prior to 0.0.114.
7890         ///
7891         /// [`claim_funds`]: Self::claim_funds
7892         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7893         /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
7894         /// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment
7895         /// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage
7896         /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
7897         pub fn create_inbound_payment(&self, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
7898                 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()> {
7899                 inbound_payment::create(&self.inbound_payment_key, min_value_msat, invoice_expiry_delta_secs,
7900                         &self.entropy_source, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7901                         min_final_cltv_expiry_delta)
7902         }
7903
7904         /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
7905         /// stored external to LDK.
7906         ///
7907         /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
7908         /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
7909         /// the `min_value_msat` provided here, if one is provided.
7910         ///
7911         /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
7912         /// note that LDK will not stop you from registering duplicate payment hashes for inbound
7913         /// payments.
7914         ///
7915         /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
7916         /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
7917         /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
7918         /// sender "proof-of-payment" unless they have paid the required amount.
7919         ///
7920         /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
7921         /// in excess of the current time. This should roughly match the expiry time set in the invoice.
7922         /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
7923         /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
7924         /// invoices when no timeout is set.
7925         ///
7926         /// Note that we use block header time to time-out pending inbound payments (with some margin
7927         /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
7928         /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
7929         /// If you need exact expiry semantics, you should enforce them upon receipt of
7930         /// [`PaymentClaimable`].
7931         ///
7932         /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
7933         /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
7934         ///
7935         /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
7936         /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
7937         ///
7938         /// # Note
7939         ///
7940         /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
7941         /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
7942         ///
7943         /// Errors if `min_value_msat` is greater than total bitcoin supply.
7944         ///
7945         /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
7946         /// on versions of LDK prior to 0.0.114.
7947         ///
7948         /// [`create_inbound_payment`]: Self::create_inbound_payment
7949         /// [`PaymentClaimable`]: events::Event::PaymentClaimable
7950         pub fn create_inbound_payment_for_hash(&self, payment_hash: PaymentHash, min_value_msat: Option<u64>,
7951                 invoice_expiry_delta_secs: u32, min_final_cltv_expiry: Option<u16>) -> Result<PaymentSecret, ()> {
7952                 inbound_payment::create_from_hash(&self.inbound_payment_key, min_value_msat, payment_hash,
7953                         invoice_expiry_delta_secs, self.highest_seen_timestamp.load(Ordering::Acquire) as u64,
7954                         min_final_cltv_expiry)
7955         }
7956
7957         /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
7958         /// previously returned from [`create_inbound_payment`].
7959         ///
7960         /// [`create_inbound_payment`]: Self::create_inbound_payment
7961         pub fn get_payment_preimage(&self, payment_hash: PaymentHash, payment_secret: PaymentSecret) -> Result<PaymentPreimage, APIError> {
7962                 inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
7963         }
7964
7965         /// Creates a blinded path by delegating to [`MessageRouter::create_blinded_paths`].
7966         ///
7967         /// Errors if the `MessageRouter` errors or returns an empty `Vec`.
7968         fn create_blinded_path(&self) -> Result<BlindedPath, ()> {
7969                 let recipient = self.get_our_node_id();
7970                 let entropy_source = self.entropy_source.deref();
7971                 let secp_ctx = &self.secp_ctx;
7972
7973                 let peers = self.per_peer_state.read().unwrap()
7974                         .iter()
7975                         .filter(|(_, peer)| peer.lock().unwrap().latest_features.supports_onion_messages())
7976                         .map(|(node_id, _)| *node_id)
7977                         .collect::<Vec<_>>();
7978
7979                 self.router
7980                         .create_blinded_paths(recipient, peers, entropy_source, secp_ctx)
7981                         .and_then(|paths| paths.into_iter().next().ok_or(()))
7982         }
7983
7984         /// Creates multi-hop blinded payment paths for the given `amount_msats` by delegating to
7985         /// [`Router::create_blinded_payment_paths`].
7986         fn create_blinded_payment_paths(
7987                 &self, amount_msats: u64, payment_secret: PaymentSecret
7988         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
7989                 let entropy_source = self.entropy_source.deref();
7990                 let secp_ctx = &self.secp_ctx;
7991
7992                 let first_hops = self.list_usable_channels();
7993                 let payee_node_id = self.get_our_node_id();
7994                 let max_cltv_expiry = self.best_block.read().unwrap().height() + CLTV_FAR_FAR_AWAY
7995                         + LATENCY_GRACE_PERIOD_BLOCKS;
7996                 let payee_tlvs = ReceiveTlvs {
7997                         payment_secret,
7998                         payment_constraints: PaymentConstraints {
7999                                 max_cltv_expiry,
8000                                 htlc_minimum_msat: 1,
8001                         },
8002                 };
8003                 self.router.create_blinded_payment_paths(
8004                         payee_node_id, first_hops, payee_tlvs, amount_msats, entropy_source, secp_ctx
8005                 )
8006         }
8007
8008         /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
8009         /// are used when constructing the phantom invoice's route hints.
8010         ///
8011         /// [phantom node payments]: crate::sign::PhantomKeysManager
8012         pub fn get_phantom_scid(&self) -> u64 {
8013                 let best_block_height = self.best_block.read().unwrap().height();
8014                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8015                 loop {
8016                         let scid_candidate = fake_scid::Namespace::Phantom.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8017                         // Ensure the generated scid doesn't conflict with a real channel.
8018                         match short_to_chan_info.get(&scid_candidate) {
8019                                 Some(_) => continue,
8020                                 None => return scid_candidate
8021                         }
8022                 }
8023         }
8024
8025         /// Gets route hints for use in receiving [phantom node payments].
8026         ///
8027         /// [phantom node payments]: crate::sign::PhantomKeysManager
8028         pub fn get_phantom_route_hints(&self) -> PhantomRouteHints {
8029                 PhantomRouteHints {
8030                         channels: self.list_usable_channels(),
8031                         phantom_scid: self.get_phantom_scid(),
8032                         real_node_pubkey: self.get_our_node_id(),
8033                 }
8034         }
8035
8036         /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
8037         /// used when constructing the route hints for HTLCs intended to be intercepted. See
8038         /// [`ChannelManager::forward_intercepted_htlc`].
8039         ///
8040         /// Note that this method is not guaranteed to return unique values, you may need to call it a few
8041         /// times to get a unique scid.
8042         pub fn get_intercept_scid(&self) -> u64 {
8043                 let best_block_height = self.best_block.read().unwrap().height();
8044                 let short_to_chan_info = self.short_to_chan_info.read().unwrap();
8045                 loop {
8046                         let scid_candidate = fake_scid::Namespace::Intercept.get_fake_scid(best_block_height, &self.chain_hash, &self.fake_scid_rand_bytes, &self.entropy_source);
8047                         // Ensure the generated scid doesn't conflict with a real channel.
8048                         if short_to_chan_info.contains_key(&scid_candidate) { continue }
8049                         return scid_candidate
8050                 }
8051         }
8052
8053         /// Gets inflight HTLC information by processing pending outbound payments that are in
8054         /// our channels. May be used during pathfinding to account for in-use channel liquidity.
8055         pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
8056                 let mut inflight_htlcs = InFlightHtlcs::new();
8057
8058                 let per_peer_state = self.per_peer_state.read().unwrap();
8059                 for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8060                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8061                         let peer_state = &mut *peer_state_lock;
8062                         for chan in peer_state.channel_by_id.values().filter_map(
8063                                 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
8064                         ) {
8065                                 for (htlc_source, _) in chan.inflight_htlc_sources() {
8066                                         if let HTLCSource::OutboundRoute { path, .. } = htlc_source {
8067                                                 inflight_htlcs.process_path(path, self.get_our_node_id());
8068                                         }
8069                                 }
8070                         }
8071                 }
8072
8073                 inflight_htlcs
8074         }
8075
8076         #[cfg(any(test, feature = "_test_utils"))]
8077         pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
8078                 let events = core::cell::RefCell::new(Vec::new());
8079                 let event_handler = |event: events::Event| events.borrow_mut().push(event);
8080                 self.process_pending_events(&event_handler);
8081                 events.into_inner()
8082         }
8083
8084         #[cfg(feature = "_test_utils")]
8085         pub fn push_pending_event(&self, event: events::Event) {
8086                 let mut events = self.pending_events.lock().unwrap();
8087                 events.push_back((event, None));
8088         }
8089
8090         #[cfg(test)]
8091         pub fn pop_pending_event(&self) -> Option<events::Event> {
8092                 let mut events = self.pending_events.lock().unwrap();
8093                 events.pop_front().map(|(e, _)| e)
8094         }
8095
8096         #[cfg(test)]
8097         pub fn has_pending_payments(&self) -> bool {
8098                 self.pending_outbound_payments.has_pending_payments()
8099         }
8100
8101         #[cfg(test)]
8102         pub fn clear_pending_payments(&self) {
8103                 self.pending_outbound_payments.clear_pending_payments()
8104         }
8105
8106         /// When something which was blocking a channel from updating its [`ChannelMonitor`] (e.g. an
8107         /// [`Event`] being handled) completes, this should be called to restore the channel to normal
8108         /// operation. It will double-check that nothing *else* is also blocking the same channel from
8109         /// making progress and then let any blocked [`ChannelMonitorUpdate`]s fly.
8110         fn handle_monitor_update_release(&self, counterparty_node_id: PublicKey,
8111                 channel_funding_outpoint: OutPoint, channel_id: ChannelId,
8112                 mut completed_blocker: Option<RAAMonitorUpdateBlockingAction>) {
8113
8114                 let logger = WithContext::from(
8115                         &self.logger, Some(counterparty_node_id), Some(channel_id),
8116                 );
8117                 loop {
8118                         let per_peer_state = self.per_peer_state.read().unwrap();
8119                         if let Some(peer_state_mtx) = per_peer_state.get(&counterparty_node_id) {
8120                                 let mut peer_state_lck = peer_state_mtx.lock().unwrap();
8121                                 let peer_state = &mut *peer_state_lck;
8122                                 if let Some(blocker) = completed_blocker.take() {
8123                                         // Only do this on the first iteration of the loop.
8124                                         if let Some(blockers) = peer_state.actions_blocking_raa_monitor_updates
8125                                                 .get_mut(&channel_id)
8126                                         {
8127                                                 blockers.retain(|iter| iter != &blocker);
8128                                         }
8129                                 }
8130
8131                                 if self.raa_monitor_updates_held(&peer_state.actions_blocking_raa_monitor_updates,
8132                                         channel_funding_outpoint, channel_id, counterparty_node_id) {
8133                                         // Check that, while holding the peer lock, we don't have anything else
8134                                         // blocking monitor updates for this channel. If we do, release the monitor
8135                                         // update(s) when those blockers complete.
8136                                         log_trace!(logger, "Delaying monitor unlock for channel {} as another channel's mon update needs to complete first",
8137                                                 &channel_id);
8138                                         break;
8139                                 }
8140
8141                                 if let hash_map::Entry::Occupied(mut chan_phase_entry) = peer_state.channel_by_id.entry(
8142                                         channel_id) {
8143                                         if let ChannelPhase::Funded(chan) = chan_phase_entry.get_mut() {
8144                                                 debug_assert_eq!(chan.context.get_funding_txo().unwrap(), channel_funding_outpoint);
8145                                                 if let Some((monitor_update, further_update_exists)) = chan.unblock_next_blocked_monitor_update() {
8146                                                         log_debug!(logger, "Unlocking monitor updating for channel {} and updating monitor",
8147                                                                 channel_id);
8148                                                         handle_new_monitor_update!(self, channel_funding_outpoint, channel_id, monitor_update,
8149                                                                 peer_state_lck, peer_state, per_peer_state, chan);
8150                                                         if further_update_exists {
8151                                                                 // If there are more `ChannelMonitorUpdate`s to process, restart at the
8152                                                                 // top of the loop.
8153                                                                 continue;
8154                                                         }
8155                                                 } else {
8156                                                         log_trace!(logger, "Unlocked monitor updating for channel {} without monitors to update",
8157                                                                 channel_id);
8158                                                 }
8159                                         }
8160                                 }
8161                         } else {
8162                                 log_debug!(logger,
8163                                         "Got a release post-RAA monitor update for peer {} but the channel is gone",
8164                                         log_pubkey!(counterparty_node_id));
8165                         }
8166                         break;
8167                 }
8168         }
8169
8170         fn handle_post_event_actions(&self, actions: Vec<EventCompletionAction>) {
8171                 for action in actions {
8172                         match action {
8173                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
8174                                         channel_funding_outpoint, channel_id, counterparty_node_id
8175                                 } => {
8176                                         self.handle_monitor_update_release(counterparty_node_id, channel_funding_outpoint, channel_id, None);
8177                                 }
8178                         }
8179                 }
8180         }
8181
8182         /// Processes any events asynchronously in the order they were generated since the last call
8183         /// using the given event handler.
8184         ///
8185         /// See the trait-level documentation of [`EventsProvider`] for requirements.
8186         pub async fn process_pending_events_async<Future: core::future::Future, H: Fn(Event) -> Future>(
8187                 &self, handler: H
8188         ) {
8189                 let mut ev;
8190                 process_events_body!(self, ev, { handler(ev).await });
8191         }
8192 }
8193
8194 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>
8195 where
8196         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8197         T::Target: BroadcasterInterface,
8198         ES::Target: EntropySource,
8199         NS::Target: NodeSigner,
8200         SP::Target: SignerProvider,
8201         F::Target: FeeEstimator,
8202         R::Target: Router,
8203         L::Target: Logger,
8204 {
8205         /// Returns `MessageSendEvent`s strictly ordered per-peer, in the order they were generated.
8206         /// The returned array will contain `MessageSendEvent`s for different peers if
8207         /// `MessageSendEvent`s to more than one peer exists, but `MessageSendEvent`s to the same peer
8208         /// is always placed next to each other.
8209         ///
8210         /// Note that that while `MessageSendEvent`s are strictly ordered per-peer, the peer order for
8211         /// the chunks of `MessageSendEvent`s for different peers is random. I.e. if the array contains
8212         /// `MessageSendEvent`s  for both `node_a` and `node_b`, the `MessageSendEvent`s for `node_a`
8213         /// will randomly be placed first or last in the returned array.
8214         ///
8215         /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
8216         /// `MessageSendEvent`s are intended to be broadcasted to all peers, they will be placed among
8217         /// the `MessageSendEvent`s to the specific peer they were generated under.
8218         fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
8219                 let events = RefCell::new(Vec::new());
8220                 PersistenceNotifierGuard::optionally_notify(self, || {
8221                         let mut result = NotifyOption::SkipPersistNoEvents;
8222
8223                         // TODO: This behavior should be documented. It's unintuitive that we query
8224                         // ChannelMonitors when clearing other events.
8225                         if self.process_pending_monitor_events() {
8226                                 result = NotifyOption::DoPersist;
8227                         }
8228
8229                         if self.check_free_holding_cells() {
8230                                 result = NotifyOption::DoPersist;
8231                         }
8232                         if self.maybe_generate_initial_closing_signed() {
8233                                 result = NotifyOption::DoPersist;
8234                         }
8235
8236                         let mut is_any_peer_connected = false;
8237                         let mut pending_events = Vec::new();
8238                         let per_peer_state = self.per_peer_state.read().unwrap();
8239                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8240                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8241                                 let peer_state = &mut *peer_state_lock;
8242                                 if peer_state.pending_msg_events.len() > 0 {
8243                                         pending_events.append(&mut peer_state.pending_msg_events);
8244                                 }
8245                                 if peer_state.is_connected {
8246                                         is_any_peer_connected = true
8247                                 }
8248                         }
8249
8250                         // Ensure that we are connected to some peers before getting broadcast messages.
8251                         if is_any_peer_connected {
8252                                 let mut broadcast_msgs = self.pending_broadcast_messages.lock().unwrap();
8253                                 pending_events.append(&mut broadcast_msgs);
8254                         }
8255
8256                         if !pending_events.is_empty() {
8257                                 events.replace(pending_events);
8258                         }
8259
8260                         result
8261                 });
8262                 events.into_inner()
8263         }
8264 }
8265
8266 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>
8267 where
8268         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8269         T::Target: BroadcasterInterface,
8270         ES::Target: EntropySource,
8271         NS::Target: NodeSigner,
8272         SP::Target: SignerProvider,
8273         F::Target: FeeEstimator,
8274         R::Target: Router,
8275         L::Target: Logger,
8276 {
8277         /// Processes events that must be periodically handled.
8278         ///
8279         /// An [`EventHandler`] may safely call back to the provider in order to handle an event.
8280         /// However, it must not call [`Writeable::write`] as doing so would result in a deadlock.
8281         fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
8282                 let mut ev;
8283                 process_events_body!(self, ev, handler.handle_event(ev));
8284         }
8285 }
8286
8287 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>
8288 where
8289         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8290         T::Target: BroadcasterInterface,
8291         ES::Target: EntropySource,
8292         NS::Target: NodeSigner,
8293         SP::Target: SignerProvider,
8294         F::Target: FeeEstimator,
8295         R::Target: Router,
8296         L::Target: Logger,
8297 {
8298         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
8299                 {
8300                         let best_block = self.best_block.read().unwrap();
8301                         assert_eq!(best_block.block_hash(), header.prev_blockhash,
8302                                 "Blocks must be connected in chain-order - the connected header must build on the last connected header");
8303                         assert_eq!(best_block.height(), height - 1,
8304                                 "Blocks must be connected in chain-order - the connected block height must be one greater than the previous height");
8305                 }
8306
8307                 self.transactions_confirmed(header, txdata, height);
8308                 self.best_block_updated(header, height);
8309         }
8310
8311         fn block_disconnected(&self, header: &Header, height: u32) {
8312                 let _persistence_guard =
8313                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8314                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8315                 let new_height = height - 1;
8316                 {
8317                         let mut best_block = self.best_block.write().unwrap();
8318                         assert_eq!(best_block.block_hash(), header.block_hash(),
8319                                 "Blocks must be disconnected in chain-order - the disconnected header must be the last connected header");
8320                         assert_eq!(best_block.height(), height,
8321                                 "Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
8322                         *best_block = BestBlock::new(header.prev_blockhash, new_height)
8323                 }
8324
8325                 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)));
8326         }
8327 }
8328
8329 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>
8330 where
8331         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8332         T::Target: BroadcasterInterface,
8333         ES::Target: EntropySource,
8334         NS::Target: NodeSigner,
8335         SP::Target: SignerProvider,
8336         F::Target: FeeEstimator,
8337         R::Target: Router,
8338         L::Target: Logger,
8339 {
8340         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
8341                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8342                 // during initialization prior to the chain_monitor being fully configured in some cases.
8343                 // See the docs for `ChannelManagerReadArgs` for more.
8344
8345                 let block_hash = header.block_hash();
8346                 log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
8347
8348                 let _persistence_guard =
8349                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8350                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8351                 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))
8352                         .map(|(a, b)| (a, Vec::new(), b)));
8353
8354                 let last_best_block_height = self.best_block.read().unwrap().height();
8355                 if height < last_best_block_height {
8356                         let timestamp = self.highest_seen_timestamp.load(Ordering::Acquire);
8357                         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)));
8358                 }
8359         }
8360
8361         fn best_block_updated(&self, header: &Header, height: u32) {
8362                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8363                 // during initialization prior to the chain_monitor being fully configured in some cases.
8364                 // See the docs for `ChannelManagerReadArgs` for more.
8365
8366                 let block_hash = header.block_hash();
8367                 log_trace!(self.logger, "New best block: {} at height {}", block_hash, height);
8368
8369                 let _persistence_guard =
8370                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8371                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8372                 *self.best_block.write().unwrap() = BestBlock::new(block_hash, height);
8373
8374                 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)));
8375
8376                 macro_rules! max_time {
8377                         ($timestamp: expr) => {
8378                                 loop {
8379                                         // Update $timestamp to be the max of its current value and the block
8380                                         // timestamp. This should keep us close to the current time without relying on
8381                                         // having an explicit local time source.
8382                                         // Just in case we end up in a race, we loop until we either successfully
8383                                         // update $timestamp or decide we don't need to.
8384                                         let old_serial = $timestamp.load(Ordering::Acquire);
8385                                         if old_serial >= header.time as usize { break; }
8386                                         if $timestamp.compare_exchange(old_serial, header.time as usize, Ordering::AcqRel, Ordering::Relaxed).is_ok() {
8387                                                 break;
8388                                         }
8389                                 }
8390                         }
8391                 }
8392                 max_time!(self.highest_seen_timestamp);
8393                 let mut payment_secrets = self.pending_inbound_payments.lock().unwrap();
8394                 payment_secrets.retain(|_, inbound_payment| {
8395                         inbound_payment.expiry_time > header.time as u64
8396                 });
8397         }
8398
8399         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)> {
8400                 let mut res = Vec::with_capacity(self.short_to_chan_info.read().unwrap().len());
8401                 for (_cp_id, peer_state_mutex) in self.per_peer_state.read().unwrap().iter() {
8402                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8403                         let peer_state = &mut *peer_state_lock;
8404                         for chan in peer_state.channel_by_id.values().filter_map(|phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }) {
8405                                 let txid_opt = chan.context.get_funding_txo();
8406                                 let height_opt = chan.context.get_funding_tx_confirmation_height();
8407                                 let hash_opt = chan.context.get_funding_tx_confirmed_in();
8408                                 if let (Some(funding_txo), Some(conf_height), Some(block_hash)) = (txid_opt, height_opt, hash_opt) {
8409                                         res.push((funding_txo.txid, conf_height, Some(block_hash)));
8410                                 }
8411                         }
8412                 }
8413                 res
8414         }
8415
8416         fn transaction_unconfirmed(&self, txid: &Txid) {
8417                 let _persistence_guard =
8418                         PersistenceNotifierGuard::optionally_notify_skipping_background_events(
8419                                 self, || -> NotifyOption { NotifyOption::DoPersist });
8420                 self.do_chain_event(None, |channel| {
8421                         if let Some(funding_txo) = channel.context.get_funding_txo() {
8422                                 if funding_txo.txid == *txid {
8423                                         channel.funding_transaction_unconfirmed(&&WithChannelContext::from(&self.logger, &channel.context)).map(|()| (None, Vec::new(), None))
8424                                 } else { Ok((None, Vec::new(), None)) }
8425                         } else { Ok((None, Vec::new(), None)) }
8426                 });
8427         }
8428 }
8429
8430 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>
8431 where
8432         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8433         T::Target: BroadcasterInterface,
8434         ES::Target: EntropySource,
8435         NS::Target: NodeSigner,
8436         SP::Target: SignerProvider,
8437         F::Target: FeeEstimator,
8438         R::Target: Router,
8439         L::Target: Logger,
8440 {
8441         /// Calls a function which handles an on-chain event (blocks dis/connected, transactions
8442         /// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
8443         /// the function.
8444         fn do_chain_event<FN: Fn(&mut Channel<SP>) -> Result<(Option<msgs::ChannelReady>, Vec<(HTLCSource, PaymentHash)>, Option<msgs::AnnouncementSignatures>), ClosureReason>>
8445                         (&self, height_opt: Option<u32>, f: FN) {
8446                 // Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
8447                 // during initialization prior to the chain_monitor being fully configured in some cases.
8448                 // See the docs for `ChannelManagerReadArgs` for more.
8449
8450                 let mut failed_channels = Vec::new();
8451                 let mut timed_out_htlcs = Vec::new();
8452                 {
8453                         let per_peer_state = self.per_peer_state.read().unwrap();
8454                         for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
8455                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8456                                 let peer_state = &mut *peer_state_lock;
8457                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8458
8459                                 peer_state.channel_by_id.retain(|_, phase| {
8460                                         match phase {
8461                                                 // Retain unfunded channels.
8462                                                 ChannelPhase::UnfundedOutboundV1(_) | ChannelPhase::UnfundedInboundV1(_) => true,
8463                                                 ChannelPhase::Funded(channel) => {
8464                                                         let res = f(channel);
8465                                                         if let Ok((channel_ready_opt, mut timed_out_pending_htlcs, announcement_sigs)) = res {
8466                                                                 for (source, payment_hash) in timed_out_pending_htlcs.drain(..) {
8467                                                                         let (failure_code, data) = self.get_htlc_inbound_temp_fail_err_and_data(0x1000|14 /* expiry_too_soon */, &channel);
8468                                                                         timed_out_htlcs.push((source, payment_hash, HTLCFailReason::reason(failure_code, data),
8469                                                                                 HTLCDestination::NextHopChannel { node_id: Some(channel.context.get_counterparty_node_id()), channel_id: channel.context.channel_id() }));
8470                                                                 }
8471                                                                 let logger = WithChannelContext::from(&self.logger, &channel.context);
8472                                                                 if let Some(channel_ready) = channel_ready_opt {
8473                                                                         send_channel_ready!(self, pending_msg_events, channel, channel_ready);
8474                                                                         if channel.context.is_usable() {
8475                                                                                 log_trace!(logger, "Sending channel_ready with private initial channel_update for our counterparty on channel {}", channel.context.channel_id());
8476                                                                                 if let Ok(msg) = self.get_channel_update_for_unicast(channel) {
8477                                                                                         pending_msg_events.push(events::MessageSendEvent::SendChannelUpdate {
8478                                                                                                 node_id: channel.context.get_counterparty_node_id(),
8479                                                                                                 msg,
8480                                                                                         });
8481                                                                                 }
8482                                                                         } else {
8483                                                                                 log_trace!(logger, "Sending channel_ready WITHOUT channel_update for {}", channel.context.channel_id());
8484                                                                         }
8485                                                                 }
8486
8487                                                                 {
8488                                                                         let mut pending_events = self.pending_events.lock().unwrap();
8489                                                                         emit_channel_ready_event!(pending_events, channel);
8490                                                                 }
8491
8492                                                                 if let Some(announcement_sigs) = announcement_sigs {
8493                                                                         log_trace!(logger, "Sending announcement_signatures for channel {}", channel.context.channel_id());
8494                                                                         pending_msg_events.push(events::MessageSendEvent::SendAnnouncementSignatures {
8495                                                                                 node_id: channel.context.get_counterparty_node_id(),
8496                                                                                 msg: announcement_sigs,
8497                                                                         });
8498                                                                         if let Some(height) = height_opt {
8499                                                                                 if let Some(announcement) = channel.get_signed_channel_announcement(&self.node_signer, self.chain_hash, height, &self.default_configuration) {
8500                                                                                         pending_msg_events.push(events::MessageSendEvent::BroadcastChannelAnnouncement {
8501                                                                                                 msg: announcement,
8502                                                                                                 // Note that announcement_signatures fails if the channel cannot be announced,
8503                                                                                                 // so get_channel_update_for_broadcast will never fail by the time we get here.
8504                                                                                                 update_msg: Some(self.get_channel_update_for_broadcast(channel).unwrap()),
8505                                                                                         });
8506                                                                                 }
8507                                                                         }
8508                                                                 }
8509                                                                 if channel.is_our_channel_ready() {
8510                                                                         if let Some(real_scid) = channel.context.get_short_channel_id() {
8511                                                                                 // If we sent a 0conf channel_ready, and now have an SCID, we add it
8512                                                                                 // to the short_to_chan_info map here. Note that we check whether we
8513                                                                                 // can relay using the real SCID at relay-time (i.e.
8514                                                                                 // enforce option_scid_alias then), and if the funding tx is ever
8515                                                                                 // un-confirmed we force-close the channel, ensuring short_to_chan_info
8516                                                                                 // is always consistent.
8517                                                                                 let mut short_to_chan_info = self.short_to_chan_info.write().unwrap();
8518                                                                                 let scid_insert = short_to_chan_info.insert(real_scid, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
8519                                                                                 assert!(scid_insert.is_none() || scid_insert.unwrap() == (channel.context.get_counterparty_node_id(), channel.context.channel_id()),
8520                                                                                         "SCIDs should never collide - ensure you weren't behind by a full {} blocks when creating channels",
8521                                                                                         fake_scid::MAX_SCID_BLOCKS_FROM_NOW);
8522                                                                         }
8523                                                                 }
8524                                                         } else if let Err(reason) = res {
8525                                                                 update_maps_on_chan_removal!(self, &channel.context);
8526                                                                 // It looks like our counterparty went on-chain or funding transaction was
8527                                                                 // reorged out of the main chain. Close the channel.
8528                                                                 let reason_message = format!("{}", reason);
8529                                                                 failed_channels.push(channel.context.force_shutdown(true, reason));
8530                                                                 if let Ok(update) = self.get_channel_update_for_broadcast(&channel) {
8531                                                                         let mut pending_broadcast_messages = self.pending_broadcast_messages.lock().unwrap();
8532                                                                         pending_broadcast_messages.push(events::MessageSendEvent::BroadcastChannelUpdate {
8533                                                                                 msg: update
8534                                                                         });
8535                                                                 }
8536                                                                 pending_msg_events.push(events::MessageSendEvent::HandleError {
8537                                                                         node_id: channel.context.get_counterparty_node_id(),
8538                                                                         action: msgs::ErrorAction::DisconnectPeer {
8539                                                                                 msg: Some(msgs::ErrorMessage {
8540                                                                                         channel_id: channel.context.channel_id(),
8541                                                                                         data: reason_message,
8542                                                                                 })
8543                                                                         },
8544                                                                 });
8545                                                                 return false;
8546                                                         }
8547                                                         true
8548                                                 }
8549                                         }
8550                                 });
8551                         }
8552                 }
8553
8554                 if let Some(height) = height_opt {
8555                         self.claimable_payments.lock().unwrap().claimable_payments.retain(|payment_hash, payment| {
8556                                 payment.htlcs.retain(|htlc| {
8557                                         // If height is approaching the number of blocks we think it takes us to get
8558                                         // our commitment transaction confirmed before the HTLC expires, plus the
8559                                         // number of blocks we generally consider it to take to do a commitment update,
8560                                         // just give up on it and fail the HTLC.
8561                                         if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
8562                                                 let mut htlc_msat_height_data = htlc.value.to_be_bytes().to_vec();
8563                                                 htlc_msat_height_data.extend_from_slice(&height.to_be_bytes());
8564
8565                                                 timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(),
8566                                                         HTLCFailReason::reason(0x4000 | 15, htlc_msat_height_data),
8567                                                         HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }));
8568                                                 false
8569                                         } else { true }
8570                                 });
8571                                 !payment.htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
8572                         });
8573
8574                         let mut intercepted_htlcs = self.pending_intercepted_htlcs.lock().unwrap();
8575                         intercepted_htlcs.retain(|_, htlc| {
8576                                 if height >= htlc.forward_info.outgoing_cltv_value - HTLC_FAIL_BACK_BUFFER {
8577                                         let prev_hop_data = HTLCSource::PreviousHopData(HTLCPreviousHopData {
8578                                                 short_channel_id: htlc.prev_short_channel_id,
8579                                                 user_channel_id: Some(htlc.prev_user_channel_id),
8580                                                 htlc_id: htlc.prev_htlc_id,
8581                                                 incoming_packet_shared_secret: htlc.forward_info.incoming_shared_secret,
8582                                                 phantom_shared_secret: None,
8583                                                 outpoint: htlc.prev_funding_outpoint,
8584                                                 channel_id: htlc.prev_channel_id,
8585                                                 blinded_failure: htlc.forward_info.routing.blinded_failure(),
8586                                         });
8587
8588                                         let requested_forward_scid /* intercept scid */ = match htlc.forward_info.routing {
8589                                                 PendingHTLCRouting::Forward { short_channel_id, .. } => short_channel_id,
8590                                                 _ => unreachable!(),
8591                                         };
8592                                         timed_out_htlcs.push((prev_hop_data, htlc.forward_info.payment_hash,
8593                                                         HTLCFailReason::from_failure_code(0x2000 | 2),
8594                                                         HTLCDestination::InvalidForward { requested_forward_scid }));
8595                                         let logger = WithContext::from(
8596                                                 &self.logger, None, Some(htlc.prev_channel_id)
8597                                         );
8598                                         log_trace!(logger, "Timing out intercepted HTLC with requested forward scid {}", requested_forward_scid);
8599                                         false
8600                                 } else { true }
8601                         });
8602                 }
8603
8604                 self.handle_init_event_channel_failures(failed_channels);
8605
8606                 for (source, payment_hash, reason, destination) in timed_out_htlcs.drain(..) {
8607                         self.fail_htlc_backwards_internal(&source, &payment_hash, &reason, destination);
8608                 }
8609         }
8610
8611         /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
8612         /// may have events that need processing.
8613         ///
8614         /// In order to check if this [`ChannelManager`] needs persisting, call
8615         /// [`Self::get_and_clear_needs_persistence`].
8616         ///
8617         /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
8618         /// [`ChannelManager`] and should instead register actions to be taken later.
8619         pub fn get_event_or_persistence_needed_future(&self) -> Future {
8620                 self.event_persist_notifier.get_future()
8621         }
8622
8623         /// Returns true if this [`ChannelManager`] needs to be persisted.
8624         pub fn get_and_clear_needs_persistence(&self) -> bool {
8625                 self.needs_persist_flag.swap(false, Ordering::AcqRel)
8626         }
8627
8628         #[cfg(any(test, feature = "_test_utils"))]
8629         pub fn get_event_or_persist_condvar_value(&self) -> bool {
8630                 self.event_persist_notifier.notify_pending()
8631         }
8632
8633         /// Gets the latest best block which was connected either via the [`chain::Listen`] or
8634         /// [`chain::Confirm`] interfaces.
8635         pub fn current_best_block(&self) -> BestBlock {
8636                 self.best_block.read().unwrap().clone()
8637         }
8638
8639         /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
8640         /// [`ChannelManager`].
8641         pub fn node_features(&self) -> NodeFeatures {
8642                 provided_node_features(&self.default_configuration)
8643         }
8644
8645         /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
8646         /// [`ChannelManager`].
8647         ///
8648         /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
8649         /// or not. Thus, this method is not public.
8650         #[cfg(any(feature = "_test_utils", test))]
8651         pub fn bolt11_invoice_features(&self) -> Bolt11InvoiceFeatures {
8652                 provided_bolt11_invoice_features(&self.default_configuration)
8653         }
8654
8655         /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
8656         /// [`ChannelManager`].
8657         fn bolt12_invoice_features(&self) -> Bolt12InvoiceFeatures {
8658                 provided_bolt12_invoice_features(&self.default_configuration)
8659         }
8660
8661         /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
8662         /// [`ChannelManager`].
8663         pub fn channel_features(&self) -> ChannelFeatures {
8664                 provided_channel_features(&self.default_configuration)
8665         }
8666
8667         /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
8668         /// [`ChannelManager`].
8669         pub fn channel_type_features(&self) -> ChannelTypeFeatures {
8670                 provided_channel_type_features(&self.default_configuration)
8671         }
8672
8673         /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
8674         /// [`ChannelManager`].
8675         pub fn init_features(&self) -> InitFeatures {
8676                 provided_init_features(&self.default_configuration)
8677         }
8678 }
8679
8680 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
8681         ChannelMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
8682 where
8683         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
8684         T::Target: BroadcasterInterface,
8685         ES::Target: EntropySource,
8686         NS::Target: NodeSigner,
8687         SP::Target: SignerProvider,
8688         F::Target: FeeEstimator,
8689         R::Target: Router,
8690         L::Target: Logger,
8691 {
8692         fn handle_open_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannel) {
8693                 // Note that we never need to persist the updated ChannelManager for an inbound
8694                 // open_channel message - pre-funded channels are never written so there should be no
8695                 // change to the contents.
8696                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8697                         let res = self.internal_open_channel(counterparty_node_id, msg);
8698                         let persist = match &res {
8699                                 Err(e) if e.closes_channel() => {
8700                                         debug_assert!(false, "We shouldn't close a new channel");
8701                                         NotifyOption::DoPersist
8702                                 },
8703                                 _ => NotifyOption::SkipPersistHandleEvents,
8704                         };
8705                         let _ = handle_error!(self, res, *counterparty_node_id);
8706                         persist
8707                 });
8708         }
8709
8710         fn handle_open_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::OpenChannelV2) {
8711                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8712                         "Dual-funded channels not supported".to_owned(),
8713                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8714         }
8715
8716         fn handle_accept_channel(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannel) {
8717                 // Note that we never need to persist the updated ChannelManager for an inbound
8718                 // accept_channel message - pre-funded channels are never written so there should be no
8719                 // change to the contents.
8720                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8721                         let _ = handle_error!(self, self.internal_accept_channel(counterparty_node_id, msg), *counterparty_node_id);
8722                         NotifyOption::SkipPersistHandleEvents
8723                 });
8724         }
8725
8726         fn handle_accept_channel_v2(&self, counterparty_node_id: &PublicKey, msg: &msgs::AcceptChannelV2) {
8727                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8728                         "Dual-funded channels not supported".to_owned(),
8729                          msg.temporary_channel_id.clone())), *counterparty_node_id);
8730         }
8731
8732         fn handle_funding_created(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingCreated) {
8733                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8734                 let _ = handle_error!(self, self.internal_funding_created(counterparty_node_id, msg), *counterparty_node_id);
8735         }
8736
8737         fn handle_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) {
8738                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8739                 let _ = handle_error!(self, self.internal_funding_signed(counterparty_node_id, msg), *counterparty_node_id);
8740         }
8741
8742         fn handle_channel_ready(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReady) {
8743                 // Note that we never need to persist the updated ChannelManager for an inbound
8744                 // channel_ready message - while the channel's state will change, any channel_ready message
8745                 // will ultimately be re-sent on startup and the `ChannelMonitor` won't be updated so we
8746                 // will not force-close the channel on startup.
8747                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8748                         let res = self.internal_channel_ready(counterparty_node_id, msg);
8749                         let persist = match &res {
8750                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8751                                 _ => NotifyOption::SkipPersistHandleEvents,
8752                         };
8753                         let _ = handle_error!(self, res, *counterparty_node_id);
8754                         persist
8755                 });
8756         }
8757
8758         fn handle_stfu(&self, counterparty_node_id: &PublicKey, msg: &msgs::Stfu) {
8759                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8760                         "Quiescence not supported".to_owned(),
8761                          msg.channel_id.clone())), *counterparty_node_id);
8762         }
8763
8764         fn handle_splice(&self, counterparty_node_id: &PublicKey, msg: &msgs::Splice) {
8765                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8766                         "Splicing not supported".to_owned(),
8767                          msg.channel_id.clone())), *counterparty_node_id);
8768         }
8769
8770         fn handle_splice_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceAck) {
8771                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8772                         "Splicing not supported (splice_ack)".to_owned(),
8773                          msg.channel_id.clone())), *counterparty_node_id);
8774         }
8775
8776         fn handle_splice_locked(&self, counterparty_node_id: &PublicKey, msg: &msgs::SpliceLocked) {
8777                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
8778                         "Splicing not supported (splice_locked)".to_owned(),
8779                          msg.channel_id.clone())), *counterparty_node_id);
8780         }
8781
8782         fn handle_shutdown(&self, counterparty_node_id: &PublicKey, msg: &msgs::Shutdown) {
8783                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8784                 let _ = handle_error!(self, self.internal_shutdown(counterparty_node_id, msg), *counterparty_node_id);
8785         }
8786
8787         fn handle_closing_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
8788                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8789                 let _ = handle_error!(self, self.internal_closing_signed(counterparty_node_id, msg), *counterparty_node_id);
8790         }
8791
8792         fn handle_update_add_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
8793                 // Note that we never need to persist the updated ChannelManager for an inbound
8794                 // update_add_htlc message - the message itself doesn't change our channel state only the
8795                 // `commitment_signed` message afterwards will.
8796                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8797                         let res = self.internal_update_add_htlc(counterparty_node_id, msg);
8798                         let persist = match &res {
8799                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8800                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8801                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8802                         };
8803                         let _ = handle_error!(self, res, *counterparty_node_id);
8804                         persist
8805                 });
8806         }
8807
8808         fn handle_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
8809                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8810                 let _ = handle_error!(self, self.internal_update_fulfill_htlc(counterparty_node_id, msg), *counterparty_node_id);
8811         }
8812
8813         fn handle_update_fail_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
8814                 // Note that we never need to persist the updated ChannelManager for an inbound
8815                 // update_fail_htlc message - the message itself doesn't change our channel state only the
8816                 // `commitment_signed` message afterwards will.
8817                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8818                         let res = self.internal_update_fail_htlc(counterparty_node_id, msg);
8819                         let persist = match &res {
8820                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8821                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8822                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8823                         };
8824                         let _ = handle_error!(self, res, *counterparty_node_id);
8825                         persist
8826                 });
8827         }
8828
8829         fn handle_update_fail_malformed_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
8830                 // Note that we never need to persist the updated ChannelManager for an inbound
8831                 // update_fail_malformed_htlc message - the message itself doesn't change our channel state
8832                 // only the `commitment_signed` message afterwards will.
8833                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8834                         let res = self.internal_update_fail_malformed_htlc(counterparty_node_id, msg);
8835                         let persist = match &res {
8836                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8837                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8838                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8839                         };
8840                         let _ = handle_error!(self, res, *counterparty_node_id);
8841                         persist
8842                 });
8843         }
8844
8845         fn handle_commitment_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
8846                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8847                 let _ = handle_error!(self, self.internal_commitment_signed(counterparty_node_id, msg), *counterparty_node_id);
8848         }
8849
8850         fn handle_revoke_and_ack(&self, counterparty_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
8851                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8852                 let _ = handle_error!(self, self.internal_revoke_and_ack(counterparty_node_id, msg), *counterparty_node_id);
8853         }
8854
8855         fn handle_update_fee(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFee) {
8856                 // Note that we never need to persist the updated ChannelManager for an inbound
8857                 // update_fee message - the message itself doesn't change our channel state only the
8858                 // `commitment_signed` message afterwards will.
8859                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8860                         let res = self.internal_update_fee(counterparty_node_id, msg);
8861                         let persist = match &res {
8862                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8863                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8864                                 Ok(()) => NotifyOption::SkipPersistNoEvents,
8865                         };
8866                         let _ = handle_error!(self, res, *counterparty_node_id);
8867                         persist
8868                 });
8869         }
8870
8871         fn handle_announcement_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
8872                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
8873                 let _ = handle_error!(self, self.internal_announcement_signatures(counterparty_node_id, msg), *counterparty_node_id);
8874         }
8875
8876         fn handle_channel_update(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelUpdate) {
8877                 PersistenceNotifierGuard::optionally_notify(self, || {
8878                         if let Ok(persist) = handle_error!(self, self.internal_channel_update(counterparty_node_id, msg), *counterparty_node_id) {
8879                                 persist
8880                         } else {
8881                                 NotifyOption::DoPersist
8882                         }
8883                 });
8884         }
8885
8886         fn handle_channel_reestablish(&self, counterparty_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
8887                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(self, || {
8888                         let res = self.internal_channel_reestablish(counterparty_node_id, msg);
8889                         let persist = match &res {
8890                                 Err(e) if e.closes_channel() => NotifyOption::DoPersist,
8891                                 Err(_) => NotifyOption::SkipPersistHandleEvents,
8892                                 Ok(persist) => *persist,
8893                         };
8894                         let _ = handle_error!(self, res, *counterparty_node_id);
8895                         persist
8896                 });
8897         }
8898
8899         fn peer_disconnected(&self, counterparty_node_id: &PublicKey) {
8900                 let _persistence_guard = PersistenceNotifierGuard::optionally_notify(
8901                         self, || NotifyOption::SkipPersistHandleEvents);
8902                 let mut failed_channels = Vec::new();
8903                 let mut per_peer_state = self.per_peer_state.write().unwrap();
8904                 let remove_peer = {
8905                         log_debug!(
8906                                 WithContext::from(&self.logger, Some(*counterparty_node_id), None),
8907                                 "Marking channels with {} disconnected and generating channel_updates.",
8908                                 log_pubkey!(counterparty_node_id)
8909                         );
8910                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
8911                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
8912                                 let peer_state = &mut *peer_state_lock;
8913                                 let pending_msg_events = &mut peer_state.pending_msg_events;
8914                                 peer_state.channel_by_id.retain(|_, phase| {
8915                                         let context = match phase {
8916                                                 ChannelPhase::Funded(chan) => {
8917                                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
8918                                                         if chan.remove_uncommitted_htlcs_and_mark_paused(&&logger).is_ok() {
8919                                                                 // We only retain funded channels that are not shutdown.
8920                                                                 return true;
8921                                                         }
8922                                                         &mut chan.context
8923                                                 },
8924                                                 // Unfunded channels will always be removed.
8925                                                 ChannelPhase::UnfundedOutboundV1(chan) => {
8926                                                         &mut chan.context
8927                                                 },
8928                                                 ChannelPhase::UnfundedInboundV1(chan) => {
8929                                                         &mut chan.context
8930                                                 },
8931                                         };
8932                                         // Clean up for removal.
8933                                         update_maps_on_chan_removal!(self, &context);
8934                                         failed_channels.push(context.force_shutdown(false, ClosureReason::DisconnectedPeer));
8935                                         false
8936                                 });
8937                                 // Note that we don't bother generating any events for pre-accept channels -
8938                                 // they're not considered "channels" yet from the PoV of our events interface.
8939                                 peer_state.inbound_channel_request_by_id.clear();
8940                                 pending_msg_events.retain(|msg| {
8941                                         match msg {
8942                                                 // V1 Channel Establishment
8943                                                 &events::MessageSendEvent::SendAcceptChannel { .. } => false,
8944                                                 &events::MessageSendEvent::SendOpenChannel { .. } => false,
8945                                                 &events::MessageSendEvent::SendFundingCreated { .. } => false,
8946                                                 &events::MessageSendEvent::SendFundingSigned { .. } => false,
8947                                                 // V2 Channel Establishment
8948                                                 &events::MessageSendEvent::SendAcceptChannelV2 { .. } => false,
8949                                                 &events::MessageSendEvent::SendOpenChannelV2 { .. } => false,
8950                                                 // Common Channel Establishment
8951                                                 &events::MessageSendEvent::SendChannelReady { .. } => false,
8952                                                 &events::MessageSendEvent::SendAnnouncementSignatures { .. } => false,
8953                                                 // Quiescence
8954                                                 &events::MessageSendEvent::SendStfu { .. } => false,
8955                                                 // Splicing
8956                                                 &events::MessageSendEvent::SendSplice { .. } => false,
8957                                                 &events::MessageSendEvent::SendSpliceAck { .. } => false,
8958                                                 &events::MessageSendEvent::SendSpliceLocked { .. } => false,
8959                                                 // Interactive Transaction Construction
8960                                                 &events::MessageSendEvent::SendTxAddInput { .. } => false,
8961                                                 &events::MessageSendEvent::SendTxAddOutput { .. } => false,
8962                                                 &events::MessageSendEvent::SendTxRemoveInput { .. } => false,
8963                                                 &events::MessageSendEvent::SendTxRemoveOutput { .. } => false,
8964                                                 &events::MessageSendEvent::SendTxComplete { .. } => false,
8965                                                 &events::MessageSendEvent::SendTxSignatures { .. } => false,
8966                                                 &events::MessageSendEvent::SendTxInitRbf { .. } => false,
8967                                                 &events::MessageSendEvent::SendTxAckRbf { .. } => false,
8968                                                 &events::MessageSendEvent::SendTxAbort { .. } => false,
8969                                                 // Channel Operations
8970                                                 &events::MessageSendEvent::UpdateHTLCs { .. } => false,
8971                                                 &events::MessageSendEvent::SendRevokeAndACK { .. } => false,
8972                                                 &events::MessageSendEvent::SendClosingSigned { .. } => false,
8973                                                 &events::MessageSendEvent::SendShutdown { .. } => false,
8974                                                 &events::MessageSendEvent::SendChannelReestablish { .. } => false,
8975                                                 &events::MessageSendEvent::HandleError { .. } => false,
8976                                                 // Gossip
8977                                                 &events::MessageSendEvent::SendChannelAnnouncement { .. } => false,
8978                                                 &events::MessageSendEvent::BroadcastChannelAnnouncement { .. } => true,
8979                                                 // [`ChannelManager::pending_broadcast_events`] holds the [`BroadcastChannelUpdate`]
8980                                                 // This check here is to ensure exhaustivity.
8981                                                 &events::MessageSendEvent::BroadcastChannelUpdate { .. } => {
8982                                                         debug_assert!(false, "This event shouldn't have been here");
8983                                                         false
8984                                                 },
8985                                                 &events::MessageSendEvent::BroadcastNodeAnnouncement { .. } => true,
8986                                                 &events::MessageSendEvent::SendChannelUpdate { .. } => false,
8987                                                 &events::MessageSendEvent::SendChannelRangeQuery { .. } => false,
8988                                                 &events::MessageSendEvent::SendShortIdsQuery { .. } => false,
8989                                                 &events::MessageSendEvent::SendReplyChannelRange { .. } => false,
8990                                                 &events::MessageSendEvent::SendGossipTimestampFilter { .. } => false,
8991                                         }
8992                                 });
8993                                 debug_assert!(peer_state.is_connected, "A disconnected peer cannot disconnect");
8994                                 peer_state.is_connected = false;
8995                                 peer_state.ok_to_remove(true)
8996                         } else { debug_assert!(false, "Unconnected peer disconnected"); true }
8997                 };
8998                 if remove_peer {
8999                         per_peer_state.remove(counterparty_node_id);
9000                 }
9001                 mem::drop(per_peer_state);
9002
9003                 for failure in failed_channels.drain(..) {
9004                         self.finish_close_channel(failure);
9005                 }
9006         }
9007
9008         fn peer_connected(&self, counterparty_node_id: &PublicKey, init_msg: &msgs::Init, inbound: bool) -> Result<(), ()> {
9009                 let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), None);
9010                 if !init_msg.features.supports_static_remote_key() {
9011                         log_debug!(logger, "Peer {} does not support static remote key, disconnecting", log_pubkey!(counterparty_node_id));
9012                         return Err(());
9013                 }
9014
9015                 let mut res = Ok(());
9016
9017                 PersistenceNotifierGuard::optionally_notify(self, || {
9018                         // If we have too many peers connected which don't have funded channels, disconnect the
9019                         // peer immediately (as long as it doesn't have funded channels). If we have a bunch of
9020                         // unfunded channels taking up space in memory for disconnected peers, we still let new
9021                         // peers connect, but we'll reject new channels from them.
9022                         let connected_peers_without_funded_channels = self.peers_without_funded_channels(|node| node.is_connected);
9023                         let inbound_peer_limited = inbound && connected_peers_without_funded_channels >= MAX_NO_CHANNEL_PEERS;
9024
9025                         {
9026                                 let mut peer_state_lock = self.per_peer_state.write().unwrap();
9027                                 match peer_state_lock.entry(counterparty_node_id.clone()) {
9028                                         hash_map::Entry::Vacant(e) => {
9029                                                 if inbound_peer_limited {
9030                                                         res = Err(());
9031                                                         return NotifyOption::SkipPersistNoEvents;
9032                                                 }
9033                                                 e.insert(Mutex::new(PeerState {
9034                                                         channel_by_id: HashMap::new(),
9035                                                         inbound_channel_request_by_id: HashMap::new(),
9036                                                         latest_features: init_msg.features.clone(),
9037                                                         pending_msg_events: Vec::new(),
9038                                                         in_flight_monitor_updates: BTreeMap::new(),
9039                                                         monitor_update_blocked_actions: BTreeMap::new(),
9040                                                         actions_blocking_raa_monitor_updates: BTreeMap::new(),
9041                                                         is_connected: true,
9042                                                 }));
9043                                         },
9044                                         hash_map::Entry::Occupied(e) => {
9045                                                 let mut peer_state = e.get().lock().unwrap();
9046                                                 peer_state.latest_features = init_msg.features.clone();
9047
9048                                                 let best_block_height = self.best_block.read().unwrap().height();
9049                                                 if inbound_peer_limited &&
9050                                                         Self::unfunded_channel_count(&*peer_state, best_block_height) ==
9051                                                         peer_state.channel_by_id.len()
9052                                                 {
9053                                                         res = Err(());
9054                                                         return NotifyOption::SkipPersistNoEvents;
9055                                                 }
9056
9057                                                 debug_assert!(!peer_state.is_connected, "A peer shouldn't be connected twice");
9058                                                 peer_state.is_connected = true;
9059                                         },
9060                                 }
9061                         }
9062
9063                         log_debug!(logger, "Generating channel_reestablish events for {}", log_pubkey!(counterparty_node_id));
9064
9065                         let per_peer_state = self.per_peer_state.read().unwrap();
9066                         if let Some(peer_state_mutex) = per_peer_state.get(counterparty_node_id) {
9067                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9068                                 let peer_state = &mut *peer_state_lock;
9069                                 let pending_msg_events = &mut peer_state.pending_msg_events;
9070
9071                                 peer_state.channel_by_id.iter_mut().filter_map(|(_, phase)|
9072                                         if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
9073                                 ).for_each(|chan| {
9074                                         let logger = WithChannelContext::from(&self.logger, &chan.context);
9075                                         pending_msg_events.push(events::MessageSendEvent::SendChannelReestablish {
9076                                                 node_id: chan.context.get_counterparty_node_id(),
9077                                                 msg: chan.get_channel_reestablish(&&logger),
9078                                         });
9079                                 });
9080                         }
9081
9082                         return NotifyOption::SkipPersistHandleEvents;
9083                         //TODO: Also re-broadcast announcement_signatures
9084                 });
9085                 res
9086         }
9087
9088         fn handle_error(&self, counterparty_node_id: &PublicKey, msg: &msgs::ErrorMessage) {
9089                 let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9090
9091                 match &msg.data as &str {
9092                         "cannot co-op close channel w/ active htlcs"|
9093                         "link failed to shutdown" =>
9094                         {
9095                                 // LND hasn't properly handled shutdown messages ever, and force-closes any time we
9096                                 // send one while HTLCs are still present. The issue is tracked at
9097                                 // https://github.com/lightningnetwork/lnd/issues/6039 and has had multiple patches
9098                                 // to fix it but none so far have managed to land upstream. The issue appears to be
9099                                 // very low priority for the LND team despite being marked "P1".
9100                                 // We're not going to bother handling this in a sensible way, instead simply
9101                                 // repeating the Shutdown message on repeat until morale improves.
9102                                 if !msg.channel_id.is_zero() {
9103                                         let per_peer_state = self.per_peer_state.read().unwrap();
9104                                         let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9105                                         if peer_state_mutex_opt.is_none() { return; }
9106                                         let mut peer_state = peer_state_mutex_opt.unwrap().lock().unwrap();
9107                                         if let Some(ChannelPhase::Funded(chan)) = peer_state.channel_by_id.get(&msg.channel_id) {
9108                                                 if let Some(msg) = chan.get_outbound_shutdown() {
9109                                                         peer_state.pending_msg_events.push(events::MessageSendEvent::SendShutdown {
9110                                                                 node_id: *counterparty_node_id,
9111                                                                 msg,
9112                                                         });
9113                                                 }
9114                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::HandleError {
9115                                                         node_id: *counterparty_node_id,
9116                                                         action: msgs::ErrorAction::SendWarningMessage {
9117                                                                 msg: msgs::WarningMessage {
9118                                                                         channel_id: msg.channel_id,
9119                                                                         data: "You appear to be exhibiting LND bug 6039, we'll keep sending you shutdown messages until you handle them correctly".to_owned()
9120                                                                 },
9121                                                                 log_level: Level::Trace,
9122                                                         }
9123                                                 });
9124                                         }
9125                                 }
9126                                 return;
9127                         }
9128                         _ => {}
9129                 }
9130
9131                 if msg.channel_id.is_zero() {
9132                         let channel_ids: Vec<ChannelId> = {
9133                                 let per_peer_state = self.per_peer_state.read().unwrap();
9134                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9135                                 if peer_state_mutex_opt.is_none() { return; }
9136                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9137                                 let peer_state = &mut *peer_state_lock;
9138                                 // Note that we don't bother generating any events for pre-accept channels -
9139                                 // they're not considered "channels" yet from the PoV of our events interface.
9140                                 peer_state.inbound_channel_request_by_id.clear();
9141                                 peer_state.channel_by_id.keys().cloned().collect()
9142                         };
9143                         for channel_id in channel_ids {
9144                                 // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9145                                 let _ = self.force_close_channel_with_peer(&channel_id, counterparty_node_id, Some(&msg.data), true);
9146                         }
9147                 } else {
9148                         {
9149                                 // First check if we can advance the channel type and try again.
9150                                 let per_peer_state = self.per_peer_state.read().unwrap();
9151                                 let peer_state_mutex_opt = per_peer_state.get(counterparty_node_id);
9152                                 if peer_state_mutex_opt.is_none() { return; }
9153                                 let mut peer_state_lock = peer_state_mutex_opt.unwrap().lock().unwrap();
9154                                 let peer_state = &mut *peer_state_lock;
9155                                 if let Some(ChannelPhase::UnfundedOutboundV1(chan)) = peer_state.channel_by_id.get_mut(&msg.channel_id) {
9156                                         if let Ok(msg) = chan.maybe_handle_error_without_close(self.chain_hash, &self.fee_estimator) {
9157                                                 peer_state.pending_msg_events.push(events::MessageSendEvent::SendOpenChannel {
9158                                                         node_id: *counterparty_node_id,
9159                                                         msg,
9160                                                 });
9161                                                 return;
9162                                         }
9163                                 }
9164                         }
9165
9166                         // Untrusted messages from peer, we throw away the error if id points to a non-existent channel
9167                         let _ = self.force_close_channel_with_peer(&msg.channel_id, counterparty_node_id, Some(&msg.data), true);
9168                 }
9169         }
9170
9171         fn provided_node_features(&self) -> NodeFeatures {
9172                 provided_node_features(&self.default_configuration)
9173         }
9174
9175         fn provided_init_features(&self, _their_init_features: &PublicKey) -> InitFeatures {
9176                 provided_init_features(&self.default_configuration)
9177         }
9178
9179         fn get_chain_hashes(&self) -> Option<Vec<ChainHash>> {
9180                 Some(vec![self.chain_hash])
9181         }
9182
9183         fn handle_tx_add_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddInput) {
9184                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9185                         "Dual-funded channels not supported".to_owned(),
9186                          msg.channel_id.clone())), *counterparty_node_id);
9187         }
9188
9189         fn handle_tx_add_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAddOutput) {
9190                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9191                         "Dual-funded channels not supported".to_owned(),
9192                          msg.channel_id.clone())), *counterparty_node_id);
9193         }
9194
9195         fn handle_tx_remove_input(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveInput) {
9196                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9197                         "Dual-funded channels not supported".to_owned(),
9198                          msg.channel_id.clone())), *counterparty_node_id);
9199         }
9200
9201         fn handle_tx_remove_output(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxRemoveOutput) {
9202                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9203                         "Dual-funded channels not supported".to_owned(),
9204                          msg.channel_id.clone())), *counterparty_node_id);
9205         }
9206
9207         fn handle_tx_complete(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxComplete) {
9208                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9209                         "Dual-funded channels not supported".to_owned(),
9210                          msg.channel_id.clone())), *counterparty_node_id);
9211         }
9212
9213         fn handle_tx_signatures(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxSignatures) {
9214                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9215                         "Dual-funded channels not supported".to_owned(),
9216                          msg.channel_id.clone())), *counterparty_node_id);
9217         }
9218
9219         fn handle_tx_init_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxInitRbf) {
9220                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9221                         "Dual-funded channels not supported".to_owned(),
9222                          msg.channel_id.clone())), *counterparty_node_id);
9223         }
9224
9225         fn handle_tx_ack_rbf(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAckRbf) {
9226                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9227                         "Dual-funded channels not supported".to_owned(),
9228                          msg.channel_id.clone())), *counterparty_node_id);
9229         }
9230
9231         fn handle_tx_abort(&self, counterparty_node_id: &PublicKey, msg: &msgs::TxAbort) {
9232                 let _: Result<(), _> = handle_error!(self, Err(MsgHandleErrInternal::send_err_msg_no_close(
9233                         "Dual-funded channels not supported".to_owned(),
9234                          msg.channel_id.clone())), *counterparty_node_id);
9235         }
9236 }
9237
9238 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
9239 OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
9240 where
9241         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9242         T::Target: BroadcasterInterface,
9243         ES::Target: EntropySource,
9244         NS::Target: NodeSigner,
9245         SP::Target: SignerProvider,
9246         F::Target: FeeEstimator,
9247         R::Target: Router,
9248         L::Target: Logger,
9249 {
9250         fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
9251                 let secp_ctx = &self.secp_ctx;
9252                 let expanded_key = &self.inbound_payment_key;
9253
9254                 match message {
9255                         OffersMessage::InvoiceRequest(invoice_request) => {
9256                                 let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
9257                                         &invoice_request
9258                                 ) {
9259                                         Ok(amount_msats) => amount_msats,
9260                                         Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
9261                                 };
9262                                 let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
9263                                         Ok(invoice_request) => invoice_request,
9264                                         Err(()) => {
9265                                                 let error = Bolt12SemanticError::InvalidMetadata;
9266                                                 return Some(OffersMessage::InvoiceError(error.into()));
9267                                         },
9268                                 };
9269
9270                                 let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9271                                 let (payment_hash, payment_secret) = match self.create_inbound_payment(
9272                                         Some(amount_msats), relative_expiry, None
9273                                 ) {
9274                                         Ok((payment_hash, payment_secret)) => (payment_hash, payment_secret),
9275                                         Err(()) => {
9276                                                 let error = Bolt12SemanticError::InvalidAmount;
9277                                                 return Some(OffersMessage::InvoiceError(error.into()));
9278                                         },
9279                                 };
9280
9281                                 let payment_paths = match self.create_blinded_payment_paths(
9282                                         amount_msats, payment_secret
9283                                 ) {
9284                                         Ok(payment_paths) => payment_paths,
9285                                         Err(()) => {
9286                                                 let error = Bolt12SemanticError::MissingPaths;
9287                                                 return Some(OffersMessage::InvoiceError(error.into()));
9288                                         },
9289                                 };
9290
9291                                 #[cfg(not(feature = "std"))]
9292                                 let created_at = Duration::from_secs(
9293                                         self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9294                                 );
9295
9296                                 if invoice_request.keys.is_some() {
9297                                         #[cfg(feature = "std")]
9298                                         let builder = invoice_request.respond_using_derived_keys(
9299                                                 payment_paths, payment_hash
9300                                         );
9301                                         #[cfg(not(feature = "std"))]
9302                                         let builder = invoice_request.respond_using_derived_keys_no_std(
9303                                                 payment_paths, payment_hash, created_at
9304                                         );
9305                                         match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
9306                                                 Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
9307                                                 Err(error) => Some(OffersMessage::InvoiceError(error.into())),
9308                                         }
9309                                 } else {
9310                                         #[cfg(feature = "std")]
9311                                         let builder = invoice_request.respond_with(payment_paths, payment_hash);
9312                                         #[cfg(not(feature = "std"))]
9313                                         let builder = invoice_request.respond_with_no_std(
9314                                                 payment_paths, payment_hash, created_at
9315                                         );
9316                                         let response = builder.and_then(|builder| builder.allow_mpp().build())
9317                                                 .map_err(|e| OffersMessage::InvoiceError(e.into()))
9318                                                 .and_then(|invoice|
9319                                                         match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
9320                                                                 Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
9321                                                                 Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
9322                                                                                 InvoiceError::from_string("Failed signing invoice".to_string())
9323                                                                 )),
9324                                                                 Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
9325                                                                                 InvoiceError::from_string("Failed invoice signature verification".to_string())
9326                                                                 )),
9327                                                         });
9328                                         match response {
9329                                                 Ok(invoice) => Some(invoice),
9330                                                 Err(error) => Some(error),
9331                                         }
9332                                 }
9333                         },
9334                         OffersMessage::Invoice(invoice) => {
9335                                 match invoice.verify(expanded_key, secp_ctx) {
9336                                         Err(()) => {
9337                                                 Some(OffersMessage::InvoiceError(InvoiceError::from_string("Unrecognized invoice".to_owned())))
9338                                         },
9339                                         Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
9340                                                 Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
9341                                         },
9342                                         Ok(payment_id) => {
9343                                                 if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
9344                                                         log_trace!(self.logger, "Failed paying invoice: {:?}", e);
9345                                                         Some(OffersMessage::InvoiceError(InvoiceError::from_string(format!("{:?}", e))))
9346                                                 } else {
9347                                                         None
9348                                                 }
9349                                         },
9350                                 }
9351                         },
9352                         OffersMessage::InvoiceError(invoice_error) => {
9353                                 log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
9354                                 None
9355                         },
9356                 }
9357         }
9358
9359         fn release_pending_messages(&self) -> Vec<PendingOnionMessage<OffersMessage>> {
9360                 core::mem::take(&mut self.pending_offers_messages.lock().unwrap())
9361         }
9362 }
9363
9364 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
9365 /// [`ChannelManager`].
9366 pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {
9367         let mut node_features = provided_init_features(config).to_context();
9368         node_features.set_keysend_optional();
9369         node_features
9370 }
9371
9372 /// Fetches the set of [`Bolt11InvoiceFeatures`] flags that are provided by or required by
9373 /// [`ChannelManager`].
9374 ///
9375 /// Note that the invoice feature flags can vary depending on if the invoice is a "phantom invoice"
9376 /// or not. Thus, this method is not public.
9377 #[cfg(any(feature = "_test_utils", test))]
9378 pub(crate) fn provided_bolt11_invoice_features(config: &UserConfig) -> Bolt11InvoiceFeatures {
9379         provided_init_features(config).to_context()
9380 }
9381
9382 /// Fetches the set of [`Bolt12InvoiceFeatures`] flags that are provided by or required by
9383 /// [`ChannelManager`].
9384 pub(crate) fn provided_bolt12_invoice_features(config: &UserConfig) -> Bolt12InvoiceFeatures {
9385         provided_init_features(config).to_context()
9386 }
9387
9388 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
9389 /// [`ChannelManager`].
9390 pub(crate) fn provided_channel_features(config: &UserConfig) -> ChannelFeatures {
9391         provided_init_features(config).to_context()
9392 }
9393
9394 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
9395 /// [`ChannelManager`].
9396 pub(crate) fn provided_channel_type_features(config: &UserConfig) -> ChannelTypeFeatures {
9397         ChannelTypeFeatures::from_init(&provided_init_features(config))
9398 }
9399
9400 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
9401 /// [`ChannelManager`].
9402 pub fn provided_init_features(config: &UserConfig) -> InitFeatures {
9403         // Note that if new features are added here which other peers may (eventually) require, we
9404         // should also add the corresponding (optional) bit to the [`ChannelMessageHandler`] impl for
9405         // [`ErroringMessageHandler`].
9406         let mut features = InitFeatures::empty();
9407         features.set_data_loss_protect_required();
9408         features.set_upfront_shutdown_script_optional();
9409         features.set_variable_length_onion_required();
9410         features.set_static_remote_key_required();
9411         features.set_payment_secret_required();
9412         features.set_basic_mpp_optional();
9413         features.set_wumbo_optional();
9414         features.set_shutdown_any_segwit_optional();
9415         features.set_channel_type_optional();
9416         features.set_scid_privacy_optional();
9417         features.set_zero_conf_optional();
9418         features.set_route_blinding_optional();
9419         if config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx {
9420                 features.set_anchors_zero_fee_htlc_tx_optional();
9421         }
9422         features
9423 }
9424
9425 const SERIALIZATION_VERSION: u8 = 1;
9426 const MIN_SERIALIZATION_VERSION: u8 = 1;
9427
9428 impl_writeable_tlv_based!(CounterpartyForwardingInfo, {
9429         (2, fee_base_msat, required),
9430         (4, fee_proportional_millionths, required),
9431         (6, cltv_expiry_delta, required),
9432 });
9433
9434 impl_writeable_tlv_based!(ChannelCounterparty, {
9435         (2, node_id, required),
9436         (4, features, required),
9437         (6, unspendable_punishment_reserve, required),
9438         (8, forwarding_info, option),
9439         (9, outbound_htlc_minimum_msat, option),
9440         (11, outbound_htlc_maximum_msat, option),
9441 });
9442
9443 impl Writeable for ChannelDetails {
9444         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9445                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9446                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9447                 let user_channel_id_low = self.user_channel_id as u64;
9448                 let user_channel_id_high_opt = Some((self.user_channel_id >> 64) as u64);
9449                 write_tlv_fields!(writer, {
9450                         (1, self.inbound_scid_alias, option),
9451                         (2, self.channel_id, required),
9452                         (3, self.channel_type, option),
9453                         (4, self.counterparty, required),
9454                         (5, self.outbound_scid_alias, option),
9455                         (6, self.funding_txo, option),
9456                         (7, self.config, option),
9457                         (8, self.short_channel_id, option),
9458                         (9, self.confirmations, option),
9459                         (10, self.channel_value_satoshis, required),
9460                         (12, self.unspendable_punishment_reserve, option),
9461                         (14, user_channel_id_low, required),
9462                         (16, self.balance_msat, required),
9463                         (18, self.outbound_capacity_msat, required),
9464                         (19, self.next_outbound_htlc_limit_msat, required),
9465                         (20, self.inbound_capacity_msat, required),
9466                         (21, self.next_outbound_htlc_minimum_msat, required),
9467                         (22, self.confirmations_required, option),
9468                         (24, self.force_close_spend_delay, option),
9469                         (26, self.is_outbound, required),
9470                         (28, self.is_channel_ready, required),
9471                         (30, self.is_usable, required),
9472                         (32, self.is_public, required),
9473                         (33, self.inbound_htlc_minimum_msat, option),
9474                         (35, self.inbound_htlc_maximum_msat, option),
9475                         (37, user_channel_id_high_opt, option),
9476                         (39, self.feerate_sat_per_1000_weight, option),
9477                         (41, self.channel_shutdown_state, option),
9478                 });
9479                 Ok(())
9480         }
9481 }
9482
9483 impl Readable for ChannelDetails {
9484         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9485                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9486                         (1, inbound_scid_alias, option),
9487                         (2, channel_id, required),
9488                         (3, channel_type, option),
9489                         (4, counterparty, required),
9490                         (5, outbound_scid_alias, option),
9491                         (6, funding_txo, option),
9492                         (7, config, option),
9493                         (8, short_channel_id, option),
9494                         (9, confirmations, option),
9495                         (10, channel_value_satoshis, required),
9496                         (12, unspendable_punishment_reserve, option),
9497                         (14, user_channel_id_low, required),
9498                         (16, balance_msat, required),
9499                         (18, outbound_capacity_msat, required),
9500                         // Note that by the time we get past the required read above, outbound_capacity_msat will be
9501                         // filled in, so we can safely unwrap it here.
9502                         (19, next_outbound_htlc_limit_msat, (default_value, outbound_capacity_msat.0.unwrap() as u64)),
9503                         (20, inbound_capacity_msat, required),
9504                         (21, next_outbound_htlc_minimum_msat, (default_value, 0)),
9505                         (22, confirmations_required, option),
9506                         (24, force_close_spend_delay, option),
9507                         (26, is_outbound, required),
9508                         (28, is_channel_ready, required),
9509                         (30, is_usable, required),
9510                         (32, is_public, required),
9511                         (33, inbound_htlc_minimum_msat, option),
9512                         (35, inbound_htlc_maximum_msat, option),
9513                         (37, user_channel_id_high_opt, option),
9514                         (39, feerate_sat_per_1000_weight, option),
9515                         (41, channel_shutdown_state, option),
9516                 });
9517
9518                 // `user_channel_id` used to be a single u64 value. In order to remain backwards compatible with
9519                 // versions prior to 0.0.113, the u128 is serialized as two separate u64 values.
9520                 let user_channel_id_low: u64 = user_channel_id_low.0.unwrap();
9521                 let user_channel_id = user_channel_id_low as u128 +
9522                         ((user_channel_id_high_opt.unwrap_or(0 as u64) as u128) << 64);
9523
9524                 Ok(Self {
9525                         inbound_scid_alias,
9526                         channel_id: channel_id.0.unwrap(),
9527                         channel_type,
9528                         counterparty: counterparty.0.unwrap(),
9529                         outbound_scid_alias,
9530                         funding_txo,
9531                         config,
9532                         short_channel_id,
9533                         channel_value_satoshis: channel_value_satoshis.0.unwrap(),
9534                         unspendable_punishment_reserve,
9535                         user_channel_id,
9536                         balance_msat: balance_msat.0.unwrap(),
9537                         outbound_capacity_msat: outbound_capacity_msat.0.unwrap(),
9538                         next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat.0.unwrap(),
9539                         next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat.0.unwrap(),
9540                         inbound_capacity_msat: inbound_capacity_msat.0.unwrap(),
9541                         confirmations_required,
9542                         confirmations,
9543                         force_close_spend_delay,
9544                         is_outbound: is_outbound.0.unwrap(),
9545                         is_channel_ready: is_channel_ready.0.unwrap(),
9546                         is_usable: is_usable.0.unwrap(),
9547                         is_public: is_public.0.unwrap(),
9548                         inbound_htlc_minimum_msat,
9549                         inbound_htlc_maximum_msat,
9550                         feerate_sat_per_1000_weight,
9551                         channel_shutdown_state,
9552                 })
9553         }
9554 }
9555
9556 impl_writeable_tlv_based!(PhantomRouteHints, {
9557         (2, channels, required_vec),
9558         (4, phantom_scid, required),
9559         (6, real_node_pubkey, required),
9560 });
9561
9562 impl_writeable_tlv_based!(BlindedForward, {
9563         (0, inbound_blinding_point, required),
9564         (1, failure, (default_value, BlindedFailure::FromIntroductionNode)),
9565 });
9566
9567 impl_writeable_tlv_based_enum!(PendingHTLCRouting,
9568         (0, Forward) => {
9569                 (0, onion_packet, required),
9570                 (1, blinded, option),
9571                 (2, short_channel_id, required),
9572         },
9573         (1, Receive) => {
9574                 (0, payment_data, required),
9575                 (1, phantom_shared_secret, option),
9576                 (2, incoming_cltv_expiry, required),
9577                 (3, payment_metadata, option),
9578                 (5, custom_tlvs, optional_vec),
9579                 (7, requires_blinded_error, (default_value, false)),
9580         },
9581         (2, ReceiveKeysend) => {
9582                 (0, payment_preimage, required),
9583                 (2, incoming_cltv_expiry, required),
9584                 (3, payment_metadata, option),
9585                 (4, payment_data, option), // Added in 0.0.116
9586                 (5, custom_tlvs, optional_vec),
9587         },
9588 ;);
9589
9590 impl_writeable_tlv_based!(PendingHTLCInfo, {
9591         (0, routing, required),
9592         (2, incoming_shared_secret, required),
9593         (4, payment_hash, required),
9594         (6, outgoing_amt_msat, required),
9595         (8, outgoing_cltv_value, required),
9596         (9, incoming_amt_msat, option),
9597         (10, skimmed_fee_msat, option),
9598 });
9599
9600
9601 impl Writeable for HTLCFailureMsg {
9602         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9603                 match self {
9604                         HTLCFailureMsg::Relay(msgs::UpdateFailHTLC { channel_id, htlc_id, reason }) => {
9605                                 0u8.write(writer)?;
9606                                 channel_id.write(writer)?;
9607                                 htlc_id.write(writer)?;
9608                                 reason.write(writer)?;
9609                         },
9610                         HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9611                                 channel_id, htlc_id, sha256_of_onion, failure_code
9612                         }) => {
9613                                 1u8.write(writer)?;
9614                                 channel_id.write(writer)?;
9615                                 htlc_id.write(writer)?;
9616                                 sha256_of_onion.write(writer)?;
9617                                 failure_code.write(writer)?;
9618                         },
9619                 }
9620                 Ok(())
9621         }
9622 }
9623
9624 impl Readable for HTLCFailureMsg {
9625         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9626                 let id: u8 = Readable::read(reader)?;
9627                 match id {
9628                         0 => {
9629                                 Ok(HTLCFailureMsg::Relay(msgs::UpdateFailHTLC {
9630                                         channel_id: Readable::read(reader)?,
9631                                         htlc_id: Readable::read(reader)?,
9632                                         reason: Readable::read(reader)?,
9633                                 }))
9634                         },
9635                         1 => {
9636                                 Ok(HTLCFailureMsg::Malformed(msgs::UpdateFailMalformedHTLC {
9637                                         channel_id: Readable::read(reader)?,
9638                                         htlc_id: Readable::read(reader)?,
9639                                         sha256_of_onion: Readable::read(reader)?,
9640                                         failure_code: Readable::read(reader)?,
9641                                 }))
9642                         },
9643                         // In versions prior to 0.0.101, HTLCFailureMsg objects were written with type 0 or 1 but
9644                         // weren't length-prefixed and thus didn't support reading the TLV stream suffix of the network
9645                         // messages contained in the variants.
9646                         // In version 0.0.101, support for reading the variants with these types was added, and
9647                         // we should migrate to writing these variants when UpdateFailHTLC or
9648                         // UpdateFailMalformedHTLC get TLV fields.
9649                         2 => {
9650                                 let length: BigSize = Readable::read(reader)?;
9651                                 let mut s = FixedLengthReader::new(reader, length.0);
9652                                 let res = Readable::read(&mut s)?;
9653                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9654                                 Ok(HTLCFailureMsg::Relay(res))
9655                         },
9656                         3 => {
9657                                 let length: BigSize = Readable::read(reader)?;
9658                                 let mut s = FixedLengthReader::new(reader, length.0);
9659                                 let res = Readable::read(&mut s)?;
9660                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
9661                                 Ok(HTLCFailureMsg::Malformed(res))
9662                         },
9663                         _ => Err(DecodeError::UnknownRequiredFeature),
9664                 }
9665         }
9666 }
9667
9668 impl_writeable_tlv_based_enum!(PendingHTLCStatus, ;
9669         (0, Forward),
9670         (1, Fail),
9671 );
9672
9673 impl_writeable_tlv_based_enum!(BlindedFailure,
9674         (0, FromIntroductionNode) => {},
9675         (2, FromBlindedNode) => {}, ;
9676 );
9677
9678 impl_writeable_tlv_based!(HTLCPreviousHopData, {
9679         (0, short_channel_id, required),
9680         (1, phantom_shared_secret, option),
9681         (2, outpoint, required),
9682         (3, blinded_failure, option),
9683         (4, htlc_id, required),
9684         (6, incoming_packet_shared_secret, required),
9685         (7, user_channel_id, option),
9686         // Note that by the time we get past the required read for type 2 above, outpoint will be
9687         // filled in, so we can safely unwrap it here.
9688         (9, channel_id, (default_value, ChannelId::v1_from_funding_outpoint(outpoint.0.unwrap()))),
9689 });
9690
9691 impl Writeable for ClaimableHTLC {
9692         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9693                 let (payment_data, keysend_preimage) = match &self.onion_payload {
9694                         OnionPayload::Invoice { _legacy_hop_data } => (_legacy_hop_data.as_ref(), None),
9695                         OnionPayload::Spontaneous(preimage) => (None, Some(preimage)),
9696                 };
9697                 write_tlv_fields!(writer, {
9698                         (0, self.prev_hop, required),
9699                         (1, self.total_msat, required),
9700                         (2, self.value, required),
9701                         (3, self.sender_intended_value, required),
9702                         (4, payment_data, option),
9703                         (5, self.total_value_received, option),
9704                         (6, self.cltv_expiry, required),
9705                         (8, keysend_preimage, option),
9706                         (10, self.counterparty_skimmed_fee_msat, option),
9707                 });
9708                 Ok(())
9709         }
9710 }
9711
9712 impl Readable for ClaimableHTLC {
9713         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9714                 _init_and_read_len_prefixed_tlv_fields!(reader, {
9715                         (0, prev_hop, required),
9716                         (1, total_msat, option),
9717                         (2, value_ser, required),
9718                         (3, sender_intended_value, option),
9719                         (4, payment_data_opt, option),
9720                         (5, total_value_received, option),
9721                         (6, cltv_expiry, required),
9722                         (8, keysend_preimage, option),
9723                         (10, counterparty_skimmed_fee_msat, option),
9724                 });
9725                 let payment_data: Option<msgs::FinalOnionHopData> = payment_data_opt;
9726                 let value = value_ser.0.unwrap();
9727                 let onion_payload = match keysend_preimage {
9728                         Some(p) => {
9729                                 if payment_data.is_some() {
9730                                         return Err(DecodeError::InvalidValue)
9731                                 }
9732                                 if total_msat.is_none() {
9733                                         total_msat = Some(value);
9734                                 }
9735                                 OnionPayload::Spontaneous(p)
9736                         },
9737                         None => {
9738                                 if total_msat.is_none() {
9739                                         if payment_data.is_none() {
9740                                                 return Err(DecodeError::InvalidValue)
9741                                         }
9742                                         total_msat = Some(payment_data.as_ref().unwrap().total_msat);
9743                                 }
9744                                 OnionPayload::Invoice { _legacy_hop_data: payment_data }
9745                         },
9746                 };
9747                 Ok(Self {
9748                         prev_hop: prev_hop.0.unwrap(),
9749                         timer_ticks: 0,
9750                         value,
9751                         sender_intended_value: sender_intended_value.unwrap_or(value),
9752                         total_value_received,
9753                         total_msat: total_msat.unwrap(),
9754                         onion_payload,
9755                         cltv_expiry: cltv_expiry.0.unwrap(),
9756                         counterparty_skimmed_fee_msat,
9757                 })
9758         }
9759 }
9760
9761 impl Readable for HTLCSource {
9762         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
9763                 let id: u8 = Readable::read(reader)?;
9764                 match id {
9765                         0 => {
9766                                 let mut session_priv: crate::util::ser::RequiredWrapper<SecretKey> = crate::util::ser::RequiredWrapper(None);
9767                                 let mut first_hop_htlc_msat: u64 = 0;
9768                                 let mut path_hops = Vec::new();
9769                                 let mut payment_id = None;
9770                                 let mut payment_params: Option<PaymentParameters> = None;
9771                                 let mut blinded_tail: Option<BlindedTail> = None;
9772                                 read_tlv_fields!(reader, {
9773                                         (0, session_priv, required),
9774                                         (1, payment_id, option),
9775                                         (2, first_hop_htlc_msat, required),
9776                                         (4, path_hops, required_vec),
9777                                         (5, payment_params, (option: ReadableArgs, 0)),
9778                                         (6, blinded_tail, option),
9779                                 });
9780                                 if payment_id.is_none() {
9781                                         // For backwards compat, if there was no payment_id written, use the session_priv bytes
9782                                         // instead.
9783                                         payment_id = Some(PaymentId(*session_priv.0.unwrap().as_ref()));
9784                                 }
9785                                 let path = Path { hops: path_hops, blinded_tail };
9786                                 if path.hops.len() == 0 {
9787                                         return Err(DecodeError::InvalidValue);
9788                                 }
9789                                 if let Some(params) = payment_params.as_mut() {
9790                                         if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = params.payee {
9791                                                 if final_cltv_expiry_delta == &0 {
9792                                                         *final_cltv_expiry_delta = path.final_cltv_expiry_delta().ok_or(DecodeError::InvalidValue)?;
9793                                                 }
9794                                         }
9795                                 }
9796                                 Ok(HTLCSource::OutboundRoute {
9797                                         session_priv: session_priv.0.unwrap(),
9798                                         first_hop_htlc_msat,
9799                                         path,
9800                                         payment_id: payment_id.unwrap(),
9801                                 })
9802                         }
9803                         1 => Ok(HTLCSource::PreviousHopData(Readable::read(reader)?)),
9804                         _ => Err(DecodeError::UnknownRequiredFeature),
9805                 }
9806         }
9807 }
9808
9809 impl Writeable for HTLCSource {
9810         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), crate::io::Error> {
9811                 match self {
9812                         HTLCSource::OutboundRoute { ref session_priv, ref first_hop_htlc_msat, ref path, payment_id } => {
9813                                 0u8.write(writer)?;
9814                                 let payment_id_opt = Some(payment_id);
9815                                 write_tlv_fields!(writer, {
9816                                         (0, session_priv, required),
9817                                         (1, payment_id_opt, option),
9818                                         (2, first_hop_htlc_msat, required),
9819                                         // 3 was previously used to write a PaymentSecret for the payment.
9820                                         (4, path.hops, required_vec),
9821                                         (5, None::<PaymentParameters>, option), // payment_params in LDK versions prior to 0.0.115
9822                                         (6, path.blinded_tail, option),
9823                                  });
9824                         }
9825                         HTLCSource::PreviousHopData(ref field) => {
9826                                 1u8.write(writer)?;
9827                                 field.write(writer)?;
9828                         }
9829                 }
9830                 Ok(())
9831         }
9832 }
9833
9834 impl_writeable_tlv_based!(PendingAddHTLCInfo, {
9835         (0, forward_info, required),
9836         (1, prev_user_channel_id, (default_value, 0)),
9837         (2, prev_short_channel_id, required),
9838         (4, prev_htlc_id, required),
9839         (6, prev_funding_outpoint, required),
9840         // Note that by the time we get past the required read for type 2 above, prev_funding_outpoint will be
9841         // filled in, so we can safely unwrap it here.
9842         (7, prev_channel_id, (default_value, ChannelId::v1_from_funding_outpoint(prev_funding_outpoint.0.unwrap()))),
9843 });
9844
9845 impl Writeable for HTLCForwardInfo {
9846         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
9847                 const FAIL_HTLC_VARIANT_ID: u8 = 1;
9848                 match self {
9849                         Self::AddHTLC(info) => {
9850                                 0u8.write(w)?;
9851                                 info.write(w)?;
9852                         },
9853                         Self::FailHTLC { htlc_id, err_packet } => {
9854                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9855                                 write_tlv_fields!(w, {
9856                                         (0, htlc_id, required),
9857                                         (2, err_packet, required),
9858                                 });
9859                         },
9860                         Self::FailMalformedHTLC { htlc_id, failure_code, sha256_of_onion } => {
9861                                 // Since this variant was added in 0.0.119, write this as `::FailHTLC` with an empty error
9862                                 // packet so older versions have something to fail back with, but serialize the real data as
9863                                 // optional TLVs for the benefit of newer versions.
9864                                 FAIL_HTLC_VARIANT_ID.write(w)?;
9865                                 let dummy_err_packet = msgs::OnionErrorPacket { data: Vec::new() };
9866                                 write_tlv_fields!(w, {
9867                                         (0, htlc_id, required),
9868                                         (1, failure_code, required),
9869                                         (2, dummy_err_packet, required),
9870                                         (3, sha256_of_onion, required),
9871                                 });
9872                         },
9873                 }
9874                 Ok(())
9875         }
9876 }
9877
9878 impl Readable for HTLCForwardInfo {
9879         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
9880                 let id: u8 = Readable::read(r)?;
9881                 Ok(match id {
9882                         0 => Self::AddHTLC(Readable::read(r)?),
9883                         1 => {
9884                                 _init_and_read_len_prefixed_tlv_fields!(r, {
9885                                         (0, htlc_id, required),
9886                                         (1, malformed_htlc_failure_code, option),
9887                                         (2, err_packet, required),
9888                                         (3, sha256_of_onion, option),
9889                                 });
9890                                 if let Some(failure_code) = malformed_htlc_failure_code {
9891                                         Self::FailMalformedHTLC {
9892                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
9893                                                 failure_code,
9894                                                 sha256_of_onion: sha256_of_onion.ok_or(DecodeError::InvalidValue)?,
9895                                         }
9896                                 } else {
9897                                         Self::FailHTLC {
9898                                                 htlc_id: _init_tlv_based_struct_field!(htlc_id, required),
9899                                                 err_packet: _init_tlv_based_struct_field!(err_packet, required),
9900                                         }
9901                                 }
9902                         },
9903                         _ => return Err(DecodeError::InvalidValue),
9904                 })
9905         }
9906 }
9907
9908 impl_writeable_tlv_based!(PendingInboundPayment, {
9909         (0, payment_secret, required),
9910         (2, expiry_time, required),
9911         (4, user_payment_id, required),
9912         (6, payment_preimage, required),
9913         (8, min_value_msat, required),
9914 });
9915
9916 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>
9917 where
9918         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
9919         T::Target: BroadcasterInterface,
9920         ES::Target: EntropySource,
9921         NS::Target: NodeSigner,
9922         SP::Target: SignerProvider,
9923         F::Target: FeeEstimator,
9924         R::Target: Router,
9925         L::Target: Logger,
9926 {
9927         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
9928                 let _consistency_lock = self.total_consistency_lock.write().unwrap();
9929
9930                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
9931
9932                 self.chain_hash.write(writer)?;
9933                 {
9934                         let best_block = self.best_block.read().unwrap();
9935                         best_block.height().write(writer)?;
9936                         best_block.block_hash().write(writer)?;
9937                 }
9938
9939                 let mut serializable_peer_count: u64 = 0;
9940                 {
9941                         let per_peer_state = self.per_peer_state.read().unwrap();
9942                         let mut number_of_funded_channels = 0;
9943                         for (_, peer_state_mutex) in per_peer_state.iter() {
9944                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9945                                 let peer_state = &mut *peer_state_lock;
9946                                 if !peer_state.ok_to_remove(false) {
9947                                         serializable_peer_count += 1;
9948                                 }
9949
9950                                 number_of_funded_channels += peer_state.channel_by_id.iter().filter(
9951                                         |(_, phase)| if let ChannelPhase::Funded(chan) = phase { chan.context.is_funding_broadcast() } else { false }
9952                                 ).count();
9953                         }
9954
9955                         (number_of_funded_channels as u64).write(writer)?;
9956
9957                         for (_, peer_state_mutex) in per_peer_state.iter() {
9958                                 let mut peer_state_lock = peer_state_mutex.lock().unwrap();
9959                                 let peer_state = &mut *peer_state_lock;
9960                                 for channel in peer_state.channel_by_id.iter().filter_map(
9961                                         |(_, phase)| if let ChannelPhase::Funded(channel) = phase {
9962                                                 if channel.context.is_funding_broadcast() { Some(channel) } else { None }
9963                                         } else { None }
9964                                 ) {
9965                                         channel.write(writer)?;
9966                                 }
9967                         }
9968                 }
9969
9970                 {
9971                         let forward_htlcs = self.forward_htlcs.lock().unwrap();
9972                         (forward_htlcs.len() as u64).write(writer)?;
9973                         for (short_channel_id, pending_forwards) in forward_htlcs.iter() {
9974                                 short_channel_id.write(writer)?;
9975                                 (pending_forwards.len() as u64).write(writer)?;
9976                                 for forward in pending_forwards {
9977                                         forward.write(writer)?;
9978                                 }
9979                         }
9980                 }
9981
9982                 let per_peer_state = self.per_peer_state.write().unwrap();
9983
9984                 let pending_inbound_payments = self.pending_inbound_payments.lock().unwrap();
9985                 let claimable_payments = self.claimable_payments.lock().unwrap();
9986                 let pending_outbound_payments = self.pending_outbound_payments.pending_outbound_payments.lock().unwrap();
9987
9988                 let mut htlc_purposes: Vec<&events::PaymentPurpose> = Vec::new();
9989                 let mut htlc_onion_fields: Vec<&_> = Vec::new();
9990                 (claimable_payments.claimable_payments.len() as u64).write(writer)?;
9991                 for (payment_hash, payment) in claimable_payments.claimable_payments.iter() {
9992                         payment_hash.write(writer)?;
9993                         (payment.htlcs.len() as u64).write(writer)?;
9994                         for htlc in payment.htlcs.iter() {
9995                                 htlc.write(writer)?;
9996                         }
9997                         htlc_purposes.push(&payment.purpose);
9998                         htlc_onion_fields.push(&payment.onion_fields);
9999                 }
10000
10001                 let mut monitor_update_blocked_actions_per_peer = None;
10002                 let mut peer_states = Vec::new();
10003                 for (_, peer_state_mutex) in per_peer_state.iter() {
10004                         // Because we're holding the owning `per_peer_state` write lock here there's no chance
10005                         // of a lockorder violation deadlock - no other thread can be holding any
10006                         // per_peer_state lock at all.
10007                         peer_states.push(peer_state_mutex.unsafe_well_ordered_double_lock_self());
10008                 }
10009
10010                 (serializable_peer_count).write(writer)?;
10011                 for ((peer_pubkey, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
10012                         // Peers which we have no channels to should be dropped once disconnected. As we
10013                         // disconnect all peers when shutting down and serializing the ChannelManager, we
10014                         // consider all peers as disconnected here. There's therefore no need write peers with
10015                         // no channels.
10016                         if !peer_state.ok_to_remove(false) {
10017                                 peer_pubkey.write(writer)?;
10018                                 peer_state.latest_features.write(writer)?;
10019                                 if !peer_state.monitor_update_blocked_actions.is_empty() {
10020                                         monitor_update_blocked_actions_per_peer
10021                                                 .get_or_insert_with(Vec::new)
10022                                                 .push((*peer_pubkey, &peer_state.monitor_update_blocked_actions));
10023                                 }
10024                         }
10025                 }
10026
10027                 let events = self.pending_events.lock().unwrap();
10028                 // LDK versions prior to 0.0.115 don't support post-event actions, thus if there's no
10029                 // actions at all, skip writing the required TLV. Otherwise, pre-0.0.115 versions will
10030                 // refuse to read the new ChannelManager.
10031                 let events_not_backwards_compatible = events.iter().any(|(_, action)| action.is_some());
10032                 if events_not_backwards_compatible {
10033                         // If we're gonna write a even TLV that will overwrite our events anyway we might as
10034                         // well save the space and not write any events here.
10035                         0u64.write(writer)?;
10036                 } else {
10037                         (events.len() as u64).write(writer)?;
10038                         for (event, _) in events.iter() {
10039                                 event.write(writer)?;
10040                         }
10041                 }
10042
10043                 // LDK versions prior to 0.0.116 wrote the `pending_background_events`
10044                 // `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
10045                 // the closing monitor updates were always effectively replayed on startup (either directly
10046                 // by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
10047                 // deserialization or, in 0.0.115, by regenerating the monitor update itself).
10048                 0u64.write(writer)?;
10049
10050                 // Prior to 0.0.111 we tracked node_announcement serials here, however that now happens in
10051                 // `PeerManager`, and thus we simply write the `highest_seen_timestamp` twice, which is
10052                 // likely to be identical.
10053                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10054                 (self.highest_seen_timestamp.load(Ordering::Acquire) as u32).write(writer)?;
10055
10056                 (pending_inbound_payments.len() as u64).write(writer)?;
10057                 for (hash, pending_payment) in pending_inbound_payments.iter() {
10058                         hash.write(writer)?;
10059                         pending_payment.write(writer)?;
10060                 }
10061
10062                 // For backwards compat, write the session privs and their total length.
10063                 let mut num_pending_outbounds_compat: u64 = 0;
10064                 for (_, outbound) in pending_outbound_payments.iter() {
10065                         if !outbound.is_fulfilled() && !outbound.abandoned() {
10066                                 num_pending_outbounds_compat += outbound.remaining_parts() as u64;
10067                         }
10068                 }
10069                 num_pending_outbounds_compat.write(writer)?;
10070                 for (_, outbound) in pending_outbound_payments.iter() {
10071                         match outbound {
10072                                 PendingOutboundPayment::Legacy { session_privs } |
10073                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10074                                         for session_priv in session_privs.iter() {
10075                                                 session_priv.write(writer)?;
10076                                         }
10077                                 }
10078                                 PendingOutboundPayment::AwaitingInvoice { .. } => {},
10079                                 PendingOutboundPayment::InvoiceReceived { .. } => {},
10080                                 PendingOutboundPayment::Fulfilled { .. } => {},
10081                                 PendingOutboundPayment::Abandoned { .. } => {},
10082                         }
10083                 }
10084
10085                 // Encode without retry info for 0.0.101 compatibility.
10086                 let mut pending_outbound_payments_no_retry: HashMap<PaymentId, HashSet<[u8; 32]>> = HashMap::new();
10087                 for (id, outbound) in pending_outbound_payments.iter() {
10088                         match outbound {
10089                                 PendingOutboundPayment::Legacy { session_privs } |
10090                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
10091                                         pending_outbound_payments_no_retry.insert(*id, session_privs.clone());
10092                                 },
10093                                 _ => {},
10094                         }
10095                 }
10096
10097                 let mut pending_intercepted_htlcs = None;
10098                 let our_pending_intercepts = self.pending_intercepted_htlcs.lock().unwrap();
10099                 if our_pending_intercepts.len() != 0 {
10100                         pending_intercepted_htlcs = Some(our_pending_intercepts);
10101                 }
10102
10103                 let mut pending_claiming_payments = Some(&claimable_payments.pending_claiming_payments);
10104                 if pending_claiming_payments.as_ref().unwrap().is_empty() {
10105                         // LDK versions prior to 0.0.113 do not know how to read the pending claimed payments
10106                         // map. Thus, if there are no entries we skip writing a TLV for it.
10107                         pending_claiming_payments = None;
10108                 }
10109
10110                 let mut in_flight_monitor_updates: Option<HashMap<(&PublicKey, &OutPoint), &Vec<ChannelMonitorUpdate>>> = None;
10111                 for ((counterparty_id, _), peer_state) in per_peer_state.iter().zip(peer_states.iter()) {
10112                         for (funding_outpoint, updates) in peer_state.in_flight_monitor_updates.iter() {
10113                                 if !updates.is_empty() {
10114                                         if in_flight_monitor_updates.is_none() { in_flight_monitor_updates = Some(HashMap::new()); }
10115                                         in_flight_monitor_updates.as_mut().unwrap().insert((counterparty_id, funding_outpoint), updates);
10116                                 }
10117                         }
10118                 }
10119
10120                 write_tlv_fields!(writer, {
10121                         (1, pending_outbound_payments_no_retry, required),
10122                         (2, pending_intercepted_htlcs, option),
10123                         (3, pending_outbound_payments, required),
10124                         (4, pending_claiming_payments, option),
10125                         (5, self.our_network_pubkey, required),
10126                         (6, monitor_update_blocked_actions_per_peer, option),
10127                         (7, self.fake_scid_rand_bytes, required),
10128                         (8, if events_not_backwards_compatible { Some(&*events) } else { None }, option),
10129                         (9, htlc_purposes, required_vec),
10130                         (10, in_flight_monitor_updates, option),
10131                         (11, self.probing_cookie_secret, required),
10132                         (13, htlc_onion_fields, optional_vec),
10133                 });
10134
10135                 Ok(())
10136         }
10137 }
10138
10139 impl Writeable for VecDeque<(Event, Option<EventCompletionAction>)> {
10140         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
10141                 (self.len() as u64).write(w)?;
10142                 for (event, action) in self.iter() {
10143                         event.write(w)?;
10144                         action.write(w)?;
10145                         #[cfg(debug_assertions)] {
10146                                 // Events are MaybeReadable, in some cases indicating that they shouldn't actually
10147                                 // be persisted and are regenerated on restart. However, if such an event has a
10148                                 // post-event-handling action we'll write nothing for the event and would have to
10149                                 // either forget the action or fail on deserialization (which we do below). Thus,
10150                                 // check that the event is sane here.
10151                                 let event_encoded = event.encode();
10152                                 let event_read: Option<Event> =
10153                                         MaybeReadable::read(&mut &event_encoded[..]).unwrap();
10154                                 if action.is_some() { assert!(event_read.is_some()); }
10155                         }
10156                 }
10157                 Ok(())
10158         }
10159 }
10160 impl Readable for VecDeque<(Event, Option<EventCompletionAction>)> {
10161         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
10162                 let len: u64 = Readable::read(reader)?;
10163                 const MAX_ALLOC_SIZE: u64 = 1024 * 16;
10164                 let mut events: Self = VecDeque::with_capacity(cmp::min(
10165                         MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>() as u64,
10166                         len) as usize);
10167                 for _ in 0..len {
10168                         let ev_opt = MaybeReadable::read(reader)?;
10169                         let action = Readable::read(reader)?;
10170                         if let Some(ev) = ev_opt {
10171                                 events.push_back((ev, action));
10172                         } else if action.is_some() {
10173                                 return Err(DecodeError::InvalidValue);
10174                         }
10175                 }
10176                 Ok(events)
10177         }
10178 }
10179
10180 impl_writeable_tlv_based_enum!(ChannelShutdownState,
10181         (0, NotShuttingDown) => {},
10182         (2, ShutdownInitiated) => {},
10183         (4, ResolvingHTLCs) => {},
10184         (6, NegotiatingClosingFee) => {},
10185         (8, ShutdownComplete) => {}, ;
10186 );
10187
10188 /// Arguments for the creation of a ChannelManager that are not deserialized.
10189 ///
10190 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
10191 /// is:
10192 /// 1) Deserialize all stored [`ChannelMonitor`]s.
10193 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
10194 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
10195 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
10196 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
10197 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
10198 ///    same way you would handle a [`chain::Filter`] call using
10199 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
10200 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
10201 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
10202 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
10203 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
10204 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
10205 ///    the next step.
10206 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
10207 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
10208 ///
10209 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
10210 /// call any other methods on the newly-deserialized [`ChannelManager`].
10211 ///
10212 /// Note that because some channels may be closed during deserialization, it is critical that you
10213 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
10214 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
10215 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
10216 /// not force-close the same channels but consider them live), you may end up revoking a state for
10217 /// which you've already broadcasted the transaction.
10218 ///
10219 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
10220 pub struct ChannelManagerReadArgs<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10221 where
10222         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10223         T::Target: BroadcasterInterface,
10224         ES::Target: EntropySource,
10225         NS::Target: NodeSigner,
10226         SP::Target: SignerProvider,
10227         F::Target: FeeEstimator,
10228         R::Target: Router,
10229         L::Target: Logger,
10230 {
10231         /// A cryptographically secure source of entropy.
10232         pub entropy_source: ES,
10233
10234         /// A signer that is able to perform node-scoped cryptographic operations.
10235         pub node_signer: NS,
10236
10237         /// The keys provider which will give us relevant keys. Some keys will be loaded during
10238         /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
10239         /// signing data.
10240         pub signer_provider: SP,
10241
10242         /// The fee_estimator for use in the ChannelManager in the future.
10243         ///
10244         /// No calls to the FeeEstimator will be made during deserialization.
10245         pub fee_estimator: F,
10246         /// The chain::Watch for use in the ChannelManager in the future.
10247         ///
10248         /// No calls to the chain::Watch will be made during deserialization. It is assumed that
10249         /// you have deserialized ChannelMonitors separately and will add them to your
10250         /// chain::Watch after deserializing this ChannelManager.
10251         pub chain_monitor: M,
10252
10253         /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
10254         /// used to broadcast the latest local commitment transactions of channels which must be
10255         /// force-closed during deserialization.
10256         pub tx_broadcaster: T,
10257         /// The router which will be used in the ChannelManager in the future for finding routes
10258         /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
10259         ///
10260         /// No calls to the router will be made during deserialization.
10261         pub router: R,
10262         /// The Logger for use in the ChannelManager and which may be used to log information during
10263         /// deserialization.
10264         pub logger: L,
10265         /// Default settings used for new channels. Any existing channels will continue to use the
10266         /// runtime settings which were stored when the ChannelManager was serialized.
10267         pub default_config: UserConfig,
10268
10269         /// A map from channel funding outpoints to ChannelMonitors for those channels (ie
10270         /// value.context.get_funding_txo() should be the key).
10271         ///
10272         /// If a monitor is inconsistent with the channel state during deserialization the channel will
10273         /// be force-closed using the data in the ChannelMonitor and the channel will be dropped. This
10274         /// is true for missing channels as well. If there is a monitor missing for which we find
10275         /// channel data Err(DecodeError::InvalidValue) will be returned.
10276         ///
10277         /// In such cases the latest local transactions will be sent to the tx_broadcaster included in
10278         /// this struct.
10279         ///
10280         /// This is not exported to bindings users because we have no HashMap bindings
10281         pub channel_monitors: HashMap<OutPoint, &'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>,
10282 }
10283
10284 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10285                 ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>
10286 where
10287         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10288         T::Target: BroadcasterInterface,
10289         ES::Target: EntropySource,
10290         NS::Target: NodeSigner,
10291         SP::Target: SignerProvider,
10292         F::Target: FeeEstimator,
10293         R::Target: Router,
10294         L::Target: Logger,
10295 {
10296         /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
10297         /// HashMap for you. This is primarily useful for C bindings where it is not practical to
10298         /// populate a HashMap directly from C.
10299         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,
10300                         mut channel_monitors: Vec<&'a mut ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>>) -> Self {
10301                 Self {
10302                         entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, default_config,
10303                         channel_monitors: channel_monitors.drain(..).map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect()
10304                 }
10305         }
10306 }
10307
10308 // Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
10309 // SipmleArcChannelManager type:
10310 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10311         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, Arc<ChannelManager<M, T, ES, NS, SP, F, R, L>>)
10312 where
10313         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10314         T::Target: BroadcasterInterface,
10315         ES::Target: EntropySource,
10316         NS::Target: NodeSigner,
10317         SP::Target: SignerProvider,
10318         F::Target: FeeEstimator,
10319         R::Target: Router,
10320         L::Target: Logger,
10321 {
10322         fn read<Reader: io::Read>(reader: &mut Reader, args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10323                 let (blockhash, chan_manager) = <(BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)>::read(reader, args)?;
10324                 Ok((blockhash, Arc::new(chan_manager)))
10325         }
10326 }
10327
10328 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
10329         ReadableArgs<ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>> for (BlockHash, ChannelManager<M, T, ES, NS, SP, F, R, L>)
10330 where
10331         M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
10332         T::Target: BroadcasterInterface,
10333         ES::Target: EntropySource,
10334         NS::Target: NodeSigner,
10335         SP::Target: SignerProvider,
10336         F::Target: FeeEstimator,
10337         R::Target: Router,
10338         L::Target: Logger,
10339 {
10340         fn read<Reader: io::Read>(reader: &mut Reader, mut args: ChannelManagerReadArgs<'a, M, T, ES, NS, SP, F, R, L>) -> Result<Self, DecodeError> {
10341                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
10342
10343                 let chain_hash: ChainHash = Readable::read(reader)?;
10344                 let best_block_height: u32 = Readable::read(reader)?;
10345                 let best_block_hash: BlockHash = Readable::read(reader)?;
10346
10347                 let mut failed_htlcs = Vec::new();
10348
10349                 let channel_count: u64 = Readable::read(reader)?;
10350                 let mut funding_txo_set = HashSet::with_capacity(cmp::min(channel_count as usize, 128));
10351                 let mut funded_peer_channels: HashMap<PublicKey, HashMap<ChannelId, ChannelPhase<SP>>> = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10352                 let mut outpoint_to_peer = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10353                 let mut short_to_chan_info = HashMap::with_capacity(cmp::min(channel_count as usize, 128));
10354                 let mut channel_closures = VecDeque::new();
10355                 let mut close_background_events = Vec::new();
10356                 let mut funding_txo_to_channel_id = HashMap::with_capacity(channel_count as usize);
10357                 for _ in 0..channel_count {
10358                         let mut channel: Channel<SP> = Channel::read(reader, (
10359                                 &args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
10360                         ))?;
10361                         let logger = WithChannelContext::from(&args.logger, &channel.context);
10362                         let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10363                         funding_txo_to_channel_id.insert(funding_txo, channel.context.channel_id());
10364                         funding_txo_set.insert(funding_txo.clone());
10365                         if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10366                                 if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
10367                                                 channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
10368                                                 channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
10369                                                 channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10370                                         // But if the channel is behind of the monitor, close the channel:
10371                                         log_error!(logger, "A ChannelManager is stale compared to the current ChannelMonitor!");
10372                                         log_error!(logger, " The channel will be force-closed and the latest commitment transaction from the ChannelMonitor broadcast.");
10373                                         if channel.context.get_latest_monitor_update_id() < monitor.get_latest_update_id() {
10374                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} but the ChannelManager is at update_id {}.",
10375                                                         &channel.context.channel_id(), monitor.get_latest_update_id(), channel.context.get_latest_monitor_update_id());
10376                                         }
10377                                         if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() {
10378                                                 log_error!(logger, " The ChannelMonitor for channel {} is at holder commitment number {} but the ChannelManager is at holder commitment number {}.",
10379                                                         &channel.context.channel_id(), monitor.get_cur_holder_commitment_number(), channel.get_cur_holder_commitment_transaction_number());
10380                                         }
10381                                         if channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() {
10382                                                 log_error!(logger, " The ChannelMonitor for channel {} is at revoked counterparty transaction number {} but the ChannelManager is at revoked counterparty transaction number {}.",
10383                                                         &channel.context.channel_id(), monitor.get_min_seen_secret(), channel.get_revoked_counterparty_commitment_transaction_number());
10384                                         }
10385                                         if channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() {
10386                                                 log_error!(logger, " The ChannelMonitor for channel {} is at counterparty commitment transaction number {} but the ChannelManager is at counterparty commitment transaction number {}.",
10387                                                         &channel.context.channel_id(), monitor.get_cur_counterparty_commitment_number(), channel.get_cur_counterparty_commitment_transaction_number());
10388                                         }
10389                                         let mut shutdown_result = channel.context.force_shutdown(true, ClosureReason::OutdatedChannelManager);
10390                                         if shutdown_result.unbroadcasted_batch_funding_txid.is_some() {
10391                                                 return Err(DecodeError::InvalidValue);
10392                                         }
10393                                         if let Some((counterparty_node_id, funding_txo, channel_id, update)) = shutdown_result.monitor_update {
10394                                                 close_background_events.push(BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10395                                                         counterparty_node_id, funding_txo, channel_id, update
10396                                                 });
10397                                         }
10398                                         failed_htlcs.append(&mut shutdown_result.dropped_outbound_htlcs);
10399                                         channel_closures.push_back((events::Event::ChannelClosed {
10400                                                 channel_id: channel.context.channel_id(),
10401                                                 user_channel_id: channel.context.get_user_id(),
10402                                                 reason: ClosureReason::OutdatedChannelManager,
10403                                                 counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10404                                                 channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10405                                                 channel_funding_txo: channel.context.get_funding_txo(),
10406                                         }, None));
10407                                         for (channel_htlc_source, payment_hash) in channel.inflight_htlc_sources() {
10408                                                 let mut found_htlc = false;
10409                                                 for (monitor_htlc_source, _) in monitor.get_all_current_outbound_htlcs() {
10410                                                         if *channel_htlc_source == monitor_htlc_source { found_htlc = true; break; }
10411                                                 }
10412                                                 if !found_htlc {
10413                                                         // If we have some HTLCs in the channel which are not present in the newer
10414                                                         // ChannelMonitor, they have been removed and should be failed back to
10415                                                         // ensure we don't forget them entirely. Note that if the missing HTLC(s)
10416                                                         // were actually claimed we'd have generated and ensured the previous-hop
10417                                                         // claim update ChannelMonitor updates were persisted prior to persising
10418                                                         // the ChannelMonitor update for the forward leg, so attempting to fail the
10419                                                         // backwards leg of the HTLC will simply be rejected.
10420                                                         log_info!(logger,
10421                                                                 "Failing HTLC with hash {} as it is missing in the ChannelMonitor for channel {} but was present in the (stale) ChannelManager",
10422                                                                 &channel.context.channel_id(), &payment_hash);
10423                                                         failed_htlcs.push((channel_htlc_source.clone(), *payment_hash, channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10424                                                 }
10425                                         }
10426                                 } else {
10427                                         log_info!(logger, "Successfully loaded channel {} at update_id {} against monitor at update id {}",
10428                                                 &channel.context.channel_id(), channel.context.get_latest_monitor_update_id(),
10429                                                 monitor.get_latest_update_id());
10430                                         if let Some(short_channel_id) = channel.context.get_short_channel_id() {
10431                                                 short_to_chan_info.insert(short_channel_id, (channel.context.get_counterparty_node_id(), channel.context.channel_id()));
10432                                         }
10433                                         if let Some(funding_txo) = channel.context.get_funding_txo() {
10434                                                 outpoint_to_peer.insert(funding_txo, channel.context.get_counterparty_node_id());
10435                                         }
10436                                         match funded_peer_channels.entry(channel.context.get_counterparty_node_id()) {
10437                                                 hash_map::Entry::Occupied(mut entry) => {
10438                                                         let by_id_map = entry.get_mut();
10439                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10440                                                 },
10441                                                 hash_map::Entry::Vacant(entry) => {
10442                                                         let mut by_id_map = HashMap::new();
10443                                                         by_id_map.insert(channel.context.channel_id(), ChannelPhase::Funded(channel));
10444                                                         entry.insert(by_id_map);
10445                                                 }
10446                                         }
10447                                 }
10448                         } else if channel.is_awaiting_initial_mon_persist() {
10449                                 // If we were persisted and shut down while the initial ChannelMonitor persistence
10450                                 // was in-progress, we never broadcasted the funding transaction and can still
10451                                 // safely discard the channel.
10452                                 let _ = channel.context.force_shutdown(false, ClosureReason::DisconnectedPeer);
10453                                 channel_closures.push_back((events::Event::ChannelClosed {
10454                                         channel_id: channel.context.channel_id(),
10455                                         user_channel_id: channel.context.get_user_id(),
10456                                         reason: ClosureReason::DisconnectedPeer,
10457                                         counterparty_node_id: Some(channel.context.get_counterparty_node_id()),
10458                                         channel_capacity_sats: Some(channel.context.get_value_satoshis()),
10459                                         channel_funding_txo: channel.context.get_funding_txo(),
10460                                 }, None));
10461                         } else {
10462                                 log_error!(logger, "Missing ChannelMonitor for channel {} needed by ChannelManager.", &channel.context.channel_id());
10463                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10464                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10465                                 log_error!(logger, " Without the ChannelMonitor we cannot continue without risking funds.");
10466                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10467                                 return Err(DecodeError::InvalidValue);
10468                         }
10469                 }
10470
10471                 for (funding_txo, monitor) in args.channel_monitors.iter() {
10472                         if !funding_txo_set.contains(funding_txo) {
10473                                 let logger = WithChannelMonitor::from(&args.logger, monitor);
10474                                 let channel_id = monitor.channel_id();
10475                                 log_info!(logger, "Queueing monitor update to ensure missing channel {} is force closed",
10476                                         &channel_id);
10477                                 let monitor_update = ChannelMonitorUpdate {
10478                                         update_id: CLOSED_CHANNEL_UPDATE_ID,
10479                                         counterparty_node_id: None,
10480                                         updates: vec![ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast: true }],
10481                                         channel_id: Some(monitor.channel_id()),
10482                                 };
10483                                 close_background_events.push(BackgroundEvent::ClosedMonitorUpdateRegeneratedOnStartup((*funding_txo, channel_id, monitor_update)));
10484                         }
10485                 }
10486
10487                 const MAX_ALLOC_SIZE: usize = 1024 * 64;
10488                 let forward_htlcs_count: u64 = Readable::read(reader)?;
10489                 let mut forward_htlcs = HashMap::with_capacity(cmp::min(forward_htlcs_count as usize, 128));
10490                 for _ in 0..forward_htlcs_count {
10491                         let short_channel_id = Readable::read(reader)?;
10492                         let pending_forwards_count: u64 = Readable::read(reader)?;
10493                         let mut pending_forwards = Vec::with_capacity(cmp::min(pending_forwards_count as usize, MAX_ALLOC_SIZE/mem::size_of::<HTLCForwardInfo>()));
10494                         for _ in 0..pending_forwards_count {
10495                                 pending_forwards.push(Readable::read(reader)?);
10496                         }
10497                         forward_htlcs.insert(short_channel_id, pending_forwards);
10498                 }
10499
10500                 let claimable_htlcs_count: u64 = Readable::read(reader)?;
10501                 let mut claimable_htlcs_list = Vec::with_capacity(cmp::min(claimable_htlcs_count as usize, 128));
10502                 for _ in 0..claimable_htlcs_count {
10503                         let payment_hash = Readable::read(reader)?;
10504                         let previous_hops_len: u64 = Readable::read(reader)?;
10505                         let mut previous_hops = Vec::with_capacity(cmp::min(previous_hops_len as usize, MAX_ALLOC_SIZE/mem::size_of::<ClaimableHTLC>()));
10506                         for _ in 0..previous_hops_len {
10507                                 previous_hops.push(<ClaimableHTLC as Readable>::read(reader)?);
10508                         }
10509                         claimable_htlcs_list.push((payment_hash, previous_hops));
10510                 }
10511
10512                 let peer_state_from_chans = |channel_by_id| {
10513                         PeerState {
10514                                 channel_by_id,
10515                                 inbound_channel_request_by_id: HashMap::new(),
10516                                 latest_features: InitFeatures::empty(),
10517                                 pending_msg_events: Vec::new(),
10518                                 in_flight_monitor_updates: BTreeMap::new(),
10519                                 monitor_update_blocked_actions: BTreeMap::new(),
10520                                 actions_blocking_raa_monitor_updates: BTreeMap::new(),
10521                                 is_connected: false,
10522                         }
10523                 };
10524
10525                 let peer_count: u64 = Readable::read(reader)?;
10526                 let mut per_peer_state = HashMap::with_capacity(cmp::min(peer_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(PublicKey, Mutex<PeerState<SP>>)>()));
10527                 for _ in 0..peer_count {
10528                         let peer_pubkey = Readable::read(reader)?;
10529                         let peer_chans = funded_peer_channels.remove(&peer_pubkey).unwrap_or(HashMap::new());
10530                         let mut peer_state = peer_state_from_chans(peer_chans);
10531                         peer_state.latest_features = Readable::read(reader)?;
10532                         per_peer_state.insert(peer_pubkey, Mutex::new(peer_state));
10533                 }
10534
10535                 let event_count: u64 = Readable::read(reader)?;
10536                 let mut pending_events_read: VecDeque<(events::Event, Option<EventCompletionAction>)> =
10537                         VecDeque::with_capacity(cmp::min(event_count as usize, MAX_ALLOC_SIZE/mem::size_of::<(events::Event, Option<EventCompletionAction>)>()));
10538                 for _ in 0..event_count {
10539                         match MaybeReadable::read(reader)? {
10540                                 Some(event) => pending_events_read.push_back((event, None)),
10541                                 None => continue,
10542                         }
10543                 }
10544
10545                 let background_event_count: u64 = Readable::read(reader)?;
10546                 for _ in 0..background_event_count {
10547                         match <u8 as Readable>::read(reader)? {
10548                                 0 => {
10549                                         // LDK versions prior to 0.0.116 wrote pending `MonitorUpdateRegeneratedOnStartup`s here,
10550                                         // however we really don't (and never did) need them - we regenerate all
10551                                         // on-startup monitor updates.
10552                                         let _: OutPoint = Readable::read(reader)?;
10553                                         let _: ChannelMonitorUpdate = Readable::read(reader)?;
10554                                 }
10555                                 _ => return Err(DecodeError::InvalidValue),
10556                         }
10557                 }
10558
10559                 let _last_node_announcement_serial: u32 = Readable::read(reader)?; // Only used < 0.0.111
10560                 let highest_seen_timestamp: u32 = Readable::read(reader)?;
10561
10562                 let pending_inbound_payment_count: u64 = Readable::read(reader)?;
10563                 let mut pending_inbound_payments: HashMap<PaymentHash, PendingInboundPayment> = HashMap::with_capacity(cmp::min(pending_inbound_payment_count as usize, MAX_ALLOC_SIZE/(3*32)));
10564                 for _ in 0..pending_inbound_payment_count {
10565                         if pending_inbound_payments.insert(Readable::read(reader)?, Readable::read(reader)?).is_some() {
10566                                 return Err(DecodeError::InvalidValue);
10567                         }
10568                 }
10569
10570                 let pending_outbound_payments_count_compat: u64 = Readable::read(reader)?;
10571                 let mut pending_outbound_payments_compat: HashMap<PaymentId, PendingOutboundPayment> =
10572                         HashMap::with_capacity(cmp::min(pending_outbound_payments_count_compat as usize, MAX_ALLOC_SIZE/32));
10573                 for _ in 0..pending_outbound_payments_count_compat {
10574                         let session_priv = Readable::read(reader)?;
10575                         let payment = PendingOutboundPayment::Legacy {
10576                                 session_privs: [session_priv].iter().cloned().collect()
10577                         };
10578                         if pending_outbound_payments_compat.insert(PaymentId(session_priv), payment).is_some() {
10579                                 return Err(DecodeError::InvalidValue)
10580                         };
10581                 }
10582
10583                 // pending_outbound_payments_no_retry is for compatibility with 0.0.101 clients.
10584                 let mut pending_outbound_payments_no_retry: Option<HashMap<PaymentId, HashSet<[u8; 32]>>> = None;
10585                 let mut pending_outbound_payments = None;
10586                 let mut pending_intercepted_htlcs: Option<HashMap<InterceptId, PendingAddHTLCInfo>> = Some(HashMap::new());
10587                 let mut received_network_pubkey: Option<PublicKey> = None;
10588                 let mut fake_scid_rand_bytes: Option<[u8; 32]> = None;
10589                 let mut probing_cookie_secret: Option<[u8; 32]> = None;
10590                 let mut claimable_htlc_purposes = None;
10591                 let mut claimable_htlc_onion_fields = None;
10592                 let mut pending_claiming_payments = Some(HashMap::new());
10593                 let mut monitor_update_blocked_actions_per_peer: Option<Vec<(_, BTreeMap<_, Vec<_>>)>> = Some(Vec::new());
10594                 let mut events_override = None;
10595                 let mut in_flight_monitor_updates: Option<HashMap<(PublicKey, OutPoint), Vec<ChannelMonitorUpdate>>> = None;
10596                 read_tlv_fields!(reader, {
10597                         (1, pending_outbound_payments_no_retry, option),
10598                         (2, pending_intercepted_htlcs, option),
10599                         (3, pending_outbound_payments, option),
10600                         (4, pending_claiming_payments, option),
10601                         (5, received_network_pubkey, option),
10602                         (6, monitor_update_blocked_actions_per_peer, option),
10603                         (7, fake_scid_rand_bytes, option),
10604                         (8, events_override, option),
10605                         (9, claimable_htlc_purposes, optional_vec),
10606                         (10, in_flight_monitor_updates, option),
10607                         (11, probing_cookie_secret, option),
10608                         (13, claimable_htlc_onion_fields, optional_vec),
10609                 });
10610                 if fake_scid_rand_bytes.is_none() {
10611                         fake_scid_rand_bytes = Some(args.entropy_source.get_secure_random_bytes());
10612                 }
10613
10614                 if probing_cookie_secret.is_none() {
10615                         probing_cookie_secret = Some(args.entropy_source.get_secure_random_bytes());
10616                 }
10617
10618                 if let Some(events) = events_override {
10619                         pending_events_read = events;
10620                 }
10621
10622                 if !channel_closures.is_empty() {
10623                         pending_events_read.append(&mut channel_closures);
10624                 }
10625
10626                 if pending_outbound_payments.is_none() && pending_outbound_payments_no_retry.is_none() {
10627                         pending_outbound_payments = Some(pending_outbound_payments_compat);
10628                 } else if pending_outbound_payments.is_none() {
10629                         let mut outbounds = HashMap::new();
10630                         for (id, session_privs) in pending_outbound_payments_no_retry.unwrap().drain() {
10631                                 outbounds.insert(id, PendingOutboundPayment::Legacy { session_privs });
10632                         }
10633                         pending_outbound_payments = Some(outbounds);
10634                 }
10635                 let pending_outbounds = OutboundPayments {
10636                         pending_outbound_payments: Mutex::new(pending_outbound_payments.unwrap()),
10637                         retry_lock: Mutex::new(())
10638                 };
10639
10640                 // We have to replay (or skip, if they were completed after we wrote the `ChannelManager`)
10641                 // each `ChannelMonitorUpdate` in `in_flight_monitor_updates`. After doing so, we have to
10642                 // check that each channel we have isn't newer than the latest `ChannelMonitorUpdate`(s) we
10643                 // replayed, and for each monitor update we have to replay we have to ensure there's a
10644                 // `ChannelMonitor` for it.
10645                 //
10646                 // In order to do so we first walk all of our live channels (so that we can check their
10647                 // state immediately after doing the update replays, when we have the `update_id`s
10648                 // available) and then walk any remaining in-flight updates.
10649                 //
10650                 // Because the actual handling of the in-flight updates is the same, it's macro'ized here:
10651                 let mut pending_background_events = Vec::new();
10652                 macro_rules! handle_in_flight_updates {
10653                         ($counterparty_node_id: expr, $chan_in_flight_upds: expr, $funding_txo: expr,
10654                          $monitor: expr, $peer_state: expr, $logger: expr, $channel_info_log: expr
10655                         ) => { {
10656                                 let mut max_in_flight_update_id = 0;
10657                                 $chan_in_flight_upds.retain(|upd| upd.update_id > $monitor.get_latest_update_id());
10658                                 for update in $chan_in_flight_upds.iter() {
10659                                         log_trace!($logger, "Replaying ChannelMonitorUpdate {} for {}channel {}",
10660                                                 update.update_id, $channel_info_log, &$monitor.channel_id());
10661                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id, update.update_id);
10662                                         pending_background_events.push(
10663                                                 BackgroundEvent::MonitorUpdateRegeneratedOnStartup {
10664                                                         counterparty_node_id: $counterparty_node_id,
10665                                                         funding_txo: $funding_txo,
10666                                                         channel_id: $monitor.channel_id(),
10667                                                         update: update.clone(),
10668                                                 });
10669                                 }
10670                                 if $chan_in_flight_upds.is_empty() {
10671                                         // We had some updates to apply, but it turns out they had completed before we
10672                                         // were serialized, we just weren't notified of that. Thus, we may have to run
10673                                         // the completion actions for any monitor updates, but otherwise are done.
10674                                         pending_background_events.push(
10675                                                 BackgroundEvent::MonitorUpdatesComplete {
10676                                                         counterparty_node_id: $counterparty_node_id,
10677                                                         channel_id: $monitor.channel_id(),
10678                                                 });
10679                                 }
10680                                 if $peer_state.in_flight_monitor_updates.insert($funding_txo, $chan_in_flight_upds).is_some() {
10681                                         log_error!($logger, "Duplicate in-flight monitor update set for the same channel!");
10682                                         return Err(DecodeError::InvalidValue);
10683                                 }
10684                                 max_in_flight_update_id
10685                         } }
10686                 }
10687
10688                 for (counterparty_id, peer_state_mtx) in per_peer_state.iter_mut() {
10689                         let mut peer_state_lock = peer_state_mtx.lock().unwrap();
10690                         let peer_state = &mut *peer_state_lock;
10691                         for phase in peer_state.channel_by_id.values() {
10692                                 if let ChannelPhase::Funded(chan) = phase {
10693                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
10694
10695                                         // Channels that were persisted have to be funded, otherwise they should have been
10696                                         // discarded.
10697                                         let funding_txo = chan.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
10698                                         let monitor = args.channel_monitors.get(&funding_txo)
10699                                                 .expect("We already checked for monitor presence when loading channels");
10700                                         let mut max_in_flight_update_id = monitor.get_latest_update_id();
10701                                         if let Some(in_flight_upds) = &mut in_flight_monitor_updates {
10702                                                 if let Some(mut chan_in_flight_upds) = in_flight_upds.remove(&(*counterparty_id, funding_txo)) {
10703                                                         max_in_flight_update_id = cmp::max(max_in_flight_update_id,
10704                                                                 handle_in_flight_updates!(*counterparty_id, chan_in_flight_upds,
10705                                                                         funding_txo, monitor, peer_state, logger, ""));
10706                                                 }
10707                                         }
10708                                         if chan.get_latest_unblocked_monitor_update_id() > max_in_flight_update_id {
10709                                                 // If the channel is ahead of the monitor, return InvalidValue:
10710                                                 log_error!(logger, "A ChannelMonitor is stale compared to the current ChannelManager! This indicates a potentially-critical violation of the chain::Watch API!");
10711                                                 log_error!(logger, " The ChannelMonitor for channel {} is at update_id {} with update_id through {} in-flight",
10712                                                         chan.context.channel_id(), monitor.get_latest_update_id(), max_in_flight_update_id);
10713                                                 log_error!(logger, " but the ChannelManager is at update_id {}.", chan.get_latest_unblocked_monitor_update_id());
10714                                                 log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10715                                                 log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10716                                                 log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10717                                                 log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10718                                                 return Err(DecodeError::InvalidValue);
10719                                         }
10720                                 } else {
10721                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
10722                                         // created in this `channel_by_id` map.
10723                                         debug_assert!(false);
10724                                         return Err(DecodeError::InvalidValue);
10725                                 }
10726                         }
10727                 }
10728
10729                 if let Some(in_flight_upds) = in_flight_monitor_updates {
10730                         for ((counterparty_id, funding_txo), mut chan_in_flight_updates) in in_flight_upds {
10731                                 let channel_id = funding_txo_to_channel_id.get(&funding_txo).copied();
10732                                 let logger = WithContext::from(&args.logger, Some(counterparty_id), channel_id);
10733                                 if let Some(monitor) = args.channel_monitors.get(&funding_txo) {
10734                                         // Now that we've removed all the in-flight monitor updates for channels that are
10735                                         // still open, we need to replay any monitor updates that are for closed channels,
10736                                         // creating the neccessary peer_state entries as we go.
10737                                         let peer_state_mutex = per_peer_state.entry(counterparty_id).or_insert_with(|| {
10738                                                 Mutex::new(peer_state_from_chans(HashMap::new()))
10739                                         });
10740                                         let mut peer_state = peer_state_mutex.lock().unwrap();
10741                                         handle_in_flight_updates!(counterparty_id, chan_in_flight_updates,
10742                                                 funding_txo, monitor, peer_state, logger, "closed ");
10743                                 } else {
10744                                         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!");
10745                                         log_error!(logger, " The ChannelMonitor for channel {} is missing.", if let Some(channel_id) =
10746                                                 channel_id { channel_id.to_string() } else { format!("with outpoint {}", funding_txo) } );
10747                                         log_error!(logger, " The chain::Watch API *requires* that monitors are persisted durably before returning,");
10748                                         log_error!(logger, " client applications must ensure that ChannelMonitor data is always available and the latest to avoid funds loss!");
10749                                         log_error!(logger, " Without the latest ChannelMonitor we cannot continue without risking funds.");
10750                                         log_error!(logger, " Please ensure the chain::Watch API requirements are met and file a bug report at https://github.com/lightningdevkit/rust-lightning");
10751                                         return Err(DecodeError::InvalidValue);
10752                                 }
10753                         }
10754                 }
10755
10756                 // Note that we have to do the above replays before we push new monitor updates.
10757                 pending_background_events.append(&mut close_background_events);
10758
10759                 // If there's any preimages for forwarded HTLCs hanging around in ChannelMonitors we
10760                 // should ensure we try them again on the inbound edge. We put them here and do so after we
10761                 // have a fully-constructed `ChannelManager` at the end.
10762                 let mut pending_claims_to_replay = Vec::new();
10763
10764                 {
10765                         // If we're tracking pending payments, ensure we haven't lost any by looking at the
10766                         // ChannelMonitor data for any channels for which we do not have authorative state
10767                         // (i.e. those for which we just force-closed above or we otherwise don't have a
10768                         // corresponding `Channel` at all).
10769                         // This avoids several edge-cases where we would otherwise "forget" about pending
10770                         // payments which are still in-flight via their on-chain state.
10771                         // We only rebuild the pending payments map if we were most recently serialized by
10772                         // 0.0.102+
10773                         for (_, monitor) in args.channel_monitors.iter() {
10774                                 let counterparty_opt = outpoint_to_peer.get(&monitor.get_funding_txo().0);
10775                                 if counterparty_opt.is_none() {
10776                                         let logger = WithChannelMonitor::from(&args.logger, monitor);
10777                                         for (htlc_source, (htlc, _)) in monitor.get_pending_or_resolved_outbound_htlcs() {
10778                                                 if let HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } = htlc_source {
10779                                                         if path.hops.is_empty() {
10780                                                                 log_error!(logger, "Got an empty path for a pending payment");
10781                                                                 return Err(DecodeError::InvalidValue);
10782                                                         }
10783
10784                                                         let path_amt = path.final_value_msat();
10785                                                         let mut session_priv_bytes = [0; 32];
10786                                                         session_priv_bytes[..].copy_from_slice(&session_priv[..]);
10787                                                         match pending_outbounds.pending_outbound_payments.lock().unwrap().entry(payment_id) {
10788                                                                 hash_map::Entry::Occupied(mut entry) => {
10789                                                                         let newly_added = entry.get_mut().insert(session_priv_bytes, &path);
10790                                                                         log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
10791                                                                                 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), htlc.payment_hash);
10792                                                                 },
10793                                                                 hash_map::Entry::Vacant(entry) => {
10794                                                                         let path_fee = path.fee_msat();
10795                                                                         entry.insert(PendingOutboundPayment::Retryable {
10796                                                                                 retry_strategy: None,
10797                                                                                 attempts: PaymentAttempts::new(),
10798                                                                                 payment_params: None,
10799                                                                                 session_privs: [session_priv_bytes].iter().map(|a| *a).collect(),
10800                                                                                 payment_hash: htlc.payment_hash,
10801                                                                                 payment_secret: None, // only used for retries, and we'll never retry on startup
10802                                                                                 payment_metadata: None, // only used for retries, and we'll never retry on startup
10803                                                                                 keysend_preimage: None, // only used for retries, and we'll never retry on startup
10804                                                                                 custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
10805                                                                                 pending_amt_msat: path_amt,
10806                                                                                 pending_fee_msat: Some(path_fee),
10807                                                                                 total_msat: path_amt,
10808                                                                                 starting_block_height: best_block_height,
10809                                                                                 remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
10810                                                                         });
10811                                                                         log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
10812                                                                                 path_amt, &htlc.payment_hash,  log_bytes!(session_priv_bytes));
10813                                                                 }
10814                                                         }
10815                                                 }
10816                                         }
10817                                         for (htlc_source, (htlc, preimage_opt)) in monitor.get_all_current_outbound_htlcs() {
10818                                                 match htlc_source {
10819                                                         HTLCSource::PreviousHopData(prev_hop_data) => {
10820                                                                 let pending_forward_matches_htlc = |info: &PendingAddHTLCInfo| {
10821                                                                         info.prev_funding_outpoint == prev_hop_data.outpoint &&
10822                                                                                 info.prev_htlc_id == prev_hop_data.htlc_id
10823                                                                 };
10824                                                                 // The ChannelMonitor is now responsible for this HTLC's
10825                                                                 // failure/success and will let us know what its outcome is. If we
10826                                                                 // still have an entry for this HTLC in `forward_htlcs` or
10827                                                                 // `pending_intercepted_htlcs`, we were apparently not persisted after
10828                                                                 // the monitor was when forwarding the payment.
10829                                                                 forward_htlcs.retain(|_, forwards| {
10830                                                                         forwards.retain(|forward| {
10831                                                                                 if let HTLCForwardInfo::AddHTLC(htlc_info) = forward {
10832                                                                                         if pending_forward_matches_htlc(&htlc_info) {
10833                                                                                                 log_info!(logger, "Removing pending to-forward HTLC with hash {} as it was forwarded to the closed channel {}",
10834                                                                                                         &htlc.payment_hash, &monitor.channel_id());
10835                                                                                                 false
10836                                                                                         } else { true }
10837                                                                                 } else { true }
10838                                                                         });
10839                                                                         !forwards.is_empty()
10840                                                                 });
10841                                                                 pending_intercepted_htlcs.as_mut().unwrap().retain(|intercepted_id, htlc_info| {
10842                                                                         if pending_forward_matches_htlc(&htlc_info) {
10843                                                                                 log_info!(logger, "Removing pending intercepted HTLC with hash {} as it was forwarded to the closed channel {}",
10844                                                                                         &htlc.payment_hash, &monitor.channel_id());
10845                                                                                 pending_events_read.retain(|(event, _)| {
10846                                                                                         if let Event::HTLCIntercepted { intercept_id: ev_id, .. } = event {
10847                                                                                                 intercepted_id != ev_id
10848                                                                                         } else { true }
10849                                                                                 });
10850                                                                                 false
10851                                                                         } else { true }
10852                                                                 });
10853                                                         },
10854                                                         HTLCSource::OutboundRoute { payment_id, session_priv, path, .. } => {
10855                                                                 if let Some(preimage) = preimage_opt {
10856                                                                         let pending_events = Mutex::new(pending_events_read);
10857                                                                         // Note that we set `from_onchain` to "false" here,
10858                                                                         // deliberately keeping the pending payment around forever.
10859                                                                         // Given it should only occur when we have a channel we're
10860                                                                         // force-closing for being stale that's okay.
10861                                                                         // The alternative would be to wipe the state when claiming,
10862                                                                         // generating a `PaymentPathSuccessful` event but regenerating
10863                                                                         // it and the `PaymentSent` on every restart until the
10864                                                                         // `ChannelMonitor` is removed.
10865                                                                         let compl_action =
10866                                                                                 EventCompletionAction::ReleaseRAAChannelMonitorUpdate {
10867                                                                                         channel_funding_outpoint: monitor.get_funding_txo().0,
10868                                                                                         channel_id: monitor.channel_id(),
10869                                                                                         counterparty_node_id: path.hops[0].pubkey,
10870                                                                                 };
10871                                                                         pending_outbounds.claim_htlc(payment_id, preimage, session_priv,
10872                                                                                 path, false, compl_action, &pending_events, &&logger);
10873                                                                         pending_events_read = pending_events.into_inner().unwrap();
10874                                                                 }
10875                                                         },
10876                                                 }
10877                                         }
10878                                 }
10879
10880                                 // Whether the downstream channel was closed or not, try to re-apply any payment
10881                                 // preimages from it which may be needed in upstream channels for forwarded
10882                                 // payments.
10883                                 let outbound_claimed_htlcs_iter = monitor.get_all_current_outbound_htlcs()
10884                                         .into_iter()
10885                                         .filter_map(|(htlc_source, (htlc, preimage_opt))| {
10886                                                 if let HTLCSource::PreviousHopData(_) = htlc_source {
10887                                                         if let Some(payment_preimage) = preimage_opt {
10888                                                                 Some((htlc_source, payment_preimage, htlc.amount_msat,
10889                                                                         // Check if `counterparty_opt.is_none()` to see if the
10890                                                                         // downstream chan is closed (because we don't have a
10891                                                                         // channel_id -> peer map entry).
10892                                                                         counterparty_opt.is_none(),
10893                                                                         counterparty_opt.cloned().or(monitor.get_counterparty_node_id()),
10894                                                                         monitor.get_funding_txo().0, monitor.channel_id()))
10895                                                         } else { None }
10896                                                 } else {
10897                                                         // If it was an outbound payment, we've handled it above - if a preimage
10898                                                         // came in and we persisted the `ChannelManager` we either handled it and
10899                                                         // are good to go or the channel force-closed - we don't have to handle the
10900                                                         // channel still live case here.
10901                                                         None
10902                                                 }
10903                                         });
10904                                 for tuple in outbound_claimed_htlcs_iter {
10905                                         pending_claims_to_replay.push(tuple);
10906                                 }
10907                         }
10908                 }
10909
10910                 if !forward_htlcs.is_empty() || pending_outbounds.needs_abandon() {
10911                         // If we have pending HTLCs to forward, assume we either dropped a
10912                         // `PendingHTLCsForwardable` or the user received it but never processed it as they
10913                         // shut down before the timer hit. Either way, set the time_forwardable to a small
10914                         // constant as enough time has likely passed that we should simply handle the forwards
10915                         // now, or at least after the user gets a chance to reconnect to our peers.
10916                         pending_events_read.push_back((events::Event::PendingHTLCsForwardable {
10917                                 time_forwardable: Duration::from_secs(2),
10918                         }, None));
10919                 }
10920
10921                 let inbound_pmt_key_material = args.node_signer.get_inbound_payment_key_material();
10922                 let expanded_inbound_key = inbound_payment::ExpandedKey::new(&inbound_pmt_key_material);
10923
10924                 let mut claimable_payments = HashMap::with_capacity(claimable_htlcs_list.len());
10925                 if let Some(purposes) = claimable_htlc_purposes {
10926                         if purposes.len() != claimable_htlcs_list.len() {
10927                                 return Err(DecodeError::InvalidValue);
10928                         }
10929                         if let Some(onion_fields) = claimable_htlc_onion_fields {
10930                                 if onion_fields.len() != claimable_htlcs_list.len() {
10931                                         return Err(DecodeError::InvalidValue);
10932                                 }
10933                                 for (purpose, (onion, (payment_hash, htlcs))) in
10934                                         purposes.into_iter().zip(onion_fields.into_iter().zip(claimable_htlcs_list.into_iter()))
10935                                 {
10936                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10937                                                 purpose, htlcs, onion_fields: onion,
10938                                         });
10939                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10940                                 }
10941                         } else {
10942                                 for (purpose, (payment_hash, htlcs)) in purposes.into_iter().zip(claimable_htlcs_list.into_iter()) {
10943                                         let existing_payment = claimable_payments.insert(payment_hash, ClaimablePayment {
10944                                                 purpose, htlcs, onion_fields: None,
10945                                         });
10946                                         if existing_payment.is_some() { return Err(DecodeError::InvalidValue); }
10947                                 }
10948                         }
10949                 } else {
10950                         // LDK versions prior to 0.0.107 did not write a `pending_htlc_purposes`, but do
10951                         // include a `_legacy_hop_data` in the `OnionPayload`.
10952                         for (payment_hash, htlcs) in claimable_htlcs_list.drain(..) {
10953                                 if htlcs.is_empty() {
10954                                         return Err(DecodeError::InvalidValue);
10955                                 }
10956                                 let purpose = match &htlcs[0].onion_payload {
10957                                         OnionPayload::Invoice { _legacy_hop_data } => {
10958                                                 if let Some(hop_data) = _legacy_hop_data {
10959                                                         events::PaymentPurpose::InvoicePayment {
10960                                                                 payment_preimage: match pending_inbound_payments.get(&payment_hash) {
10961                                                                         Some(inbound_payment) => inbound_payment.payment_preimage,
10962                                                                         None => match inbound_payment::verify(payment_hash, &hop_data, 0, &expanded_inbound_key, &args.logger) {
10963                                                                                 Ok((payment_preimage, _)) => payment_preimage,
10964                                                                                 Err(()) => {
10965                                                                                         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);
10966                                                                                         return Err(DecodeError::InvalidValue);
10967                                                                                 }
10968                                                                         }
10969                                                                 },
10970                                                                 payment_secret: hop_data.payment_secret,
10971                                                         }
10972                                                 } else { return Err(DecodeError::InvalidValue); }
10973                                         },
10974                                         OnionPayload::Spontaneous(payment_preimage) =>
10975                                                 events::PaymentPurpose::SpontaneousPayment(*payment_preimage),
10976                                 };
10977                                 claimable_payments.insert(payment_hash, ClaimablePayment {
10978                                         purpose, htlcs, onion_fields: None,
10979                                 });
10980                         }
10981                 }
10982
10983                 let mut secp_ctx = Secp256k1::new();
10984                 secp_ctx.seeded_randomize(&args.entropy_source.get_secure_random_bytes());
10985
10986                 let our_network_pubkey = match args.node_signer.get_node_id(Recipient::Node) {
10987                         Ok(key) => key,
10988                         Err(()) => return Err(DecodeError::InvalidValue)
10989                 };
10990                 if let Some(network_pubkey) = received_network_pubkey {
10991                         if network_pubkey != our_network_pubkey {
10992                                 log_error!(args.logger, "Key that was generated does not match the existing key.");
10993                                 return Err(DecodeError::InvalidValue);
10994                         }
10995                 }
10996
10997                 let mut outbound_scid_aliases = HashSet::new();
10998                 for (_peer_node_id, peer_state_mutex) in per_peer_state.iter_mut() {
10999                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
11000                         let peer_state = &mut *peer_state_lock;
11001                         for (chan_id, phase) in peer_state.channel_by_id.iter_mut() {
11002                                 if let ChannelPhase::Funded(chan) = phase {
11003                                         let logger = WithChannelContext::from(&args.logger, &chan.context);
11004                                         if chan.context.outbound_scid_alias() == 0 {
11005                                                 let mut outbound_scid_alias;
11006                                                 loop {
11007                                                         outbound_scid_alias = fake_scid::Namespace::OutboundAlias
11008                                                                 .get_fake_scid(best_block_height, &chain_hash, fake_scid_rand_bytes.as_ref().unwrap(), &args.entropy_source);
11009                                                         if outbound_scid_aliases.insert(outbound_scid_alias) { break; }
11010                                                 }
11011                                                 chan.context.set_outbound_scid_alias(outbound_scid_alias);
11012                                         } else if !outbound_scid_aliases.insert(chan.context.outbound_scid_alias()) {
11013                                                 // Note that in rare cases its possible to hit this while reading an older
11014                                                 // channel if we just happened to pick a colliding outbound alias above.
11015                                                 log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
11016                                                 return Err(DecodeError::InvalidValue);
11017                                         }
11018                                         if chan.context.is_usable() {
11019                                                 if short_to_chan_info.insert(chan.context.outbound_scid_alias(), (chan.context.get_counterparty_node_id(), *chan_id)).is_some() {
11020                                                         // Note that in rare cases its possible to hit this while reading an older
11021                                                         // channel if we just happened to pick a colliding outbound alias above.
11022                                                         log_error!(logger, "Got duplicate outbound SCID alias; {}", chan.context.outbound_scid_alias());
11023                                                         return Err(DecodeError::InvalidValue);
11024                                                 }
11025                                         }
11026                                 } else {
11027                                         // We shouldn't have persisted (or read) any unfunded channel types so none should have been
11028                                         // created in this `channel_by_id` map.
11029                                         debug_assert!(false);
11030                                         return Err(DecodeError::InvalidValue);
11031                                 }
11032                         }
11033                 }
11034
11035                 let bounded_fee_estimator = LowerBoundedFeeEstimator::new(args.fee_estimator);
11036
11037                 for (_, monitor) in args.channel_monitors.iter() {
11038                         for (payment_hash, payment_preimage) in monitor.get_stored_preimages() {
11039                                 if let Some(payment) = claimable_payments.remove(&payment_hash) {
11040                                         log_info!(args.logger, "Re-claiming HTLCs with payment hash {} as we've released the preimage to a ChannelMonitor!", &payment_hash);
11041                                         let mut claimable_amt_msat = 0;
11042                                         let mut receiver_node_id = Some(our_network_pubkey);
11043                                         let phantom_shared_secret = payment.htlcs[0].prev_hop.phantom_shared_secret;
11044                                         if phantom_shared_secret.is_some() {
11045                                                 let phantom_pubkey = args.node_signer.get_node_id(Recipient::PhantomNode)
11046                                                         .expect("Failed to get node_id for phantom node recipient");
11047                                                 receiver_node_id = Some(phantom_pubkey)
11048                                         }
11049                                         for claimable_htlc in &payment.htlcs {
11050                                                 claimable_amt_msat += claimable_htlc.value;
11051
11052                                                 // Add a holding-cell claim of the payment to the Channel, which should be
11053                                                 // applied ~immediately on peer reconnection. Because it won't generate a
11054                                                 // new commitment transaction we can just provide the payment preimage to
11055                                                 // the corresponding ChannelMonitor and nothing else.
11056                                                 //
11057                                                 // We do so directly instead of via the normal ChannelMonitor update
11058                                                 // procedure as the ChainMonitor hasn't yet been initialized, implying
11059                                                 // we're not allowed to call it directly yet. Further, we do the update
11060                                                 // without incrementing the ChannelMonitor update ID as there isn't any
11061                                                 // reason to.
11062                                                 // If we were to generate a new ChannelMonitor update ID here and then
11063                                                 // crash before the user finishes block connect we'd end up force-closing
11064                                                 // this channel as well. On the flip side, there's no harm in restarting
11065                                                 // without the new monitor persisted - we'll end up right back here on
11066                                                 // restart.
11067                                                 let previous_channel_id = claimable_htlc.prev_hop.channel_id;
11068                                                 if let Some(peer_node_id) = outpoint_to_peer.get(&claimable_htlc.prev_hop.outpoint) {
11069                                                         let peer_state_mutex = per_peer_state.get(peer_node_id).unwrap();
11070                                                         let mut peer_state_lock = peer_state_mutex.lock().unwrap();
11071                                                         let peer_state = &mut *peer_state_lock;
11072                                                         if let Some(ChannelPhase::Funded(channel)) = peer_state.channel_by_id.get_mut(&previous_channel_id) {
11073                                                                 let logger = WithChannelContext::from(&args.logger, &channel.context);
11074                                                                 channel.claim_htlc_while_disconnected_dropping_mon_update(claimable_htlc.prev_hop.htlc_id, payment_preimage, &&logger);
11075                                                         }
11076                                                 }
11077                                                 if let Some(previous_hop_monitor) = args.channel_monitors.get(&claimable_htlc.prev_hop.outpoint) {
11078                                                         previous_hop_monitor.provide_payment_preimage(&payment_hash, &payment_preimage, &args.tx_broadcaster, &bounded_fee_estimator, &args.logger);
11079                                                 }
11080                                         }
11081                                         pending_events_read.push_back((events::Event::PaymentClaimed {
11082                                                 receiver_node_id,
11083                                                 payment_hash,
11084                                                 purpose: payment.purpose,
11085                                                 amount_msat: claimable_amt_msat,
11086                                                 htlcs: payment.htlcs.iter().map(events::ClaimedHTLC::from).collect(),
11087                                                 sender_intended_total_msat: payment.htlcs.first().map(|htlc| htlc.total_msat),
11088                                         }, None));
11089                                 }
11090                         }
11091                 }
11092
11093                 for (node_id, monitor_update_blocked_actions) in monitor_update_blocked_actions_per_peer.unwrap() {
11094                         if let Some(peer_state) = per_peer_state.get(&node_id) {
11095                                 for (channel_id, actions) in monitor_update_blocked_actions.iter() {
11096                                         let logger = WithContext::from(&args.logger, Some(node_id), Some(*channel_id));
11097                                         for action in actions.iter() {
11098                                                 if let MonitorUpdateCompletionAction::EmitEventAndFreeOtherChannel {
11099                                                         downstream_counterparty_and_funding_outpoint:
11100                                                                 Some((blocked_node_id, _blocked_channel_outpoint, blocked_channel_id, blocking_action)), ..
11101                                                 } = action {
11102                                                         if let Some(blocked_peer_state) = per_peer_state.get(&blocked_node_id) {
11103                                                                 let channel_id = blocked_channel_id;
11104                                                                 log_trace!(logger,
11105                                                                         "Holding the next revoke_and_ack from {} until the preimage is durably persisted in the inbound edge's ChannelMonitor",
11106                                                                         channel_id);
11107                                                                 blocked_peer_state.lock().unwrap().actions_blocking_raa_monitor_updates
11108                                                                         .entry(*channel_id)
11109                                                                         .or_insert_with(Vec::new).push(blocking_action.clone());
11110                                                         } else {
11111                                                                 // If the channel we were blocking has closed, we don't need to
11112                                                                 // worry about it - the blocked monitor update should never have
11113                                                                 // been released from the `Channel` object so it can't have
11114                                                                 // completed, and if the channel closed there's no reason to bother
11115                                                                 // anymore.
11116                                                         }
11117                                                 }
11118                                                 if let MonitorUpdateCompletionAction::FreeOtherChannelImmediately { .. } = action {
11119                                                         debug_assert!(false, "Non-event-generating channel freeing should not appear in our queue");
11120                                                 }
11121                                         }
11122                                 }
11123                                 peer_state.lock().unwrap().monitor_update_blocked_actions = monitor_update_blocked_actions;
11124                         } else {
11125                                 log_error!(WithContext::from(&args.logger, Some(node_id), None), "Got blocked actions without a per-peer-state for {}", node_id);
11126                                 return Err(DecodeError::InvalidValue);
11127                         }
11128                 }
11129
11130                 let channel_manager = ChannelManager {
11131                         chain_hash,
11132                         fee_estimator: bounded_fee_estimator,
11133                         chain_monitor: args.chain_monitor,
11134                         tx_broadcaster: args.tx_broadcaster,
11135                         router: args.router,
11136
11137                         best_block: RwLock::new(BestBlock::new(best_block_hash, best_block_height)),
11138
11139                         inbound_payment_key: expanded_inbound_key,
11140                         pending_inbound_payments: Mutex::new(pending_inbound_payments),
11141                         pending_outbound_payments: pending_outbounds,
11142                         pending_intercepted_htlcs: Mutex::new(pending_intercepted_htlcs.unwrap()),
11143
11144                         forward_htlcs: Mutex::new(forward_htlcs),
11145                         claimable_payments: Mutex::new(ClaimablePayments { claimable_payments, pending_claiming_payments: pending_claiming_payments.unwrap() }),
11146                         outbound_scid_aliases: Mutex::new(outbound_scid_aliases),
11147                         outpoint_to_peer: Mutex::new(outpoint_to_peer),
11148                         short_to_chan_info: FairRwLock::new(short_to_chan_info),
11149                         fake_scid_rand_bytes: fake_scid_rand_bytes.unwrap(),
11150
11151                         probing_cookie_secret: probing_cookie_secret.unwrap(),
11152
11153                         our_network_pubkey,
11154                         secp_ctx,
11155
11156                         highest_seen_timestamp: AtomicUsize::new(highest_seen_timestamp as usize),
11157
11158                         per_peer_state: FairRwLock::new(per_peer_state),
11159
11160                         pending_events: Mutex::new(pending_events_read),
11161                         pending_events_processor: AtomicBool::new(false),
11162                         pending_background_events: Mutex::new(pending_background_events),
11163                         total_consistency_lock: RwLock::new(()),
11164                         background_events_processed_since_startup: AtomicBool::new(false),
11165
11166                         event_persist_notifier: Notifier::new(),
11167                         needs_persist_flag: AtomicBool::new(false),
11168
11169                         funding_batch_states: Mutex::new(BTreeMap::new()),
11170
11171                         pending_offers_messages: Mutex::new(Vec::new()),
11172
11173                         pending_broadcast_messages: Mutex::new(Vec::new()),
11174
11175                         entropy_source: args.entropy_source,
11176                         node_signer: args.node_signer,
11177                         signer_provider: args.signer_provider,
11178
11179                         logger: args.logger,
11180                         default_configuration: args.default_config,
11181                 };
11182
11183                 for htlc_source in failed_htlcs.drain(..) {
11184                         let (source, payment_hash, counterparty_node_id, channel_id) = htlc_source;
11185                         let receiver = HTLCDestination::NextHopChannel { node_id: Some(counterparty_node_id), channel_id };
11186                         let reason = HTLCFailReason::from_failure_code(0x4000 | 8);
11187                         channel_manager.fail_htlc_backwards_internal(&source, &payment_hash, &reason, receiver);
11188                 }
11189
11190                 for (source, preimage, downstream_value, downstream_closed, downstream_node_id, downstream_funding, downstream_channel_id) in pending_claims_to_replay {
11191                         // We use `downstream_closed` in place of `from_onchain` here just as a guess - we
11192                         // don't remember in the `ChannelMonitor` where we got a preimage from, but if the
11193                         // channel is closed we just assume that it probably came from an on-chain claim.
11194                         channel_manager.claim_funds_internal(source, preimage, Some(downstream_value),
11195                                 downstream_closed, true, downstream_node_id, downstream_funding, downstream_channel_id);
11196                 }
11197
11198                 //TODO: Broadcast channel update for closed channels, but only after we've made a
11199                 //connection or two.
11200
11201                 Ok((best_block_hash.clone(), channel_manager))
11202         }
11203 }
11204
11205 #[cfg(test)]
11206 mod tests {
11207         use bitcoin::hashes::Hash;
11208         use bitcoin::hashes::sha256::Hash as Sha256;
11209         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
11210         use core::sync::atomic::Ordering;
11211         use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
11212         use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
11213         use crate::ln::ChannelId;
11214         use crate::ln::channelmanager::{create_recv_pending_htlc_info, HTLCForwardInfo, inbound_payment, PaymentId, PaymentSendFailure, RecipientOnionFields, InterceptId};
11215         use crate::ln::functional_test_utils::*;
11216         use crate::ln::msgs::{self, ErrorAction};
11217         use crate::ln::msgs::ChannelMessageHandler;
11218         use crate::prelude::*;
11219         use crate::routing::router::{PaymentParameters, RouteParameters, find_route};
11220         use crate::util::errors::APIError;
11221         use crate::util::ser::Writeable;
11222         use crate::util::test_utils;
11223         use crate::util::config::{ChannelConfig, ChannelConfigUpdate};
11224         use crate::sign::EntropySource;
11225
11226         #[test]
11227         fn test_notify_limits() {
11228                 // Check that a few cases which don't require the persistence of a new ChannelManager,
11229                 // indeed, do not cause the persistence of a new ChannelManager.
11230                 let chanmon_cfgs = create_chanmon_cfgs(3);
11231                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11232                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11233                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11234
11235                 // All nodes start with a persistable update pending as `create_network` connects each node
11236                 // with all other nodes to make most tests simpler.
11237                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11238                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11239                 assert!(nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11240
11241                 let mut chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11242
11243                 // We check that the channel info nodes have doesn't change too early, even though we try
11244                 // to connect messages with new values
11245                 chan.0.contents.fee_base_msat *= 2;
11246                 chan.1.contents.fee_base_msat *= 2;
11247                 let node_a_chan_info = nodes[0].node.list_channels_with_counterparty(
11248                         &nodes[1].node.get_our_node_id()).pop().unwrap();
11249                 let node_b_chan_info = nodes[1].node.list_channels_with_counterparty(
11250                         &nodes[0].node.get_our_node_id()).pop().unwrap();
11251
11252                 // The first two nodes (which opened a channel) should now require fresh persistence
11253                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11254                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11255                 // ... but the last node should not.
11256                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11257                 // After persisting the first two nodes they should no longer need fresh persistence.
11258                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11259                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11260
11261                 // Node 3, unrelated to the only channel, shouldn't care if it receives a channel_update
11262                 // about the channel.
11263                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.0);
11264                 nodes[2].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan.1);
11265                 assert!(!nodes[2].node.get_event_or_persistence_needed_future().poll_is_complete());
11266
11267                 // The nodes which are a party to the channel should also ignore messages from unrelated
11268                 // parties.
11269                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11270                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11271                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.0);
11272                 nodes[1].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan.1);
11273                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11274                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11275
11276                 // At this point the channel info given by peers should still be the same.
11277                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11278                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11279
11280                 // An earlier version of handle_channel_update didn't check the directionality of the
11281                 // update message and would always update the local fee info, even if our peer was
11282                 // (spuriously) forwarding us our own channel_update.
11283                 let as_node_one = nodes[0].node.get_our_node_id().serialize()[..] < nodes[1].node.get_our_node_id().serialize()[..];
11284                 let as_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.0 } else { &chan.1 };
11285                 let bs_update = if as_node_one == (chan.0.contents.flags & 1 == 0 /* chan.0 is from node one */) { &chan.1 } else { &chan.0 };
11286
11287                 // First deliver each peers' own message, checking that the node doesn't need to be
11288                 // persisted and that its channel info remains the same.
11289                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &as_update);
11290                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &bs_update);
11291                 assert!(!nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11292                 assert!(!nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11293                 assert_eq!(nodes[0].node.list_channels()[0], node_a_chan_info);
11294                 assert_eq!(nodes[1].node.list_channels()[0], node_b_chan_info);
11295
11296                 // Finally, deliver the other peers' message, ensuring each node needs to be persisted and
11297                 // the channel info has updated.
11298                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &bs_update);
11299                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &as_update);
11300                 assert!(nodes[0].node.get_event_or_persistence_needed_future().poll_is_complete());
11301                 assert!(nodes[1].node.get_event_or_persistence_needed_future().poll_is_complete());
11302                 assert_ne!(nodes[0].node.list_channels()[0], node_a_chan_info);
11303                 assert_ne!(nodes[1].node.list_channels()[0], node_b_chan_info);
11304         }
11305
11306         #[test]
11307         fn test_keysend_dup_hash_partial_mpp() {
11308                 // Test that a keysend payment with a duplicate hash to an existing partial MPP payment fails as
11309                 // expected.
11310                 let chanmon_cfgs = create_chanmon_cfgs(2);
11311                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11312                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11313                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11314                 create_announced_chan_between_nodes(&nodes, 0, 1);
11315
11316                 // First, send a partial MPP payment.
11317                 let (route, our_payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
11318                 let mut mpp_route = route.clone();
11319                 mpp_route.paths.push(mpp_route.paths[0].clone());
11320
11321                 let payment_id = PaymentId([42; 32]);
11322                 // Use the utility function send_payment_along_path to send the payment with MPP data which
11323                 // indicates there are more HTLCs coming.
11324                 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.
11325                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
11326                         RecipientOnionFields::secret_only(payment_secret), payment_id, &mpp_route).unwrap();
11327                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[0], &our_payment_hash,
11328                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
11329                 check_added_monitors!(nodes[0], 1);
11330                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11331                 assert_eq!(events.len(), 1);
11332                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
11333
11334                 // Next, send a keysend payment with the same payment_hash and make sure it fails.
11335                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11336                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11337                 check_added_monitors!(nodes[0], 1);
11338                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11339                 assert_eq!(events.len(), 1);
11340                 let ev = events.drain(..).next().unwrap();
11341                 let payment_event = SendEvent::from_event(ev);
11342                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11343                 check_added_monitors!(nodes[1], 0);
11344                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11345                 expect_pending_htlcs_forwardable!(nodes[1]);
11346                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
11347                 check_added_monitors!(nodes[1], 1);
11348                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11349                 assert!(updates.update_add_htlcs.is_empty());
11350                 assert!(updates.update_fulfill_htlcs.is_empty());
11351                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11352                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11353                 assert!(updates.update_fee.is_none());
11354                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11355                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11356                 expect_payment_failed!(nodes[0], our_payment_hash, true);
11357
11358                 // Send the second half of the original MPP payment.
11359                 nodes[0].node.test_send_payment_along_path(&mpp_route.paths[1], &our_payment_hash,
11360                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
11361                 check_added_monitors!(nodes[0], 1);
11362                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11363                 assert_eq!(events.len(), 1);
11364                 pass_along_path(&nodes[0], &[&nodes[1]], 200_000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), true, None);
11365
11366                 // Claim the full MPP payment. Note that we can't use a test utility like
11367                 // claim_funds_along_route because the ordering of the messages causes the second half of the
11368                 // payment to be put in the holding cell, which confuses the test utilities. So we exchange the
11369                 // lightning messages manually.
11370                 nodes[1].node.claim_funds(payment_preimage);
11371                 expect_payment_claimed!(nodes[1], our_payment_hash, 200_000);
11372                 check_added_monitors!(nodes[1], 2);
11373
11374                 let bs_first_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11375                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_first_updates.update_fulfill_htlcs[0]);
11376                 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
11377                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_updates.commitment_signed);
11378                 check_added_monitors!(nodes[0], 1);
11379                 let (as_first_raa, as_first_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11380                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
11381                 check_added_monitors!(nodes[1], 1);
11382                 let bs_second_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11383                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_first_cs);
11384                 check_added_monitors!(nodes[1], 1);
11385                 let bs_first_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11386                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_updates.update_fulfill_htlcs[0]);
11387                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_updates.commitment_signed);
11388                 check_added_monitors!(nodes[0], 1);
11389                 let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
11390                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
11391                 let as_second_updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11392                 check_added_monitors!(nodes[0], 1);
11393                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
11394                 check_added_monitors!(nodes[1], 1);
11395                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_updates.commitment_signed);
11396                 check_added_monitors!(nodes[1], 1);
11397                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
11398                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
11399                 check_added_monitors!(nodes[0], 1);
11400
11401                 // Note that successful MPP payments will generate a single PaymentSent event upon the first
11402                 // path's success and a PaymentPathSuccessful event for each path's success.
11403                 let events = nodes[0].node.get_and_clear_pending_events();
11404                 assert_eq!(events.len(), 2);
11405                 match events[0] {
11406                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11407                                 assert_eq!(payment_id, *actual_payment_id);
11408                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11409                                 assert_eq!(route.paths[0], *path);
11410                         },
11411                         _ => panic!("Unexpected event"),
11412                 }
11413                 match events[1] {
11414                         Event::PaymentPathSuccessful { payment_id: ref actual_payment_id, ref payment_hash, ref path } => {
11415                                 assert_eq!(payment_id, *actual_payment_id);
11416                                 assert_eq!(our_payment_hash, *payment_hash.as_ref().unwrap());
11417                                 assert_eq!(route.paths[0], *path);
11418                         },
11419                         _ => panic!("Unexpected event"),
11420                 }
11421         }
11422
11423         #[test]
11424         fn test_keysend_dup_payment_hash() {
11425                 do_test_keysend_dup_payment_hash(false);
11426                 do_test_keysend_dup_payment_hash(true);
11427         }
11428
11429         fn do_test_keysend_dup_payment_hash(accept_mpp_keysend: bool) {
11430                 // (1): Test that a keysend payment with a duplicate payment hash to an existing pending
11431                 //      outbound regular payment fails as expected.
11432                 // (2): Test that a regular payment with a duplicate payment hash to an existing keysend payment
11433                 //      fails as expected.
11434                 // (3): Test that a keysend payment with a duplicate payment hash to an existing keysend
11435                 //      payment fails as expected. When `accept_mpp_keysend` is false, this tests that we
11436                 //      reject MPP keysend payments, since in this case where the payment has no payment
11437                 //      secret, a keysend payment with a duplicate hash is basically an MPP keysend. If
11438                 //      `accept_mpp_keysend` is true, this tests that we only accept MPP keysends with
11439                 //      payment secrets and reject otherwise.
11440                 let chanmon_cfgs = create_chanmon_cfgs(2);
11441                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11442                 let mut mpp_keysend_cfg = test_default_channel_config();
11443                 mpp_keysend_cfg.accept_mpp_keysend = accept_mpp_keysend;
11444                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(mpp_keysend_cfg)]);
11445                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11446                 create_announced_chan_between_nodes(&nodes, 0, 1);
11447                 let scorer = test_utils::TestScorer::new();
11448                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11449
11450                 // To start (1), send a regular payment but don't claim it.
11451                 let expected_route = [&nodes[1]];
11452                 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &expected_route, 100_000);
11453
11454                 // Next, attempt a keysend payment and make sure it fails.
11455                 let route_params = RouteParameters::from_payment_params_and_value(
11456                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(),
11457                         TEST_FINAL_CLTV, false), 100_000);
11458                 let route = find_route(
11459                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11460                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11461                 ).unwrap();
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                 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
11473                 // fails), the second will process the resulting failure and fail the HTLC backward
11474                 expect_pending_htlcs_forwardable!(nodes[1]);
11475                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11476                 check_added_monitors!(nodes[1], 1);
11477                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11478                 assert!(updates.update_add_htlcs.is_empty());
11479                 assert!(updates.update_fulfill_htlcs.is_empty());
11480                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11481                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11482                 assert!(updates.update_fee.is_none());
11483                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11484                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11485                 expect_payment_failed!(nodes[0], payment_hash, true);
11486
11487                 // Finally, claim the original payment.
11488                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11489
11490                 // To start (2), send a keysend payment but don't claim it.
11491                 let payment_preimage = PaymentPreimage([42; 32]);
11492                 let route = find_route(
11493                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11494                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11495                 ).unwrap();
11496                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11497                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_preimage.0)).unwrap();
11498                 check_added_monitors!(nodes[0], 1);
11499                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11500                 assert_eq!(events.len(), 1);
11501                 let event = events.pop().unwrap();
11502                 let path = vec![&nodes[1]];
11503                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11504
11505                 // Next, attempt a regular payment and make sure it fails.
11506                 let payment_secret = PaymentSecret([43; 32]);
11507                 nodes[0].node.send_payment_with_route(&route, payment_hash,
11508                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
11509                 check_added_monitors!(nodes[0], 1);
11510                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11511                 assert_eq!(events.len(), 1);
11512                 let ev = events.drain(..).next().unwrap();
11513                 let payment_event = SendEvent::from_event(ev);
11514                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11515                 check_added_monitors!(nodes[1], 0);
11516                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11517                 expect_pending_htlcs_forwardable!(nodes[1]);
11518                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11519                 check_added_monitors!(nodes[1], 1);
11520                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11521                 assert!(updates.update_add_htlcs.is_empty());
11522                 assert!(updates.update_fulfill_htlcs.is_empty());
11523                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11524                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11525                 assert!(updates.update_fee.is_none());
11526                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11527                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11528                 expect_payment_failed!(nodes[0], payment_hash, true);
11529
11530                 // Finally, succeed the keysend payment.
11531                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11532
11533                 // To start (3), send a keysend payment but don't claim it.
11534                 let payment_id_1 = PaymentId([44; 32]);
11535                 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11536                         RecipientOnionFields::spontaneous_empty(), payment_id_1).unwrap();
11537                 check_added_monitors!(nodes[0], 1);
11538                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11539                 assert_eq!(events.len(), 1);
11540                 let event = events.pop().unwrap();
11541                 let path = vec![&nodes[1]];
11542                 pass_along_path(&nodes[0], &path, 100_000, payment_hash, None, event, true, Some(payment_preimage));
11543
11544                 // Next, attempt a keysend payment and make sure it fails.
11545                 let route_params = RouteParameters::from_payment_params_and_value(
11546                         PaymentParameters::for_keysend(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV, false),
11547                         100_000
11548                 );
11549                 let route = find_route(
11550                         &nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph,
11551                         None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11552                 ).unwrap();
11553                 let payment_id_2 = PaymentId([45; 32]);
11554                 nodes[0].node.send_spontaneous_payment(&route, Some(payment_preimage),
11555                         RecipientOnionFields::spontaneous_empty(), payment_id_2).unwrap();
11556                 check_added_monitors!(nodes[0], 1);
11557                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
11558                 assert_eq!(events.len(), 1);
11559                 let ev = events.drain(..).next().unwrap();
11560                 let payment_event = SendEvent::from_event(ev);
11561                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
11562                 check_added_monitors!(nodes[1], 0);
11563                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
11564                 expect_pending_htlcs_forwardable!(nodes[1]);
11565                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
11566                 check_added_monitors!(nodes[1], 1);
11567                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
11568                 assert!(updates.update_add_htlcs.is_empty());
11569                 assert!(updates.update_fulfill_htlcs.is_empty());
11570                 assert_eq!(updates.update_fail_htlcs.len(), 1);
11571                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11572                 assert!(updates.update_fee.is_none());
11573                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
11574                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
11575                 expect_payment_failed!(nodes[0], payment_hash, true);
11576
11577                 // Finally, claim the original payment.
11578                 claim_payment(&nodes[0], &expected_route, payment_preimage);
11579         }
11580
11581         #[test]
11582         fn test_keysend_hash_mismatch() {
11583                 // Test that if we receive a keysend `update_add_htlc` msg, we fail as expected if the keysend
11584                 // preimage doesn't match the msg's payment hash.
11585                 let chanmon_cfgs = create_chanmon_cfgs(2);
11586                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11587                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11588                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11589
11590                 let payer_pubkey = nodes[0].node.get_our_node_id();
11591                 let payee_pubkey = nodes[1].node.get_our_node_id();
11592
11593                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11594                 let route_params = RouteParameters::from_payment_params_and_value(
11595                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11596                 let network_graph = nodes[0].network_graph;
11597                 let first_hops = nodes[0].node.list_usable_channels();
11598                 let scorer = test_utils::TestScorer::new();
11599                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11600                 let route = find_route(
11601                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11602                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11603                 ).unwrap();
11604
11605                 let test_preimage = PaymentPreimage([42; 32]);
11606                 let mismatch_payment_hash = PaymentHash([43; 32]);
11607                 let session_privs = nodes[0].node.test_add_new_pending_payment(mismatch_payment_hash,
11608                         RecipientOnionFields::spontaneous_empty(), PaymentId(mismatch_payment_hash.0), &route).unwrap();
11609                 nodes[0].node.test_send_payment_internal(&route, mismatch_payment_hash,
11610                         RecipientOnionFields::spontaneous_empty(), Some(test_preimage), PaymentId(mismatch_payment_hash.0), None, session_privs).unwrap();
11611                 check_added_monitors!(nodes[0], 1);
11612
11613                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11614                 assert_eq!(updates.update_add_htlcs.len(), 1);
11615                 assert!(updates.update_fulfill_htlcs.is_empty());
11616                 assert!(updates.update_fail_htlcs.is_empty());
11617                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11618                 assert!(updates.update_fee.is_none());
11619                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11620
11621                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Payment preimage didn't match payment hash", 1);
11622         }
11623
11624         #[test]
11625         fn test_keysend_msg_with_secret_err() {
11626                 // Test that we error as expected if we receive a keysend payment that includes a payment
11627                 // secret when we don't support MPP keysend.
11628                 let mut reject_mpp_keysend_cfg = test_default_channel_config();
11629                 reject_mpp_keysend_cfg.accept_mpp_keysend = false;
11630                 let chanmon_cfgs = create_chanmon_cfgs(2);
11631                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11632                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(reject_mpp_keysend_cfg)]);
11633                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11634
11635                 let payer_pubkey = nodes[0].node.get_our_node_id();
11636                 let payee_pubkey = nodes[1].node.get_our_node_id();
11637
11638                 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
11639                 let route_params = RouteParameters::from_payment_params_and_value(
11640                         PaymentParameters::for_keysend(payee_pubkey, 40, false), 10_000);
11641                 let network_graph = nodes[0].network_graph;
11642                 let first_hops = nodes[0].node.list_usable_channels();
11643                 let scorer = test_utils::TestScorer::new();
11644                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
11645                 let route = find_route(
11646                         &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
11647                         nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes
11648                 ).unwrap();
11649
11650                 let test_preimage = PaymentPreimage([42; 32]);
11651                 let test_secret = PaymentSecret([43; 32]);
11652                 let payment_hash = PaymentHash(Sha256::hash(&test_preimage.0).to_byte_array());
11653                 let session_privs = nodes[0].node.test_add_new_pending_payment(payment_hash,
11654                         RecipientOnionFields::secret_only(test_secret), PaymentId(payment_hash.0), &route).unwrap();
11655                 nodes[0].node.test_send_payment_internal(&route, payment_hash,
11656                         RecipientOnionFields::secret_only(test_secret), Some(test_preimage),
11657                         PaymentId(payment_hash.0), None, session_privs).unwrap();
11658                 check_added_monitors!(nodes[0], 1);
11659
11660                 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
11661                 assert_eq!(updates.update_add_htlcs.len(), 1);
11662                 assert!(updates.update_fulfill_htlcs.is_empty());
11663                 assert!(updates.update_fail_htlcs.is_empty());
11664                 assert!(updates.update_fail_malformed_htlcs.is_empty());
11665                 assert!(updates.update_fee.is_none());
11666                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
11667
11668                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "We don't support MPP keysend payments", 1);
11669         }
11670
11671         #[test]
11672         fn test_multi_hop_missing_secret() {
11673                 let chanmon_cfgs = create_chanmon_cfgs(4);
11674                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
11675                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
11676                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
11677
11678                 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
11679                 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
11680                 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
11681                 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
11682
11683                 // Marshall an MPP route.
11684                 let (mut route, payment_hash, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
11685                 let path = route.paths[0].clone();
11686                 route.paths.push(path);
11687                 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
11688                 route.paths[0].hops[0].short_channel_id = chan_1_id;
11689                 route.paths[0].hops[1].short_channel_id = chan_3_id;
11690                 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
11691                 route.paths[1].hops[0].short_channel_id = chan_2_id;
11692                 route.paths[1].hops[1].short_channel_id = chan_4_id;
11693
11694                 match nodes[0].node.send_payment_with_route(&route, payment_hash,
11695                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0))
11696                 .unwrap_err() {
11697                         PaymentSendFailure::ParameterError(APIError::APIMisuseError { ref err }) => {
11698                                 assert!(regex::Regex::new(r"Payment secret is required for multi-path payments").unwrap().is_match(err))
11699                         },
11700                         _ => panic!("unexpected error")
11701                 }
11702         }
11703
11704         #[test]
11705         fn test_channel_update_cached() {
11706                 let chanmon_cfgs = create_chanmon_cfgs(3);
11707                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11708                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11709                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11710
11711                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11712
11713                 nodes[0].node.force_close_channel_with_peer(&chan.2, &nodes[1].node.get_our_node_id(), None, true).unwrap();
11714                 check_added_monitors!(nodes[0], 1);
11715                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11716
11717                 // Confirm that the channel_update was not sent immediately to node[1] but was cached.
11718                 let node_1_events = nodes[1].node.get_and_clear_pending_msg_events();
11719                 assert_eq!(node_1_events.len(), 0);
11720
11721                 {
11722                         // Assert that ChannelUpdate message has been added to node[0] pending broadcast messages
11723                         let pending_broadcast_messages= nodes[0].node.pending_broadcast_messages.lock().unwrap();
11724                         assert_eq!(pending_broadcast_messages.len(), 1);
11725                 }
11726
11727                 // Test that we do not retrieve the pending broadcast messages when we are not connected to any peer
11728                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11729                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11730
11731                 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
11732                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11733
11734                 let node_0_events = nodes[0].node.get_and_clear_pending_msg_events();
11735                 assert_eq!(node_0_events.len(), 0);
11736
11737                 // Now we reconnect to a peer
11738                 nodes[0].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init {
11739                         features: nodes[2].node.init_features(), networks: None, remote_network_address: None
11740                 }, true).unwrap();
11741                 nodes[2].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
11742                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
11743                 }, false).unwrap();
11744
11745                 // Confirm that get_and_clear_pending_msg_events correctly captures pending broadcast messages
11746                 let node_0_events = nodes[0].node.get_and_clear_pending_msg_events();
11747                 assert_eq!(node_0_events.len(), 1);
11748                 match &node_0_events[0] {
11749                         MessageSendEvent::BroadcastChannelUpdate { .. } => (),
11750                         _ => panic!("Unexpected event"),
11751                 }
11752                 {
11753                         // Assert that ChannelUpdate message has been cleared from nodes[0] pending broadcast messages
11754                         let pending_broadcast_messages= nodes[0].node.pending_broadcast_messages.lock().unwrap();
11755                         assert_eq!(pending_broadcast_messages.len(), 0);
11756                 }
11757         }
11758
11759         #[test]
11760         fn test_drop_disconnected_peers_when_removing_channels() {
11761                 let chanmon_cfgs = create_chanmon_cfgs(2);
11762                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11763                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11764                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11765
11766                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
11767
11768                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
11769                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
11770
11771                 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
11772                 check_closed_broadcast!(nodes[0], true);
11773                 check_added_monitors!(nodes[0], 1);
11774                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
11775
11776                 {
11777                         // Assert that nodes[1] is awaiting removal for nodes[0] once nodes[1] has been
11778                         // disconnected and the channel between has been force closed.
11779                         let nodes_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
11780                         // Assert that nodes[1] isn't removed before `timer_tick_occurred` has been executed.
11781                         assert_eq!(nodes_0_per_peer_state.len(), 1);
11782                         assert!(nodes_0_per_peer_state.get(&nodes[1].node.get_our_node_id()).is_some());
11783                 }
11784
11785                 nodes[0].node.timer_tick_occurred();
11786
11787                 {
11788                         // Assert that nodes[1] has now been removed.
11789                         assert_eq!(nodes[0].node.per_peer_state.read().unwrap().len(), 0);
11790                 }
11791         }
11792
11793         #[test]
11794         fn bad_inbound_payment_hash() {
11795                 // Add coverage for checking that a user-provided payment hash matches the payment secret.
11796                 let chanmon_cfgs = create_chanmon_cfgs(2);
11797                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11798                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11799                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11800
11801                 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[0]);
11802                 let payment_data = msgs::FinalOnionHopData {
11803                         payment_secret,
11804                         total_msat: 100_000,
11805                 };
11806
11807                 // Ensure that if the payment hash given to `inbound_payment::verify` differs from the original,
11808                 // payment verification fails as expected.
11809                 let mut bad_payment_hash = payment_hash.clone();
11810                 bad_payment_hash.0[0] += 1;
11811                 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) {
11812                         Ok(_) => panic!("Unexpected ok"),
11813                         Err(()) => {
11814                                 nodes[0].logger.assert_log_contains("lightning::ln::inbound_payment", "Failing HTLC with user-generated payment_hash", 1);
11815                         }
11816                 }
11817
11818                 // Check that using the original payment hash succeeds.
11819                 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());
11820         }
11821
11822         #[test]
11823         fn test_outpoint_to_peer_coverage() {
11824                 // Test that the `ChannelManager:outpoint_to_peer` contains channels which have been assigned
11825                 // a `channel_id` (i.e. have had the funding tx created), and that they are removed once
11826                 // the channel is successfully closed.
11827                 let chanmon_cfgs = create_chanmon_cfgs(2);
11828                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11829                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
11830                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11831
11832                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
11833                 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11834                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
11835                 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
11836                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
11837
11838                 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
11839                 let channel_id = ChannelId::from_bytes(tx.txid().to_byte_array());
11840                 {
11841                         // Ensure that the `outpoint_to_peer` map is empty until either party has received the
11842                         // funding transaction, and have the real `channel_id`.
11843                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11844                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11845                 }
11846
11847                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
11848                 {
11849                         // Assert that `nodes[0]`'s `outpoint_to_peer` map is populated with the channel as soon as
11850                         // as it has the funding transaction.
11851                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11852                         assert_eq!(nodes_0_lock.len(), 1);
11853                         assert!(nodes_0_lock.contains_key(&funding_output));
11854                 }
11855
11856                 assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11857
11858                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
11859
11860                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
11861                 {
11862                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11863                         assert_eq!(nodes_0_lock.len(), 1);
11864                         assert!(nodes_0_lock.contains_key(&funding_output));
11865                 }
11866                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11867
11868                 {
11869                         // Assert that `nodes[1]`'s `outpoint_to_peer` map is populated with the channel as
11870                         // soon as it has the funding transaction.
11871                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11872                         assert_eq!(nodes_1_lock.len(), 1);
11873                         assert!(nodes_1_lock.contains_key(&funding_output));
11874                 }
11875                 check_added_monitors!(nodes[1], 1);
11876                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11877                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
11878                 check_added_monitors!(nodes[0], 1);
11879                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
11880                 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
11881                 let (announcement, nodes_0_update, nodes_1_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
11882                 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &nodes_0_update, &nodes_1_update);
11883
11884                 nodes[0].node.close_channel(&channel_id, &nodes[1].node.get_our_node_id()).unwrap();
11885                 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()));
11886                 let nodes_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
11887                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &nodes_1_shutdown);
11888
11889                 let closing_signed_node_0 = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
11890                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0);
11891                 {
11892                         // Assert that the channel is kept in the `outpoint_to_peer` map for both nodes until the
11893                         // channel can be fully closed by both parties (i.e. no outstanding htlcs exists, the
11894                         // fee for the closing transaction has been negotiated and the parties has the other
11895                         // party's signature for the fee negotiated closing transaction.)
11896                         let nodes_0_lock = nodes[0].node.outpoint_to_peer.lock().unwrap();
11897                         assert_eq!(nodes_0_lock.len(), 1);
11898                         assert!(nodes_0_lock.contains_key(&funding_output));
11899                 }
11900
11901                 {
11902                         // At this stage, `nodes[1]` has proposed a fee for the closing transaction in the
11903                         // `handle_closing_signed` call above. As `nodes[1]` has not yet received the signature
11904                         // from `nodes[0]` for the closing transaction with the proposed fee, the channel is
11905                         // kept in the `nodes[1]`'s `outpoint_to_peer` map.
11906                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11907                         assert_eq!(nodes_1_lock.len(), 1);
11908                         assert!(nodes_1_lock.contains_key(&funding_output));
11909                 }
11910
11911                 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()));
11912                 {
11913                         // `nodes[0]` accepts `nodes[1]`'s proposed fee for the closing transaction, and
11914                         // therefore has all it needs to fully close the channel (both signatures for the
11915                         // closing transaction).
11916                         // Assert that the channel is removed from `nodes[0]`'s `outpoint_to_peer` map as it can be
11917                         // fully closed by `nodes[0]`.
11918                         assert_eq!(nodes[0].node.outpoint_to_peer.lock().unwrap().len(), 0);
11919
11920                         // Assert that the channel is still in `nodes[1]`'s  `outpoint_to_peer` map, as `nodes[1]`
11921                         // doesn't have `nodes[0]`'s signature for the closing transaction yet.
11922                         let nodes_1_lock = nodes[1].node.outpoint_to_peer.lock().unwrap();
11923                         assert_eq!(nodes_1_lock.len(), 1);
11924                         assert!(nodes_1_lock.contains_key(&funding_output));
11925                 }
11926
11927                 let (_nodes_0_update, closing_signed_node_0) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
11928
11929                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &closing_signed_node_0.unwrap());
11930                 {
11931                         // Assert that the channel has now been removed from both parties `outpoint_to_peer` map once
11932                         // they both have everything required to fully close the channel.
11933                         assert_eq!(nodes[1].node.outpoint_to_peer.lock().unwrap().len(), 0);
11934                 }
11935                 let (_nodes_1_update, _none) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
11936
11937                 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 1000000);
11938                 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 1000000);
11939         }
11940
11941         fn check_not_connected_to_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11942                 let expected_message = format!("Not connected to node: {}", expected_public_key);
11943                 check_api_error_message(expected_message, res_err)
11944         }
11945
11946         fn check_unkown_peer_error<T>(res_err: Result<T, APIError>, expected_public_key: PublicKey) {
11947                 let expected_message = format!("Can't find a peer matching the passed counterparty node_id {}", expected_public_key);
11948                 check_api_error_message(expected_message, res_err)
11949         }
11950
11951         fn check_channel_unavailable_error<T>(res_err: Result<T, APIError>, expected_channel_id: ChannelId, peer_node_id: PublicKey) {
11952                 let expected_message = format!("Channel with id {} not found for the passed counterparty node_id {}", expected_channel_id, peer_node_id);
11953                 check_api_error_message(expected_message, res_err)
11954         }
11955
11956         fn check_api_misuse_error<T>(res_err: Result<T, APIError>) {
11957                 let expected_message = "No such channel awaiting to be accepted.".to_string();
11958                 check_api_error_message(expected_message, res_err)
11959         }
11960
11961         fn check_api_error_message<T>(expected_err_message: String, res_err: Result<T, APIError>) {
11962                 match res_err {
11963                         Err(APIError::APIMisuseError { err }) => {
11964                                 assert_eq!(err, expected_err_message);
11965                         },
11966                         Err(APIError::ChannelUnavailable { err }) => {
11967                                 assert_eq!(err, expected_err_message);
11968                         },
11969                         Ok(_) => panic!("Unexpected Ok"),
11970                         Err(_) => panic!("Unexpected Error"),
11971                 }
11972         }
11973
11974         #[test]
11975         fn test_api_calls_with_unkown_counterparty_node() {
11976                 // Tests that our API functions that expects a `counterparty_node_id` as input, behaves as
11977                 // expected if the `counterparty_node_id` is an unkown peer in the
11978                 // `ChannelManager::per_peer_state` map.
11979                 let chanmon_cfg = create_chanmon_cfgs(2);
11980                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
11981                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
11982                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
11983
11984                 // Dummy values
11985                 let channel_id = ChannelId::from_bytes([4; 32]);
11986                 let unkown_public_key = PublicKey::from_secret_key(&Secp256k1::signing_only(), &SecretKey::from_slice(&[42; 32]).unwrap());
11987                 let intercept_id = InterceptId([0; 32]);
11988
11989                 // Test the API functions.
11990                 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);
11991
11992                 check_unkown_peer_error(nodes[0].node.accept_inbound_channel(&channel_id, &unkown_public_key, 42), unkown_public_key);
11993
11994                 check_unkown_peer_error(nodes[0].node.close_channel(&channel_id, &unkown_public_key), unkown_public_key);
11995
11996                 check_unkown_peer_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &unkown_public_key), unkown_public_key);
11997
11998                 check_unkown_peer_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &unkown_public_key), unkown_public_key);
11999
12000                 check_unkown_peer_error(nodes[0].node.forward_intercepted_htlc(intercept_id, &channel_id, unkown_public_key, 1_000_000), unkown_public_key);
12001
12002                 check_unkown_peer_error(nodes[0].node.update_channel_config(&unkown_public_key, &[channel_id], &ChannelConfig::default()), unkown_public_key);
12003         }
12004
12005         #[test]
12006         fn test_api_calls_with_unavailable_channel() {
12007                 // Tests that our API functions that expects a `counterparty_node_id` and a `channel_id`
12008                 // as input, behaves as expected if the `counterparty_node_id` is a known peer in the
12009                 // `ChannelManager::per_peer_state` map, but the peer state doesn't contain a channel with
12010                 // the given `channel_id`.
12011                 let chanmon_cfg = create_chanmon_cfgs(2);
12012                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12013                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
12014                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12015
12016                 let counterparty_node_id = nodes[1].node.get_our_node_id();
12017
12018                 // Dummy values
12019                 let channel_id = ChannelId::from_bytes([4; 32]);
12020
12021                 // Test the API functions.
12022                 check_api_misuse_error(nodes[0].node.accept_inbound_channel(&channel_id, &counterparty_node_id, 42));
12023
12024                 check_channel_unavailable_error(nodes[0].node.close_channel(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
12025
12026                 check_channel_unavailable_error(nodes[0].node.force_close_broadcasting_latest_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
12027
12028                 check_channel_unavailable_error(nodes[0].node.force_close_without_broadcasting_txn(&channel_id, &counterparty_node_id), channel_id, counterparty_node_id);
12029
12030                 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);
12031
12032                 check_channel_unavailable_error(nodes[0].node.update_channel_config(&counterparty_node_id, &[channel_id], &ChannelConfig::default()), channel_id, counterparty_node_id);
12033         }
12034
12035         #[test]
12036         fn test_connection_limiting() {
12037                 // Test that we limit un-channel'd peers and un-funded channels properly.
12038                 let chanmon_cfgs = create_chanmon_cfgs(2);
12039                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12040                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
12041                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12042
12043                 // Note that create_network connects the nodes together for us
12044
12045                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12046                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12047
12048                 let mut funding_tx = None;
12049                 for idx in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
12050                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12051                         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12052
12053                         if idx == 0 {
12054                                 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
12055                                 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
12056                                 funding_tx = Some(tx.clone());
12057                                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
12058                                 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
12059
12060                                 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
12061                                 check_added_monitors!(nodes[1], 1);
12062                                 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
12063
12064                                 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
12065
12066                                 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
12067                                 check_added_monitors!(nodes[0], 1);
12068                                 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
12069                         }
12070                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12071                 }
12072
12073                 // A MAX_UNFUNDED_CHANS_PER_PEER + 1 channel will be summarily rejected
12074                 open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12075                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12076                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12077                         open_channel_msg.temporary_channel_id);
12078
12079                 // Further, because all of our channels with nodes[0] are inbound, and none of them funded,
12080                 // it doesn't count as a "protected" peer, i.e. it counts towards the MAX_NO_CHANNEL_PEERS
12081                 // limit.
12082                 let mut peer_pks = Vec::with_capacity(super::MAX_NO_CHANNEL_PEERS);
12083                 for _ in 1..super::MAX_NO_CHANNEL_PEERS {
12084                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12085                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12086                         peer_pks.push(random_pk);
12087                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
12088                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12089                         }, true).unwrap();
12090                 }
12091                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12092                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12093                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12094                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12095                 }, true).unwrap_err();
12096
12097                 // Also importantly, because nodes[0] isn't "protected", we will refuse a reconnection from
12098                 // them if we have too many un-channel'd peers.
12099                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12100                 let chan_closed_events = nodes[1].node.get_and_clear_pending_events();
12101                 assert_eq!(chan_closed_events.len(), super::MAX_UNFUNDED_CHANS_PER_PEER - 1);
12102                 for ev in chan_closed_events {
12103                         if let Event::ChannelClosed { .. } = ev { } else { panic!(); }
12104                 }
12105                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12106                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12107                 }, true).unwrap();
12108                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12109                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12110                 }, true).unwrap_err();
12111
12112                 // but of course if the connection is outbound its allowed...
12113                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12114                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12115                 }, false).unwrap();
12116                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12117
12118                 // Now nodes[0] is disconnected but still has a pending, un-funded channel lying around.
12119                 // Even though we accept one more connection from new peers, we won't actually let them
12120                 // open channels.
12121                 assert!(peer_pks.len() > super::MAX_UNFUNDED_CHANNEL_PEERS - 1);
12122                 for i in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12123                         nodes[1].node.handle_open_channel(&peer_pks[i], &open_channel_msg);
12124                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, peer_pks[i]);
12125                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12126                 }
12127                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12128                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12129                         open_channel_msg.temporary_channel_id);
12130
12131                 // Of course, however, outbound channels are always allowed
12132                 nodes[1].node.create_channel(last_random_pk, 100_000, 0, 42, None, None).unwrap();
12133                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, last_random_pk);
12134
12135                 // If we fund the first channel, nodes[0] has a live on-chain channel with us, it is now
12136                 // "protected" and can connect again.
12137                 mine_transaction(&nodes[1], funding_tx.as_ref().unwrap());
12138                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12139                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12140                 }, true).unwrap();
12141                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
12142
12143                 // Further, because the first channel was funded, we can open another channel with
12144                 // last_random_pk.
12145                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12146                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12147         }
12148
12149         #[test]
12150         fn test_outbound_chans_unlimited() {
12151                 // Test that we never refuse an outbound channel even if a peer is unfuned-channel-limited
12152                 let chanmon_cfgs = create_chanmon_cfgs(2);
12153                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12154                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
12155                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12156
12157                 // Note that create_network connects the nodes together for us
12158
12159                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12160                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12161
12162                 for _ in 0..super::MAX_UNFUNDED_CHANS_PER_PEER {
12163                         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12164                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12165                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12166                 }
12167
12168                 // Once we have MAX_UNFUNDED_CHANS_PER_PEER unfunded channels, new inbound channels will be
12169                 // rejected.
12170                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12171                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12172                         open_channel_msg.temporary_channel_id);
12173
12174                 // but we can still open an outbound channel.
12175                 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12176                 get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
12177
12178                 // but even with such an outbound channel, additional inbound channels will still fail.
12179                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12180                 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
12181                         open_channel_msg.temporary_channel_id);
12182         }
12183
12184         #[test]
12185         fn test_0conf_limiting() {
12186                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12187                 // flag set and (sometimes) accept channels as 0conf.
12188                 let chanmon_cfgs = create_chanmon_cfgs(2);
12189                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12190                 let mut settings = test_default_channel_config();
12191                 settings.manually_accept_inbound_channels = true;
12192                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(settings)]);
12193                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12194
12195                 // Note that create_network connects the nodes together for us
12196
12197                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12198                 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12199
12200                 // First, get us up to MAX_UNFUNDED_CHANNEL_PEERS so we can test at the edge
12201                 for _ in 0..super::MAX_UNFUNDED_CHANNEL_PEERS - 1 {
12202                         let random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12203                                 &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12204                         nodes[1].node.peer_connected(&random_pk, &msgs::Init {
12205                                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12206                         }, true).unwrap();
12207
12208                         nodes[1].node.handle_open_channel(&random_pk, &open_channel_msg);
12209                         let events = nodes[1].node.get_and_clear_pending_events();
12210                         match events[0] {
12211                                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
12212                                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &random_pk, 23).unwrap();
12213                                 }
12214                                 _ => panic!("Unexpected event"),
12215                         }
12216                         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, random_pk);
12217                         open_channel_msg.temporary_channel_id = ChannelId::temporary_from_entropy_source(&nodes[0].keys_manager);
12218                 }
12219
12220                 // If we try to accept a channel from another peer non-0conf it will fail.
12221                 let last_random_pk = PublicKey::from_secret_key(&nodes[0].node.secp_ctx,
12222                         &SecretKey::from_slice(&nodes[1].keys_manager.get_secure_random_bytes()).unwrap());
12223                 nodes[1].node.peer_connected(&last_random_pk, &msgs::Init {
12224                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12225                 }, true).unwrap();
12226                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12227                 let events = nodes[1].node.get_and_clear_pending_events();
12228                 match events[0] {
12229                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12230                                 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &last_random_pk, 23) {
12231                                         Err(APIError::APIMisuseError { err }) =>
12232                                                 assert_eq!(err, "Too many peers with unfunded channels, refusing to accept new ones"),
12233                                         _ => panic!(),
12234                                 }
12235                         }
12236                         _ => panic!("Unexpected event"),
12237                 }
12238                 assert_eq!(get_err_msg(&nodes[1], &last_random_pk).channel_id,
12239                         open_channel_msg.temporary_channel_id);
12240
12241                 // ...however if we accept the same channel 0conf it should work just fine.
12242                 nodes[1].node.handle_open_channel(&last_random_pk, &open_channel_msg);
12243                 let events = nodes[1].node.get_and_clear_pending_events();
12244                 match events[0] {
12245                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12246                                 nodes[1].node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &last_random_pk, 23).unwrap();
12247                         }
12248                         _ => panic!("Unexpected event"),
12249                 }
12250                 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, last_random_pk);
12251         }
12252
12253         #[test]
12254         fn reject_excessively_underpaying_htlcs() {
12255                 let chanmon_cfg = create_chanmon_cfgs(1);
12256                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12257                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12258                 let node = create_network(1, &node_cfg, &node_chanmgr);
12259                 let sender_intended_amt_msat = 100;
12260                 let extra_fee_msat = 10;
12261                 let hop_data = msgs::InboundOnionPayload::Receive {
12262                         sender_intended_htlc_amt_msat: 100,
12263                         cltv_expiry_height: 42,
12264                         payment_metadata: None,
12265                         keysend_preimage: None,
12266                         payment_data: Some(msgs::FinalOnionHopData {
12267                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12268                         }),
12269                         custom_tlvs: Vec::new(),
12270                 };
12271                 // Check that if the amount we received + the penultimate hop extra fee is less than the sender
12272                 // intended amount, we fail the payment.
12273                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12274                 if let Err(crate::ln::channelmanager::InboundHTLCErr { err_code, .. }) =
12275                         create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12276                                 sender_intended_amt_msat - extra_fee_msat - 1, 42, None, true, Some(extra_fee_msat),
12277                                 current_height, node[0].node.default_configuration.accept_mpp_keysend)
12278                 {
12279                         assert_eq!(err_code, 19);
12280                 } else { panic!(); }
12281
12282                 // If amt_received + extra_fee is equal to the sender intended amount, we're fine.
12283                 let hop_data = msgs::InboundOnionPayload::Receive { // This is the same payload as above, InboundOnionPayload doesn't implement Clone
12284                         sender_intended_htlc_amt_msat: 100,
12285                         cltv_expiry_height: 42,
12286                         payment_metadata: None,
12287                         keysend_preimage: None,
12288                         payment_data: Some(msgs::FinalOnionHopData {
12289                                 payment_secret: PaymentSecret([0; 32]), total_msat: sender_intended_amt_msat,
12290                         }),
12291                         custom_tlvs: Vec::new(),
12292                 };
12293                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12294                 assert!(create_recv_pending_htlc_info(hop_data, [0; 32], PaymentHash([0; 32]),
12295                         sender_intended_amt_msat - extra_fee_msat, 42, None, true, Some(extra_fee_msat),
12296                         current_height, node[0].node.default_configuration.accept_mpp_keysend).is_ok());
12297         }
12298
12299         #[test]
12300         fn test_final_incorrect_cltv(){
12301                 let chanmon_cfg = create_chanmon_cfgs(1);
12302                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12303                 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
12304                 let node = create_network(1, &node_cfg, &node_chanmgr);
12305
12306                 let current_height: u32 = node[0].node.best_block.read().unwrap().height();
12307                 let result = create_recv_pending_htlc_info(msgs::InboundOnionPayload::Receive {
12308                         sender_intended_htlc_amt_msat: 100,
12309                         cltv_expiry_height: 22,
12310                         payment_metadata: None,
12311                         keysend_preimage: None,
12312                         payment_data: Some(msgs::FinalOnionHopData {
12313                                 payment_secret: PaymentSecret([0; 32]), total_msat: 100,
12314                         }),
12315                         custom_tlvs: Vec::new(),
12316                 }, [0; 32], PaymentHash([0; 32]), 100, 23, None, true, None, current_height,
12317                         node[0].node.default_configuration.accept_mpp_keysend);
12318
12319                 // Should not return an error as this condition:
12320                 // https://github.com/lightning/bolts/blob/4dcc377209509b13cf89a4b91fde7d478f5b46d8/04-onion-routing.md?plain=1#L334
12321                 // is not satisfied.
12322                 assert!(result.is_ok());
12323         }
12324
12325         #[test]
12326         fn test_inbound_anchors_manual_acceptance() {
12327                 // Tests that we properly limit inbound channels when we have the manual-channel-acceptance
12328                 // flag set and (sometimes) accept channels as 0conf.
12329                 let mut anchors_cfg = test_default_channel_config();
12330                 anchors_cfg.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12331
12332                 let mut anchors_manual_accept_cfg = anchors_cfg.clone();
12333                 anchors_manual_accept_cfg.manually_accept_inbound_channels = true;
12334
12335                 let chanmon_cfgs = create_chanmon_cfgs(3);
12336                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
12337                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs,
12338                         &[Some(anchors_cfg.clone()), Some(anchors_cfg.clone()), Some(anchors_manual_accept_cfg.clone())]);
12339                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
12340
12341                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
12342                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12343
12344                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12345                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12346                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
12347                 match &msg_events[0] {
12348                         MessageSendEvent::HandleError { node_id, action } => {
12349                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
12350                                 match action {
12351                                         ErrorAction::SendErrorMessage { msg } =>
12352                                                 assert_eq!(msg.data, "No channels with anchor outputs accepted".to_owned()),
12353                                         _ => panic!("Unexpected error action"),
12354                                 }
12355                         }
12356                         _ => panic!("Unexpected event"),
12357                 }
12358
12359                 nodes[2].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12360                 let events = nodes[2].node.get_and_clear_pending_events();
12361                 match events[0] {
12362                         Event::OpenChannelRequest { temporary_channel_id, .. } =>
12363                                 nodes[2].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap(),
12364                         _ => panic!("Unexpected event"),
12365                 }
12366                 get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
12367         }
12368
12369         #[test]
12370         fn test_anchors_zero_fee_htlc_tx_fallback() {
12371                 // Tests that if both nodes support anchors, but the remote node does not want to accept
12372                 // anchor channels at the moment, an error it sent to the local node such that it can retry
12373                 // the channel without the anchors feature.
12374                 let chanmon_cfgs = create_chanmon_cfgs(2);
12375                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
12376                 let mut anchors_config = test_default_channel_config();
12377                 anchors_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx = true;
12378                 anchors_config.manually_accept_inbound_channels = true;
12379                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(anchors_config.clone()), Some(anchors_config.clone())]);
12380                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
12381
12382                 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 0, None, None).unwrap();
12383                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12384                 assert!(open_channel_msg.channel_type.as_ref().unwrap().supports_anchors_zero_fee_htlc_tx());
12385
12386                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
12387                 let events = nodes[1].node.get_and_clear_pending_events();
12388                 match events[0] {
12389                         Event::OpenChannelRequest { temporary_channel_id, .. } => {
12390                                 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
12391                         }
12392                         _ => panic!("Unexpected event"),
12393                 }
12394
12395                 let error_msg = get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id());
12396                 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &error_msg);
12397
12398                 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
12399                 assert!(!open_channel_msg.channel_type.unwrap().supports_anchors_zero_fee_htlc_tx());
12400
12401                 // Since nodes[1] should not have accepted the channel, it should
12402                 // not have generated any events.
12403                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
12404         }
12405
12406         #[test]
12407         fn test_update_channel_config() {
12408                 let chanmon_cfg = create_chanmon_cfgs(2);
12409                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12410                 let mut user_config = test_default_channel_config();
12411                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12412                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12413                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
12414                 let channel = &nodes[0].node.list_channels()[0];
12415
12416                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12417                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12418                 assert_eq!(events.len(), 0);
12419
12420                 user_config.channel_config.forwarding_fee_base_msat += 10;
12421                 nodes[0].node.update_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &user_config.channel_config).unwrap();
12422                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_base_msat, user_config.channel_config.forwarding_fee_base_msat);
12423                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12424                 assert_eq!(events.len(), 1);
12425                 match &events[0] {
12426                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12427                         _ => panic!("expected BroadcastChannelUpdate event"),
12428                 }
12429
12430                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate::default()).unwrap();
12431                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12432                 assert_eq!(events.len(), 0);
12433
12434                 let new_cltv_expiry_delta = user_config.channel_config.cltv_expiry_delta + 6;
12435                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12436                         cltv_expiry_delta: Some(new_cltv_expiry_delta),
12437                         ..Default::default()
12438                 }).unwrap();
12439                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12440                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12441                 assert_eq!(events.len(), 1);
12442                 match &events[0] {
12443                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12444                         _ => panic!("expected BroadcastChannelUpdate event"),
12445                 }
12446
12447                 let new_fee = user_config.channel_config.forwarding_fee_proportional_millionths + 100;
12448                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id], &ChannelConfigUpdate {
12449                         forwarding_fee_proportional_millionths: Some(new_fee),
12450                         ..Default::default()
12451                 }).unwrap();
12452                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().cltv_expiry_delta, new_cltv_expiry_delta);
12453                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, new_fee);
12454                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12455                 assert_eq!(events.len(), 1);
12456                 match &events[0] {
12457                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
12458                         _ => panic!("expected BroadcastChannelUpdate event"),
12459                 }
12460
12461                 // If we provide a channel_id not associated with the peer, we should get an error and no updates
12462                 // should be applied to ensure update atomicity as specified in the API docs.
12463                 let bad_channel_id = ChannelId::v1_from_funding_txid(&[10; 32], 10);
12464                 let current_fee = nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths;
12465                 let new_fee = current_fee + 100;
12466                 assert!(
12467                         matches!(
12468                                 nodes[0].node.update_partial_channel_config(&channel.counterparty.node_id, &[channel.channel_id, bad_channel_id], &ChannelConfigUpdate {
12469                                         forwarding_fee_proportional_millionths: Some(new_fee),
12470                                         ..Default::default()
12471                                 }),
12472                                 Err(APIError::ChannelUnavailable { err: _ }),
12473                         )
12474                 );
12475                 // Check that the fee hasn't changed for the channel that exists.
12476                 assert_eq!(nodes[0].node.list_channels()[0].config.unwrap().forwarding_fee_proportional_millionths, current_fee);
12477                 let events = nodes[0].node.get_and_clear_pending_msg_events();
12478                 assert_eq!(events.len(), 0);
12479         }
12480
12481         #[test]
12482         fn test_payment_display() {
12483                 let payment_id = PaymentId([42; 32]);
12484                 assert_eq!(format!("{}", &payment_id), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12485                 let payment_hash = PaymentHash([42; 32]);
12486                 assert_eq!(format!("{}", &payment_hash), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12487                 let payment_preimage = PaymentPreimage([42; 32]);
12488                 assert_eq!(format!("{}", &payment_preimage), "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a");
12489         }
12490
12491         #[test]
12492         fn test_trigger_lnd_force_close() {
12493                 let chanmon_cfg = create_chanmon_cfgs(2);
12494                 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
12495                 let user_config = test_default_channel_config();
12496                 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[Some(user_config), Some(user_config)]);
12497                 let nodes = create_network(2, &node_cfg, &node_chanmgr);
12498
12499                 // Open a channel, immediately disconnect each other, and broadcast Alice's latest state.
12500                 let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
12501                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
12502                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
12503                 nodes[0].node.force_close_broadcasting_latest_txn(&chan_id, &nodes[1].node.get_our_node_id()).unwrap();
12504                 check_closed_broadcast(&nodes[0], 1, true);
12505                 check_added_monitors(&nodes[0], 1);
12506                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
12507                 {
12508                         let txn = nodes[0].tx_broadcaster.txn_broadcast();
12509                         assert_eq!(txn.len(), 1);
12510                         check_spends!(txn[0], funding_tx);
12511                 }
12512
12513                 // Since they're disconnected, Bob won't receive Alice's `Error` message. Reconnect them
12514                 // such that Bob sends a `ChannelReestablish` to Alice since the channel is still open from
12515                 // their side.
12516                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
12517                         features: nodes[1].node.init_features(), networks: None, remote_network_address: None
12518                 }, true).unwrap();
12519                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
12520                         features: nodes[0].node.init_features(), networks: None, remote_network_address: None
12521                 }, false).unwrap();
12522                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
12523                 let channel_reestablish = get_event_msg!(
12524                         nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()
12525                 );
12526                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &channel_reestablish);
12527
12528                 // Alice should respond with an error since the channel isn't known, but a bogus
12529                 // `ChannelReestablish` should be sent first, such that we actually trigger Bob to force
12530                 // close even if it was an lnd node.
12531                 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
12532                 assert_eq!(msg_events.len(), 2);
12533                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = &msg_events[0] {
12534                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
12535                         assert_eq!(msg.next_local_commitment_number, 0);
12536                         assert_eq!(msg.next_remote_commitment_number, 0);
12537                         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &msg);
12538                 } else { panic!() };
12539                 check_closed_broadcast(&nodes[1], 1, true);
12540                 check_added_monitors(&nodes[1], 1);
12541                 let expected_close_reason = ClosureReason::ProcessingError {
12542                         err: "Peer sent an invalid channel_reestablish to force close in a non-standard way".to_string()
12543                 };
12544                 check_closed_event!(nodes[1], 1, expected_close_reason, [nodes[0].node.get_our_node_id()], 100000);
12545                 {
12546                         let txn = nodes[1].tx_broadcaster.txn_broadcast();
12547                         assert_eq!(txn.len(), 1);
12548                         check_spends!(txn[0], funding_tx);
12549                 }
12550         }
12551
12552         #[test]
12553         fn test_malformed_forward_htlcs_ser() {
12554                 // Ensure that `HTLCForwardInfo::FailMalformedHTLC`s are (de)serialized properly.
12555                 let chanmon_cfg = create_chanmon_cfgs(1);
12556                 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
12557                 let persister;
12558                 let chain_monitor;
12559                 let chanmgrs = create_node_chanmgrs(1, &node_cfg, &[None]);
12560                 let deserialized_chanmgr;
12561                 let mut nodes = create_network(1, &node_cfg, &chanmgrs);
12562
12563                 let dummy_failed_htlc = |htlc_id| {
12564                         HTLCForwardInfo::FailHTLC { htlc_id, err_packet: msgs::OnionErrorPacket { data: vec![42] }, }
12565                 };
12566                 let dummy_malformed_htlc = |htlc_id| {
12567                         HTLCForwardInfo::FailMalformedHTLC { htlc_id, failure_code: 0x4000, sha256_of_onion: [0; 32] }
12568                 };
12569
12570                 let dummy_htlcs_1: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12571                         if htlc_id % 2 == 0 {
12572                                 dummy_failed_htlc(htlc_id)
12573                         } else {
12574                                 dummy_malformed_htlc(htlc_id)
12575                         }
12576                 }).collect();
12577
12578                 let dummy_htlcs_2: Vec<HTLCForwardInfo> = (1..10).map(|htlc_id| {
12579                         if htlc_id % 2 == 1 {
12580                                 dummy_failed_htlc(htlc_id)
12581                         } else {
12582                                 dummy_malformed_htlc(htlc_id)
12583                         }
12584                 }).collect();
12585
12586
12587                 let (scid_1, scid_2) = (42, 43);
12588                 let mut forward_htlcs = HashMap::new();
12589                 forward_htlcs.insert(scid_1, dummy_htlcs_1.clone());
12590                 forward_htlcs.insert(scid_2, dummy_htlcs_2.clone());
12591
12592                 let mut chanmgr_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12593                 *chanmgr_fwd_htlcs = forward_htlcs.clone();
12594                 core::mem::drop(chanmgr_fwd_htlcs);
12595
12596                 reload_node!(nodes[0], nodes[0].node.encode(), &[], persister, chain_monitor, deserialized_chanmgr);
12597
12598                 let mut deserialized_fwd_htlcs = nodes[0].node.forward_htlcs.lock().unwrap();
12599                 for scid in [scid_1, scid_2].iter() {
12600                         let deserialized_htlcs = deserialized_fwd_htlcs.remove(scid).unwrap();
12601                         assert_eq!(forward_htlcs.remove(scid).unwrap(), deserialized_htlcs);
12602                 }
12603                 assert!(deserialized_fwd_htlcs.is_empty());
12604                 core::mem::drop(deserialized_fwd_htlcs);
12605
12606                 expect_pending_htlcs_forwardable!(nodes[0]);
12607         }
12608 }
12609
12610 #[cfg(ldk_bench)]
12611 pub mod bench {
12612         use crate::chain::Listen;
12613         use crate::chain::chainmonitor::{ChainMonitor, Persist};
12614         use crate::sign::{KeysManager, InMemorySigner};
12615         use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
12616         use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
12617         use crate::ln::functional_test_utils::*;
12618         use crate::ln::msgs::{ChannelMessageHandler, Init};
12619         use crate::routing::gossip::NetworkGraph;
12620         use crate::routing::router::{PaymentParameters, RouteParameters};
12621         use crate::util::test_utils;
12622         use crate::util::config::{UserConfig, MaxDustHTLCExposure};
12623
12624         use bitcoin::blockdata::locktime::absolute::LockTime;
12625         use bitcoin::hashes::Hash;
12626         use bitcoin::hashes::sha256::Hash as Sha256;
12627         use bitcoin::{Transaction, TxOut};
12628
12629         use crate::sync::{Arc, Mutex, RwLock};
12630
12631         use criterion::Criterion;
12632
12633         type Manager<'a, P> = ChannelManager<
12634                 &'a ChainMonitor<InMemorySigner, &'a test_utils::TestChainSource,
12635                         &'a test_utils::TestBroadcaster, &'a test_utils::TestFeeEstimator,
12636                         &'a test_utils::TestLogger, &'a P>,
12637                 &'a test_utils::TestBroadcaster, &'a KeysManager, &'a KeysManager, &'a KeysManager,
12638                 &'a test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'a>,
12639                 &'a test_utils::TestLogger>;
12640
12641         struct ANodeHolder<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> {
12642                 node: &'node_cfg Manager<'chan_mon_cfg, P>,
12643         }
12644         impl<'node_cfg, 'chan_mon_cfg: 'node_cfg, P: Persist<InMemorySigner>> NodeHolder for ANodeHolder<'node_cfg, 'chan_mon_cfg, P> {
12645                 type CM = Manager<'chan_mon_cfg, P>;
12646                 #[inline]
12647                 fn node(&self) -> &Manager<'chan_mon_cfg, P> { self.node }
12648                 #[inline]
12649                 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { None }
12650         }
12651
12652         pub fn bench_sends(bench: &mut Criterion) {
12653                 bench_two_sends(bench, "bench_sends", test_utils::TestPersister::new(), test_utils::TestPersister::new());
12654         }
12655
12656         pub fn bench_two_sends<P: Persist<InMemorySigner>>(bench: &mut Criterion, bench_name: &str, persister_a: P, persister_b: P) {
12657                 // Do a simple benchmark of sending a payment back and forth between two nodes.
12658                 // Note that this is unrealistic as each payment send will require at least two fsync
12659                 // calls per node.
12660                 let network = bitcoin::Network::Testnet;
12661                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
12662
12663                 let tx_broadcaster = test_utils::TestBroadcaster::new(network);
12664                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
12665                 let logger_a = test_utils::TestLogger::with_id("node a".to_owned());
12666                 let scorer = RwLock::new(test_utils::TestScorer::new());
12667                 let router = test_utils::TestRouter::new(Arc::new(NetworkGraph::new(network, &logger_a)), &logger_a, &scorer);
12668
12669                 let mut config: UserConfig = Default::default();
12670                 config.channel_config.max_dust_htlc_exposure = MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253);
12671                 config.channel_handshake_config.minimum_depth = 1;
12672
12673                 let chain_monitor_a = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_a);
12674                 let seed_a = [1u8; 32];
12675                 let keys_manager_a = KeysManager::new(&seed_a, 42, 42);
12676                 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 {
12677                         network,
12678                         best_block: BestBlock::from_network(network),
12679                 }, genesis_block.header.time);
12680                 let node_a_holder = ANodeHolder { node: &node_a };
12681
12682                 let logger_b = test_utils::TestLogger::with_id("node a".to_owned());
12683                 let chain_monitor_b = ChainMonitor::new(None, &tx_broadcaster, &logger_a, &fee_estimator, &persister_b);
12684                 let seed_b = [2u8; 32];
12685                 let keys_manager_b = KeysManager::new(&seed_b, 42, 42);
12686                 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 {
12687                         network,
12688                         best_block: BestBlock::from_network(network),
12689                 }, genesis_block.header.time);
12690                 let node_b_holder = ANodeHolder { node: &node_b };
12691
12692                 node_a.peer_connected(&node_b.get_our_node_id(), &Init {
12693                         features: node_b.init_features(), networks: None, remote_network_address: None
12694                 }, true).unwrap();
12695                 node_b.peer_connected(&node_a.get_our_node_id(), &Init {
12696                         features: node_a.init_features(), networks: None, remote_network_address: None
12697                 }, false).unwrap();
12698                 node_a.create_channel(node_b.get_our_node_id(), 8_000_000, 100_000_000, 42, None, None).unwrap();
12699                 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()));
12700                 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()));
12701
12702                 let tx;
12703                 if let Event::FundingGenerationReady { temporary_channel_id, output_script, .. } = get_event!(node_a_holder, Event::FundingGenerationReady) {
12704                         tx = Transaction { version: 2, lock_time: LockTime::ZERO, input: Vec::new(), output: vec![TxOut {
12705                                 value: 8_000_000, script_pubkey: output_script,
12706                         }]};
12707                         node_a.funding_transaction_generated(&temporary_channel_id, &node_b.get_our_node_id(), tx.clone()).unwrap();
12708                 } else { panic!(); }
12709
12710                 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()));
12711                 let events_b = node_b.get_and_clear_pending_events();
12712                 assert_eq!(events_b.len(), 1);
12713                 match events_b[0] {
12714                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12715                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12716                         },
12717                         _ => panic!("Unexpected event"),
12718                 }
12719
12720                 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()));
12721                 let events_a = node_a.get_and_clear_pending_events();
12722                 assert_eq!(events_a.len(), 1);
12723                 match events_a[0] {
12724                         Event::ChannelPending{ ref counterparty_node_id, .. } => {
12725                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12726                         },
12727                         _ => panic!("Unexpected event"),
12728                 }
12729
12730                 assert_eq!(&tx_broadcaster.txn_broadcasted.lock().unwrap()[..], &[tx.clone()]);
12731
12732                 let block = create_dummy_block(BestBlock::from_network(network).block_hash(), 42, vec![tx]);
12733                 Listen::block_connected(&node_a, &block, 1);
12734                 Listen::block_connected(&node_b, &block, 1);
12735
12736                 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()));
12737                 let msg_events = node_a.get_and_clear_pending_msg_events();
12738                 assert_eq!(msg_events.len(), 2);
12739                 match msg_events[0] {
12740                         MessageSendEvent::SendChannelReady { ref msg, .. } => {
12741                                 node_b.handle_channel_ready(&node_a.get_our_node_id(), msg);
12742                                 get_event_msg!(node_b_holder, MessageSendEvent::SendChannelUpdate, node_a.get_our_node_id());
12743                         },
12744                         _ => panic!(),
12745                 }
12746                 match msg_events[1] {
12747                         MessageSendEvent::SendChannelUpdate { .. } => {},
12748                         _ => panic!(),
12749                 }
12750
12751                 let events_a = node_a.get_and_clear_pending_events();
12752                 assert_eq!(events_a.len(), 1);
12753                 match events_a[0] {
12754                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12755                                 assert_eq!(*counterparty_node_id, node_b.get_our_node_id());
12756                         },
12757                         _ => panic!("Unexpected event"),
12758                 }
12759
12760                 let events_b = node_b.get_and_clear_pending_events();
12761                 assert_eq!(events_b.len(), 1);
12762                 match events_b[0] {
12763                         Event::ChannelReady{ ref counterparty_node_id, .. } => {
12764                                 assert_eq!(*counterparty_node_id, node_a.get_our_node_id());
12765                         },
12766                         _ => panic!("Unexpected event"),
12767                 }
12768
12769                 let mut payment_count: u64 = 0;
12770                 macro_rules! send_payment {
12771                         ($node_a: expr, $node_b: expr) => {
12772                                 let payment_params = PaymentParameters::from_node_id($node_b.get_our_node_id(), TEST_FINAL_CLTV)
12773                                         .with_bolt11_features($node_b.bolt11_invoice_features()).unwrap();
12774                                 let mut payment_preimage = PaymentPreimage([0; 32]);
12775                                 payment_preimage.0[0..8].copy_from_slice(&payment_count.to_le_bytes());
12776                                 payment_count += 1;
12777                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).to_byte_array());
12778                                 let payment_secret = $node_b.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
12779
12780                                 $node_a.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
12781                                         PaymentId(payment_hash.0),
12782                                         RouteParameters::from_payment_params_and_value(payment_params, 10_000),
12783                                         Retry::Attempts(0)).unwrap();
12784                                 let payment_event = SendEvent::from_event($node_a.get_and_clear_pending_msg_events().pop().unwrap());
12785                                 $node_b.handle_update_add_htlc(&$node_a.get_our_node_id(), &payment_event.msgs[0]);
12786                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &payment_event.commitment_msg);
12787                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_b }, &$node_a.get_our_node_id());
12788                                 $node_a.handle_revoke_and_ack(&$node_b.get_our_node_id(), &raa);
12789                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &cs);
12790                                 $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()));
12791
12792                                 expect_pending_htlcs_forwardable!(ANodeHolder { node: &$node_b });
12793                                 expect_payment_claimable!(ANodeHolder { node: &$node_b }, payment_hash, payment_secret, 10_000);
12794                                 $node_b.claim_funds(payment_preimage);
12795                                 expect_payment_claimed!(ANodeHolder { node: &$node_b }, payment_hash, 10_000);
12796
12797                                 match $node_b.get_and_clear_pending_msg_events().pop().unwrap() {
12798                                         MessageSendEvent::UpdateHTLCs { node_id, updates } => {
12799                                                 assert_eq!(node_id, $node_a.get_our_node_id());
12800                                                 $node_a.handle_update_fulfill_htlc(&$node_b.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
12801                                                 $node_a.handle_commitment_signed(&$node_b.get_our_node_id(), &updates.commitment_signed);
12802                                         },
12803                                         _ => panic!("Failed to generate claim event"),
12804                                 }
12805
12806                                 let (raa, cs) = get_revoke_commit_msgs(&ANodeHolder { node: &$node_a }, &$node_b.get_our_node_id());
12807                                 $node_b.handle_revoke_and_ack(&$node_a.get_our_node_id(), &raa);
12808                                 $node_b.handle_commitment_signed(&$node_a.get_our_node_id(), &cs);
12809                                 $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()));
12810
12811                                 expect_payment_sent!(ANodeHolder { node: &$node_a }, payment_preimage);
12812                         }
12813                 }
12814
12815                 bench.bench_function(bench_name, |b| b.iter(|| {
12816                         send_payment!(node_a, node_b);
12817                         send_payment!(node_b, node_a);
12818                 }));
12819         }
12820 }